# # Copyright (C) 2005, 2006, 2007, 2008 Nikolas Zimmermann # Copyright (C) 2006 Anders Carlsson # Copyright (C) 2006, 2007 Samuel Weinig # Copyright (C) 2006 Alexey Proskuryakov # Copyright (C) 2006-2010, 2013-2016 Apple Inc. All rights reserved. # Copyright (C) 2009 Cameron McCormack # Copyright (C) Research In Motion Limited 2010. All rights reserved. # Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) # Copyright (C) 2011 Patrick Gansterer # Copyright (C) 2012 Ericsson AB. All rights reserved. # Copyright (C) 2007, 2008, 2009, 2012 Google Inc. # Copyright (C) 2013 Samsung Electronics. All rights reserved. # Copyright (C) 2015, 2016 Canon Inc. All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public License # along with this library; see the file COPYING.LIB. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301, USA. package CodeGeneratorJS; use strict; use constant FileNamePrefix => "JS"; use Hasher; my $codeGenerator; my @headerContentHeader = (); my @headerContent = (); my %headerIncludes = (); my %headerTrailingIncludes = (); my @implContentHeader = (); my @implContent = (); my %implIncludes = (); my @depsContent = (); my $numCachedAttributes = 0; my $currentCachedAttribute = 0; my $beginAppleCopyrightForHeaderFiles = <LinkOverloadedFunctions($interface); if ($interface->isCallback) { $object->GenerateCallbackHeader($interface); $object->GenerateCallbackImplementation($interface, $enumerations, $dictionaries); } else { $object->GenerateHeader($interface); $object->GenerateImplementation($interface, $enumerations, $dictionaries); } } sub EventHandlerAttributeEventName { my $attribute = shift; my $eventType = $attribute->signature->extendedAttributes->{"ImplementedAs"} || $attribute->signature->name; # Remove the "on" prefix. $eventType = substr($eventType, 2); return "eventNames().${eventType}Event"; } sub GetParentClassName { my $interface = shift; return $interface->extendedAttributes->{"JSLegacyParent"} if $interface->extendedAttributes->{"JSLegacyParent"}; return "JSDOMObject" unless NeedsImplementationClass($interface); return "JSDOMWrapper<" . GetImplClassName($interface->name) . ">" unless $interface->parent; return "JS" . $interface->parent; } sub GetCallbackClassName { my $className = shift; return "JS$className"; } sub GetJSCallbackDataType { my $callbackInterface = shift; return $callbackInterface->extendedAttributes->{"IsWeakCallback"} ? "JSCallbackDataWeak" : "JSCallbackDataStrong"; } sub AddIncludesForTypeInImpl { my $type = shift; my $isCallback = @_ ? shift : 0; AddIncludesForType($type, $isCallback, \%implIncludes); } sub AddIncludesForTypeInHeader { my $type = shift; my $isCallback = @_ ? shift : 0; AddIncludesForType($type, $isCallback, \%headerIncludes); } sub GetExportMacroForJSClass { my $interface = shift; return $interface->extendedAttributes->{"ExportMacro"} . " " if $interface->extendedAttributes->{"ExportMacro"}; return ""; } sub AddIncludesForType { my $type = shift; my $isCallback = shift; my $includesRef = shift; return if $codeGenerator->SkipIncludeHeader($type); # When we're finished with the one-file-per-class reorganization, we won't need these special cases. if ($isCallback && $codeGenerator->IsWrapperType($type)) { $includesRef->{"JS${type}.h"} = 1; } elsif ($codeGenerator->GetArrayOrSequenceType($type)) { my $arrayType = $codeGenerator->GetArrayType($type); my $arrayOrSequenceType = $arrayType || $codeGenerator->GetSequenceType($type); if ($arrayType eq "DOMString") { $includesRef->{"JSDOMStringList.h"} = 1; $includesRef->{"DOMStringList.h"} = 1; } elsif ($codeGenerator->IsRefPtrType($arrayOrSequenceType)) { $includesRef->{"JS${arrayOrSequenceType}.h"} = 1; $includesRef->{"${arrayOrSequenceType}.h"} = 1; } $includesRef->{""} = 1; } else { # default, include the same named file $includesRef->{"${type}.h"} = 1; } } sub AddToImplIncludes { my $header = shift; my $conditional = shift; if (not $conditional) { $implIncludes{$header} = 1; } elsif (not exists($implIncludes{$header})) { $implIncludes{$header} = $conditional; } else { my $oldValue = $implIncludes{$header}; $implIncludes{$header} = "$oldValue|$conditional" if $oldValue ne 1; } } sub IsReadonly { my $attribute = shift; return $attribute->isReadOnly && !$attribute->signature->extendedAttributes->{"Replaceable"} && !$attribute->signature->extendedAttributes->{"PutForwards"}; } sub AddClassForwardIfNeeded { my $interfaceName = shift; # SVGAnimatedLength/Number/etc. are typedefs and should not be forward-declared as classes. return if $codeGenerator->IsSVGAnimatedType($interfaceName); return if $codeGenerator->IsTypedArrayType($interfaceName); push(@headerContent, "class $interfaceName;\n\n"); } sub GetGenerateIsReachable { my $interface = shift; return $interface->extendedAttributes->{"GenerateIsReachable"}; } sub GetCustomIsReachable { my $interface = shift; return $interface->extendedAttributes->{"CustomIsReachable"}; } sub IsDOMGlobalObject { my $interface = shift; return $interface->name eq "DOMWindow" || $codeGenerator->InheritsInterface($interface, "WorkerGlobalScope") || $interface->name eq "TestGlobalObject"; } sub ShouldUseGlobalObjectPrototype { my $interface = shift; # For workers, the global object is a DedicatedWorkerGlobalScope. return 0 if $interface->name eq "WorkerGlobalScope"; return IsDOMGlobalObject($interface); } sub GenerateGetOwnPropertySlotBody { my ($interface, $className, $inlined) = @_; my $namespaceMaybe = ($inlined ? "JSC::" : ""); my $namedGetterFunction = GetNamedGetterFunction($interface); my $indexedGetterFunction = GetIndexedGetterFunction($interface); my @getOwnPropertySlotImpl = (); my $ownPropertyCheck = sub { push(@getOwnPropertySlotImpl, " if (Base::getOwnPropertySlot(thisObject, state, propertyName, slot))\n"); push(@getOwnPropertySlotImpl, " return true;\n"); }; # FIXME: As per the Web IDL specification, the prototype check is supposed to skip "named properties objects": # https://heycam.github.io/webidl/#dfn-named-property-visibility # https://heycam.github.io/webidl/#dfn-named-properties-object my $prototypeCheck = sub { push(@getOwnPropertySlotImpl, " ${namespaceMaybe}JSValue proto = thisObject->getPrototypeDirect();\n"); push(@getOwnPropertySlotImpl, " if (proto.isObject() && jsCast<${namespaceMaybe}JSObject*>(proto)->hasProperty(state, propertyName))\n"); push(@getOwnPropertySlotImpl, " return false;\n\n"); }; if ($indexedGetterFunction) { push(@getOwnPropertySlotImpl, " Optional optionalIndex = parseIndex(propertyName);\n"); # If the item function returns a string then we let the TreatReturnedNullStringAs handle the cases # where the index is out of range. if ($indexedGetterFunction->signature->type eq "DOMString") { push(@getOwnPropertySlotImpl, " if (optionalIndex) {\n"); } else { push(@getOwnPropertySlotImpl, " if (optionalIndex && optionalIndex.value() < thisObject->wrapped().length()) {\n"); } push(@getOwnPropertySlotImpl, " unsigned index = optionalIndex.value();\n"); # Assume that if there's a setter, the index will be writable if ($interface->extendedAttributes->{"CustomIndexedSetter"}) { push(@getOwnPropertySlotImpl, " unsigned attributes = ${namespaceMaybe}DontDelete;\n"); } else { push(@getOwnPropertySlotImpl, " unsigned attributes = ${namespaceMaybe}DontDelete | ${namespaceMaybe}ReadOnly;\n"); } push(@getOwnPropertySlotImpl, " slot.setValue(thisObject, attributes, " . GetIndexedGetterExpression($indexedGetterFunction) . ");\n"); push(@getOwnPropertySlotImpl, " return true;\n"); push(@getOwnPropertySlotImpl, " }\n"); } my $hasNamedGetter = $namedGetterFunction || $interface->extendedAttributes->{"CustomNamedGetter"}; if ($hasNamedGetter) { if (!$interface->extendedAttributes->{"OverrideBuiltins"}) { &$ownPropertyCheck(); &$prototypeCheck(); } # The "thisObject->classInfo() == info()" check is to make sure we use the subclass' named getter # instead of the base class one when possible. if ($indexedGetterFunction) { # Indexing an object with an integer that is not a supported property index should not call the named property getter. # https://heycam.github.io/webidl/#idl-indexed-properties push(@getOwnPropertySlotImpl, " if (!optionalIndex && thisObject->classInfo() == info()) {\n"); } else { push(@getOwnPropertySlotImpl, " if (thisObject->classInfo() == info()) {\n"); } push(@getOwnPropertySlotImpl, " JSValue value;\n"); push(@getOwnPropertySlotImpl, " if (thisObject->nameGetter(state, propertyName, value)) {\n"); push(@getOwnPropertySlotImpl, " slot.setValue(thisObject, ReadOnly | DontDelete | DontEnum, value);\n"); push(@getOwnPropertySlotImpl, " return true;\n"); push(@getOwnPropertySlotImpl, " }\n"); push(@getOwnPropertySlotImpl, " }\n"); if ($inlined) { $headerIncludes{"wtf/text/AtomicString.h"} = 1; } else { $implIncludes{"wtf/text/AtomicString.h"} = 1; } } if ($interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}) { push(@getOwnPropertySlotImpl, " if (thisObject->getOwnPropertySlotDelegate(state, propertyName, slot))\n"); push(@getOwnPropertySlotImpl, " return true;\n"); } if (!$hasNamedGetter || $interface->extendedAttributes->{"OverrideBuiltins"}) { &$ownPropertyCheck(); } push(@getOwnPropertySlotImpl, " return false;\n"); return @getOwnPropertySlotImpl; } sub GenerateHeaderContentHeader { my $interface = shift; my $className = "JS" . $interface->name; my @headerContentHeader; if ($interface->extendedAttributes->{"AppleCopyright"}) { @headerContentHeader = split("\r", $beginAppleCopyrightForHeaderFiles); } else { @headerContentHeader = split("\r", $headerTemplate); } push(@headerContentHeader, "\n#pragma once\n\n"); my $conditionalString = $codeGenerator->GenerateConditionalString($interface); push(@headerContentHeader, "#if ${conditionalString}\n\n") if $conditionalString; return @headerContentHeader; } sub GenerateImplementationContentHeader { my $interface = shift; my $className = "JS" . $interface->name; my @implContentHeader; if ($interface->extendedAttributes->{"AppleCopyright"}) { @implContentHeader = split("\r", $beginAppleCopyrightForSourceFiles); } else { @implContentHeader = split("\r", $headerTemplate); } push(@implContentHeader, "\n#include \"config.h\"\n"); my $conditionalString = $codeGenerator->GenerateConditionalString($interface); push(@implContentHeader, "\n#if ${conditionalString}\n\n") if $conditionalString; push(@implContentHeader, "#include \"$className.h\"\n\n"); return @implContentHeader; } sub NeedsImplementationClass { my ($interface) = @_; return 0 if $interface->extendedAttributes->{"JSBuiltin"}; return 1; } sub ShouldGenerateToWrapped { my ($hasParent, $interface) = @_; return 0 if not NeedsImplementationClass($interface); return 1 if !$hasParent or $interface->extendedAttributes->{"JSGenerateToNativeObject"}; return 1 if $interface->parent && $interface->parent eq "EventTarget"; return 0; } sub ShouldGenerateWrapperOwnerCode { my ($hasParent, $interface) = @_; return 0 if not NeedsImplementationClass($interface); if (!$hasParent || GetGenerateIsReachable($interface) || GetCustomIsReachable($interface) || $interface->extendedAttributes->{"JSCustomFinalize"} || $codeGenerator->InheritsExtendedAttribute($interface, "ActiveDOMObject")) { return 1; } return 0; } sub ShouldGenerateToJSDeclaration { my ($hasParent, $interface) = @_; return 0 if ($interface->extendedAttributes->{"SuppressToJSObject"}); return 0 if not NeedsImplementationClass($interface); return 0 if $interface->name eq "AbstractView"; return 0 if $interface->extendedAttributes->{"CustomProxyToJSObject"}; return 1 if (!$hasParent or $interface->extendedAttributes->{"JSGenerateToJSObject"} or $interface->extendedAttributes->{"CustomToJSObject"}); return 1 if $interface->parent && $interface->parent eq "EventTarget"; return 1 if $interface->extendedAttributes->{"Constructor"} or $interface->extendedAttributes->{"NamedConstructor"}; return 0; } sub ShouldGenerateToJSImplementation { my ($hasParent, $interface) = @_; return 0 if not ShouldGenerateToJSDeclaration($hasParent, $interface); return 1 if not $interface->extendedAttributes->{"CustomToJSObject"}; return 0; } sub GetAttributeGetterName { my ($interface, $className, $attribute) = @_; return $codeGenerator->WK_lcfirst($className) . "Constructor" . $codeGenerator->WK_ucfirst($attribute->signature->name) if $attribute->isStatic; return GetJSBuiltinFunctionName($className, $attribute) if IsJSBuiltin($interface, $attribute); return "js" . $interface->name . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : ""); } sub GetAttributeSetterName { my ($interface, $className, $attribute) = @_; return "set" . $codeGenerator->WK_ucfirst($className) . "Constructor" . $codeGenerator->WK_ucfirst($attribute->signature->name) if $attribute->isStatic; return "set" . $codeGenerator->WK_ucfirst(GetJSBuiltinFunctionName($className, $attribute)) if IsJSBuiltin($interface, $attribute); return "setJS" . $interface->name . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : ""); } sub GetFunctionName { my ($interface, $className, $function) = @_; return GetJSBuiltinFunctionName($className, $function) if IsJSBuiltin($interface, $function); my $functionName = $function->signature->name; $functionName = "SymbolIterator" if $functionName eq "[Symbol.Iterator]"; my $kind = $function->isStatic ? "Constructor" : (OperationShouldBeOnInstance($interface, $function) ? "Instance" : "Prototype"); return $codeGenerator->WK_lcfirst($className) . $kind . "Function" . $codeGenerator->WK_ucfirst($functionName); } sub GetSpecialAccessorFunctionForType { my $interface = shift; my $special = shift; my $firstParameterType = shift; my $numberOfParameters = shift; foreach my $function (@{$interface->functions}, @{$interface->anonymousFunctions}) { my $specials = $function->signature->specials; my $specialExists = grep { $_ eq $special } @$specials; my $parameters = $function->parameters; if ($specialExists and scalar(@$parameters) == $numberOfParameters and $parameters->[0]->type eq $firstParameterType) { return $function; } } return 0; } sub HasComplexGetOwnProperty { my $interface = shift; my $namedGetterFunction = GetNamedGetterFunction($interface); my $indexedGetterFunction = GetIndexedGetterFunction($interface); my $hasNamedGetter = $namedGetterFunction || $interface->extendedAttributes->{"CustomNamedGetter"}; my $hasComplexGetter = $indexedGetterFunction || $interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"} || $interface->extendedAttributes->{"CustomGetOwnPropertySlot"} || $hasNamedGetter; return 1 if $interface->extendedAttributes->{"CheckSecurity"}; return 1 if IsDOMGlobalObject($interface); return 1 if $hasComplexGetter; return 0; } sub InterfaceRequiresAttributesOnInstanceForCompatibility { my $interface = shift; my $interfaceName = $interface->name; # Needed for compatibility with existing content return 1 if $interfaceName =~ "Touch"; return 1 if $interfaceName =~ "ClientRect"; return 0; } sub InterfaceRequiresAttributesOnInstance { my $interface = shift; my $interfaceName = $interface->name; # FIXME: All these return 1 if ... should ideally be removed. # Some of them are unavoidable due to DOM weirdness, in which case we should # add an IDL attribute for them # FIXME: We should be able to drop this once is fixed. return 1 if $interface->isException; # FIXME: Add support for [PrimaryGlobal] / [Global]. return 1 if IsDOMGlobalObject($interface) && $interface->name ne "WorkerGlobalScope"; return 1 if InterfaceRequiresAttributesOnInstanceForCompatibility($interface); return 0; } sub AttributeShouldBeOnInstance { my $interface = shift; my $attribute = shift; # FIXME: The bindings generator does not support putting runtime-enabled attributes on the instance yet (except for global objects). return 0 if $attribute->signature->extendedAttributes->{"EnabledAtRuntime"} && !IsDOMGlobalObject($interface); return 1 if InterfaceRequiresAttributesOnInstance($interface); return 1 if $attribute->signature->type =~ /Constructor$/; # [Unforgeable] attributes should be on the instance. # https://heycam.github.io/webidl/#Unforgeable return 1 if IsUnforgeable($interface, $attribute); if ($interface->extendedAttributes->{"CheckSecurity"}) { if ($attribute->signature->extendedAttributes->{"DoNotCheckSecurity"} or $attribute->signature->extendedAttributes->{"DoNotCheckSecurityOnGetter"}) { return 0; } return 1; } return 0; } # https://heycam.github.io/webidl/#es-operations sub OperationShouldBeOnInstance { my $interface = shift; my $function = shift; # FIXME: Add support for [PrimaryGlobal] / [Global]. return 1 if IsDOMGlobalObject($interface) && $interface->name ne "WorkerGlobalScope"; # FIXME: The bindings generator does not support putting runtime-enabled operations on the instance yet (except for global objects). return 0 if $function->signature->extendedAttributes->{"EnabledAtRuntime"}; # [Unforgeable] operations should be on the instance. https://heycam.github.io/webidl/#Unforgeable return 1 if IsUnforgeable($interface, $function); return 0; } sub GetJSCAttributesForAttribute { my $interface = shift; my $attribute = shift; my @specials = (); push(@specials, "DontDelete") if IsUnforgeable($interface, $attribute); # As per Web IDL specification, constructor properties on the ECMAScript global object should not be enumerable. my $is_global_constructor = $attribute->signature->type =~ /Constructor$/; push(@specials, "DontEnum") if ($attribute->signature->extendedAttributes->{"NotEnumerable"} || $is_global_constructor); push(@specials, "ReadOnly") if IsReadonly($attribute); push(@specials, "CustomAccessor") unless $is_global_constructor or IsJSBuiltin($interface, $attribute); push(@specials, "Accessor | Builtin") if IsJSBuiltin($interface, $attribute); return (@specials > 0) ? join(" | ", @specials) : "0"; } sub GetIndexedGetterFunction { my $interface = shift; return GetSpecialAccessorFunctionForType($interface, "getter", "unsigned long", 1); } sub GetNamedGetterFunction { my $interface = shift; return GetSpecialAccessorFunctionForType($interface, "getter", "DOMString", 1); } sub InstanceFunctionCount { my $interface = shift; my $count = 0; foreach my $function (@{$interface->functions}) { $count++ if OperationShouldBeOnInstance($interface, $function); } return $count; } sub PrototypeFunctionCount { my $interface = shift; my $count = 0; foreach my $function (@{$interface->functions}) { $count++ if !$function->isStatic && !OperationShouldBeOnInstance($interface, $function); } $count += scalar @{$interface->iterable->functions} if $interface->iterable; return $count; } sub InstancePropertyCount { my $interface = shift; my $count = 0; foreach my $attribute (@{$interface->attributes}) { $count++ if AttributeShouldBeOnInstance($interface, $attribute); } $count += InstanceFunctionCount($interface); return $count; } sub PrototypePropertyCount { my $interface = shift; my $count = 0; foreach my $attribute (@{$interface->attributes}) { $count++ if !AttributeShouldBeOnInstance($interface, $attribute); } $count += PrototypeFunctionCount($interface); $count++ if NeedsConstructorProperty($interface); return $count; } sub InstanceOverridesGetOwnPropertySlot { my $interface = shift; my $namedGetterFunction = GetNamedGetterFunction($interface); my $indexedGetterFunction = GetIndexedGetterFunction($interface); my $hasNamedGetter = $namedGetterFunction || $interface->extendedAttributes->{"CustomNamedGetter"}; my $hasComplexGetter = $indexedGetterFunction || $interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"} || $interface->extendedAttributes->{"CustomGetOwnPropertySlot"} || $hasNamedGetter; return $hasComplexGetter; } sub PrototypeHasStaticPropertyTable { my $interface = shift; my $numPrototypeProperties = PrototypePropertyCount($interface); my $numConstants = @{$interface->constants}; return $numConstants > 0 || $numPrototypeProperties > 0; } sub InstanceOverridesPutImplementation { my $interface = shift; return $interface->extendedAttributes->{"CustomNamedSetter"} || $interface->extendedAttributes->{"CustomIndexedSetter"}; } sub InstanceOverridesPutDeclaration { my $interface = shift; return $interface->extendedAttributes->{"CustomPutFunction"} || $interface->extendedAttributes->{"CustomNamedSetter"} || $interface->extendedAttributes->{"CustomIndexedSetter"}; } sub InstanceNeedsVisitChildren { my $interface = shift; return $interface->extendedAttributes->{"JSCustomMarkFunction"} || $codeGenerator->InheritsInterface($interface, "EventTarget") || $interface->name eq "EventTarget" || $interface->extendedAttributes->{"ReportExtraMemoryCost"} || IsJSBuiltinConstructor($interface) } sub InstanceNeedsEstimatedSize { my $interface = shift; return $interface->extendedAttributes->{"ReportExtraMemoryCost"}; } sub GetImplClassName { my $name = shift; return "DOMWindow" if $name eq "AbstractView"; my ($svgPropertyType, $svgListPropertyType, $svgNativeType) = GetSVGPropertyTypes($name); return $svgNativeType if $svgNativeType; return $name; } sub IsClassNameWordBoundary { my ($name, $i) = @_; # Interpret negative numbers as distance from end of string, just as the substr function does. $i += length($name) if $i < 0; return 0 if $i < 0; return 1 if $i == 0; return 1 if $i == length($name); return 0 if $i > length($name); my $checkString = substr($name, $i - 1); return $checkString =~ /^[^A-Z][A-Z]/ || $checkString =~ /^[A-Z][A-Z][^A-Z]/; } sub IsPrefixRemovable { my ($class, $name, $i) = @_; return IsClassNameWordBoundary($name, $i) && (IsClassNameWordBoundary($class, $i) && substr($class, 0, $i) eq substr($name, 0, $i) || IsClassNameWordBoundary($class, -$i) && substr($class, -$i) eq substr($name, 0, $i)); } sub GetNestedClassName { my ($interface, $name) = @_; my $class = GetImplClassName($interface->name); my $member = $codeGenerator->WK_ucfirst($name); # Since the enumeration name will be nested in the class name's namespace, remove any words # that happen to match the start or end of the class name. If an enumeration is named TrackType or # TextTrackType, and the class is named TextTrack, then we will get a name like TextTrack::Type. my $memberLength = length($member); my $longestPrefixLength = 0; if ($member =~ /^[A-Z]./) { for (my $i = 2; $i < $memberLength - 1; $i++) { $longestPrefixLength = $i if IsPrefixRemovable($class, $member, $i); } } $member = substr($member, $longestPrefixLength); return "${class}::$member"; } sub GetEnumerationClassName { my ($interface, $name) = @_; return GetNestedClassName($interface, $name); } sub GetEnumerationValueName { my ($name) = @_; return "EmptyString" if $name eq ""; $name = join("", map { $codeGenerator->WK_ucfirst($_) } split("-", $name)); $name = "_$name" if $name =~ /^\d/; return $name; } sub GenerateEnumerationImplementationContent { my ($interface, $enumerations) = @_; return "" unless @$enumerations; # FIXME: Could optimize this to only generate the parts of each enumeration that are actually # used, which would require iterating over everything in the interface. my $result = ""; $result .= "template Optional parse(ExecState&, JSValue);\n"; $result .= "template const char* expectedEnumerationValues();\n\n"; foreach my $enumeration (@$enumerations) { my $name = $enumeration->name; my $className = GetEnumerationClassName($interface, $name); # FIXME: A little ugly to have this be a side effect instead of a return value. AddToImplIncludes(""); my $conditionalString = $codeGenerator->GenerateConditionalString($enumeration); $result .= "#if ${conditionalString}\n\n" if $conditionalString; # Declare this instead of using "static" because it may be unused and we don't want warnings about that. $result .= "JSString* jsStringWithCache(ExecState*, $className);\n\n"; # Take an ExecState* instead of an ExecState& to match the jsStringWithCache from JSString.h. # FIXME: Change to take VM& instead of ExecState*. $result .= "JSString* jsStringWithCache(ExecState* state, $className enumerationValue)\n"; $result .= "{\n"; # FIXME: Might be nice to make this global be "const", but NeverDestroyed does not currently support that. # FIXME: Might be nice to make the entire array be NeverDestroyed instead of each value, but not sure what the syntax for that is. $result .= " static NeverDestroyed values[] = {\n"; foreach my $value (@{$enumeration->values}) { if ($value eq "") { $result .= " emptyString(),\n"; } else { $result .= " ASCIILiteral(\"$value\"),\n"; } } $result .= " };\n"; my $index = 0; foreach my $value (@{$enumeration->values}) { my $enumerationValueName = GetEnumerationValueName($value); $result .= " static_assert(static_cast(${className}::$enumerationValueName) == $index, \"${className}::$enumerationValueName is not $index as expected\");\n"; $index++; } $result .= " ASSERT(static_cast(enumerationValue) < WTF_ARRAY_LENGTH(values));\n"; $result .= " return jsStringWithCache(state, values[static_cast(enumerationValue)]);\n"; $result .= "}\n\n"; $result .= "template<> struct JSValueTraits<$className> {\n"; $result .= " static JSString* arrayJSValue(ExecState* state, JSDOMGlobalObject*, $className value) { return jsStringWithCache(state, value); }\n"; $result .= "};\n\n"; # FIXME: Change to take VM& instead of ExecState&. # FIXME: Consider using toStringOrNull to make exception checking faster. # FIXME: Consider finding a more efficient way to match against all the strings quickly. $result .= "template<> Optional<$className> parse<$className>(ExecState& state, JSValue value)\n"; $result .= "{\n"; $result .= " auto stringValue = value.toWTFString(&state);\n"; foreach my $value (@{$enumeration->values}) { my $enumerationValueName = GetEnumerationValueName($value); if ($value eq "") { $result .= " if (stringValue.isEmpty())\n"; } else { $result .= " if (stringValue == \"$value\")\n"; } $result .= " return ${className}::${enumerationValueName};\n"; } $result .= " return Nullopt;\n"; $result .= "}\n\n"; # FIXME: A little ugly to have this be a side effect instead of a return value. AddToImplIncludes("JSDOMConvert.h"); $result .= "template<> $className convert<$className>(ExecState& state, JSValue value)\n"; $result .= "{\n"; $result .= " auto result = parse<$className>(state, value);\n"; $result .= " if (UNLIKELY(!result)) {\n"; $result .= " throwTypeError(&state);\n"; $result .= " return { };\n"; $result .= " }\n"; $result .= " return result.value();\n"; $result .= "}\n\n"; $result .= "template<> inline const char* expectedEnumerationValues<$className>()\n"; $result .= "{\n"; $result .= " return \"\\\"" . join ("\\\", \\\"", @{$enumeration->values}) . "\\\"\";\n"; $result .= "}\n\n"; $result .= "#endif\n\n" if $conditionalString; } return $result; } sub GetDictionaryClassName { my ($interface, $name) = @_; return GetNestedClassName($interface, $name); } sub GenerateDefaultValue { my ($interface, $member) = @_; my $value = $member->default; if ($codeGenerator->IsEnumType($member->type)) { # FIXME: Would be nice to report an error if the value does not have quote marks around it. # FIXME: Would be nice to report an error if the value is not one of the enumeration values. my $className = GetEnumerationClassName($interface, $member->type); my $enumerationValueName = GetEnumerationValueName(substr($value, 1, -1)); $value = $className . "::" . $enumerationValueName; } return $value; } sub ShouldAllowNonFiniteForFloatingPointType { my $type = shift; die "Can only be called with floating point types" unless $codeGenerator->IsFloatingPointType($type); return $type eq "unrestricted double" || $type eq "unrestricted float"; } sub GenerateConversionRuleWithLeadingComma { my ($interface, $member) = @_; if ($codeGenerator->IsFloatingPointType($member->type)) { return ", " . (ShouldAllowNonFiniteForFloatingPointType($member->type) ? "ShouldAllowNonFinite::Yes" : "ShouldAllowNonFinite::No"); } return ", " . GetIntegerConversionConfiguration($member) if $codeGenerator->IsIntegerType($member->type); return ""; } sub GenerateDefaultValueWithLeadingComma { my ($interface, $member) = @_; return "" unless $member->isOptional && defined $member->default; return ", " . GenerateDefaultValue($interface, $member); } sub GenerateDictionaryImplementationContent { my ($interface, $dictionaries) = @_; my $result = ""; foreach my $dictionary (@$dictionaries) { my $name = $dictionary->name; my $conditionalString = $codeGenerator->GenerateConditionalString($dictionary); $result .= "#if ${conditionalString}\n\n" if $conditionalString; my $className = GetDictionaryClassName($interface, $name); # FIXME: A little ugly to have this be a side effect instead of a return value. AddToImplIncludes("JSDOMConvert.h"); my $defaultValues = ""; my $comma = ""; foreach my $member (@{$dictionary->members}) { if (!$member->isOptional) { $defaultValues = ""; last; } $defaultValues .= $comma . (defined $member->default ? GenerateDefaultValue($interface, $member) : "{ }"); $comma = ", "; } $result .= "template<> $className convert<$className>(ExecState& state, JSValue value)\n"; $result .= "{\n"; $result .= " if (value.isUndefinedOrNull())\n" if $defaultValues; $result .= " return { " . $defaultValues . " };\n" if $defaultValues; $result .= " auto* object = value.getObject();\n"; $result .= " if (UNLIKELY(!object || object->type() == RegExpObjectType)) {\n"; $result .= " throwTypeError(&state);\n"; $result .= " return { };\n"; $result .= " }\n"; my $needExceptionCheck = 0; foreach my $member (@{$dictionary->members}) { if ($needExceptionCheck) { $result .= " if (UNLIKELY(state.hadException()))\n"; $result .= " return { };\n"; } # FIXME: Eventually we will want this to share a lot more code with JSValueToNative. my $function = $member->isOptional ? "convertOptional" : "convert"; $result .= " auto " . $member->name . " = " . $function . "<" . GetNativeTypeFromSignature($interface, $member) . ">" . "(state, object->get(&state, Identifier::fromString(&state, \"" . $member->name . "\"))" . GenerateConversionRuleWithLeadingComma($interface, $member) . GenerateDefaultValueWithLeadingComma($interface, $member) . ");\n"; $needExceptionCheck = 1; } my $arguments = ""; $comma = ""; foreach my $member (@{$dictionary->members}) { $arguments .= $comma . "WTFMove(" . $member->name . ")"; $comma = ", "; } $result .= " return { " . $arguments . " };\n"; $result .= "}\n\n"; $result .= "#endif\n\n" if $conditionalString; } return $result; } sub GenerateHeader { my ($object, $interface) = @_; my $interfaceName = $interface->name; my $className = "JS$interfaceName"; my %structureFlags = (); my $hasLegacyParent = $interface->extendedAttributes->{"JSLegacyParent"}; my $hasRealParent = $interface->parent; my $hasParent = $hasLegacyParent || $hasRealParent; my $parentClassName = GetParentClassName($interface); my $needsVisitChildren = InstanceNeedsVisitChildren($interface); # - Add default header template and header protection push(@headerContentHeader, GenerateHeaderContentHeader($interface)); if ($hasParent) { $headerIncludes{"$parentClassName.h"} = 1; } else { $headerIncludes{"JSDOMWrapper.h"} = 1; if ($interface->isException) { $headerIncludes{""} = 1; } } if ($interface->extendedAttributes->{"CustomCall"}) { $headerIncludes{""} = 1; } if ($hasParent && $interface->extendedAttributes->{"JSGenerateToNativeObject"}) { $headerIncludes{"$interfaceName.h"} = 1; } $headerIncludes{"SVGElement.h"} = 1 if $className =~ /^JSSVG/; my $implType = GetImplClassName($interfaceName); my ($svgPropertyType, $svgListPropertyType, $svgNativeType) = GetSVGPropertyTypes($interfaceName); my $svgPropertyOrListPropertyType; $svgPropertyOrListPropertyType = $svgPropertyType if $svgPropertyType; $svgPropertyOrListPropertyType = $svgListPropertyType if $svgListPropertyType; my $numConstants = @{$interface->constants}; my $numAttributes = @{$interface->attributes}; my $numFunctions = @{$interface->functions}; push(@headerContent, "\nnamespace WebCore {\n\n"); if ($codeGenerator->IsSVGAnimatedType($interfaceName)) { $headerIncludes{"$interfaceName.h"} = 1; } else { # Implementation class forward declaration if (IsDOMGlobalObject($interface)) { AddClassForwardIfNeeded($interfaceName) unless $svgPropertyOrListPropertyType; } } AddClassForwardIfNeeded("JSDOMWindowShell") if $interfaceName eq "DOMWindow"; AddClassForwardIfNeeded("JSDictionary") if $codeGenerator->IsConstructorTemplate($interface, "Event"); my $exportMacro = GetExportMacroForJSClass($interface); # Class declaration push(@headerContent, "class $exportMacro$className : public $parentClassName {\n"); # Static create methods push(@headerContent, "public:\n"); push(@headerContent, " typedef $parentClassName Base;\n"); push(@headerContent, " typedef $implType DOMWrapped;\n") if $interface->parent; if ($interfaceName eq "DOMWindow") { push(@headerContent, " static $className* create(JSC::VM& vm, JSC::Structure* structure, Ref<$implType>&& impl, JSDOMWindowShell* windowShell)\n"); push(@headerContent, " {\n"); push(@headerContent, " $className* ptr = new (NotNull, JSC::allocateCell<$className>(vm.heap)) ${className}(vm, structure, WTFMove(impl), windowShell);\n"); push(@headerContent, " ptr->finishCreation(vm, windowShell);\n"); push(@headerContent, " vm.heap.addFinalizer(ptr, destroy);\n"); push(@headerContent, " return ptr;\n"); push(@headerContent, " }\n\n"); } elsif ($codeGenerator->InheritsInterface($interface, "WorkerGlobalScope")) { push(@headerContent, " static $className* create(JSC::VM& vm, JSC::Structure* structure, Ref<$implType>&& impl, JSC::JSProxy* proxy)\n"); push(@headerContent, " {\n"); push(@headerContent, " $className* ptr = new (NotNull, JSC::allocateCell<$className>(vm.heap)) ${className}(vm, structure, WTFMove(impl));\n"); push(@headerContent, " ptr->finishCreation(vm, proxy);\n"); push(@headerContent, " vm.heap.addFinalizer(ptr, destroy);\n"); push(@headerContent, " return ptr;\n"); push(@headerContent, " }\n\n"); } elsif ($interface->extendedAttributes->{"MasqueradesAsUndefined"}) { AddIncludesForTypeInHeader($implType) unless $svgPropertyOrListPropertyType; push(@headerContent, " static $className* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject, Ref<$implType>&& impl)\n"); push(@headerContent, " {\n"); push(@headerContent, " globalObject->masqueradesAsUndefinedWatchpoint()->fireAll(globalObject->vm(), \"Allocated masquerading object\");\n"); push(@headerContent, " $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalObject->vm().heap)) $className(structure, *globalObject, WTFMove(impl));\n"); push(@headerContent, " ptr->finishCreation(globalObject->vm());\n"); push(@headerContent, " return ptr;\n"); push(@headerContent, " }\n\n"); } elsif (!NeedsImplementationClass($interface)) { push(@headerContent, " static $className* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject)\n"); push(@headerContent, " {\n"); push(@headerContent, " $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalObject->vm().heap)) $className(structure, *globalObject);\n"); push(@headerContent, " ptr->finishCreation(globalObject->vm());\n"); push(@headerContent, " return ptr;\n"); push(@headerContent, " }\n\n"); } else { AddIncludesForTypeInHeader($implType) unless $svgPropertyOrListPropertyType; push(@headerContent, " static $className* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject, Ref<$implType>&& impl)\n"); push(@headerContent, " {\n"); push(@headerContent, " $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalObject->vm().heap)) $className(structure, *globalObject, WTFMove(impl));\n"); push(@headerContent, " ptr->finishCreation(globalObject->vm());\n"); push(@headerContent, " return ptr;\n"); push(@headerContent, " }\n\n"); } if (IsDOMGlobalObject($interface)) { push(@headerContent, " static const bool needsDestruction = false;\n\n"); } if (InstancePropertyCount($interface) > 0) { $structureFlags{"JSC::HasStaticPropertyTable"} = 1; } # Prototype unless (ShouldUseGlobalObjectPrototype($interface)) { push(@headerContent, " static JSC::JSObject* createPrototype(JSC::VM&, JSC::JSGlobalObject*);\n"); push(@headerContent, " static JSC::JSObject* prototype(JSC::VM&, JSC::JSGlobalObject*);\n"); } # JSValue to implementation type if (ShouldGenerateToWrapped($hasParent, $interface)) { my $nativeType = GetNativeType($interface, $implType); if ($interface->extendedAttributes->{"JSCustomToNativeObject"}) { push(@headerContent, " static $nativeType toWrapped(JSC::ExecState&, JSC::JSValue);\n"); } else { push(@headerContent, " static $nativeType toWrapped(JSC::JSValue);\n"); } } $headerTrailingIncludes{"${className}Custom.h"} = 1 if $interface->extendedAttributes->{"JSCustomHeader"}; my $namedGetterFunction = GetNamedGetterFunction($interface); my $indexedGetterFunction = GetIndexedGetterFunction($interface); my $hasNamedGetter = $namedGetterFunction || $interface->extendedAttributes->{"CustomNamedGetter"}; my $hasComplexGetter = $indexedGetterFunction || $interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"} || $interface->extendedAttributes->{"CustomGetOwnPropertySlot"} || $hasNamedGetter; my $hasGetter = InstanceOverridesGetOwnPropertySlot($interface); if ($hasNamedGetter) { if ($interface->extendedAttributes->{"OverrideBuiltins"}) { $structureFlags{"JSC::GetOwnPropertySlotIsImpure"} = 1; } else { $structureFlags{"JSC::GetOwnPropertySlotIsImpureForPropertyAbsence"} = 1; } } if ($interface->extendedAttributes->{"NewImpurePropertyFiresWatchpoints"}) { $structureFlags{"JSC::NewImpurePropertyFiresWatchpoints"} = 1; } if ($interface->extendedAttributes->{"CustomCall"}) { $structureFlags{"JSC::TypeOfShouldCallGetCallData"} = 1; } # Getters if ($hasGetter) { push(@headerContent, " static bool getOwnPropertySlot(JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&);\n"); push(@headerContent, " bool getOwnPropertySlotDelegate(JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&);\n") if $interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}; $structureFlags{"JSC::OverridesGetOwnPropertySlot"} = 1; if ($hasComplexGetter) { push(@headerContent, " static bool getOwnPropertySlotByIndex(JSC::JSObject*, JSC::ExecState*, unsigned propertyName, JSC::PropertySlot&);\n"); $structureFlags{"JSC::InterceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero"} = 1; } } my $overridesPut = InstanceOverridesPutDeclaration($interface); # Getters if ($overridesPut) { push(@headerContent, " static bool put(JSC::JSCell*, JSC::ExecState*, JSC::PropertyName, JSC::JSValue, JSC::PutPropertySlot&);\n"); push(@headerContent, " static bool putByIndex(JSC::JSCell*, JSC::ExecState*, unsigned propertyName, JSC::JSValue, bool shouldThrow);\n"); push(@headerContent, " bool putDelegate(JSC::ExecState*, JSC::PropertyName, JSC::JSValue, JSC::PutPropertySlot&, bool& putResult);\n") if $interface->extendedAttributes->{"CustomNamedSetter"}; } if (!$hasParent) { push(@headerContent, " static void destroy(JSC::JSCell*);\n"); } # Class info if ($interfaceName eq "Node") { push(@headerContent, "\n"); push(@headerContent, "protected:\n"); push(@headerContent, " static const JSC::ClassInfo s_info;\n"); push(@headerContent, "public:\n"); push(@headerContent, " static const JSC::ClassInfo* info() { return &s_info; }\n\n"); } else { push(@headerContent, "\n"); push(@headerContent, " DECLARE_INFO;\n\n"); } # Structure ID if ($interfaceName eq "DOMWindow") { $structureFlags{"JSC::ImplementsHasInstance | JSC::ImplementsDefaultHasInstance"} = 1; } push(@headerContent, " static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)\n"); push(@headerContent, " {\n"); if (IsDOMGlobalObject($interface)) { push(@headerContent, " return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::GlobalObjectType, StructureFlags), info());\n"); } elsif ($codeGenerator->InheritsInterface($interface, "Document")) { push(@headerContent, " return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::JSType(JSDocumentWrapperType), StructureFlags), info());\n"); } elsif ($codeGenerator->InheritsInterface($interface, "Element")) { push(@headerContent, " return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::JSType(JSElementType), StructureFlags), info());\n"); } elsif ($codeGenerator->InheritsInterface($interface, "Node")) { push(@headerContent, " return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::JSType(JSNodeType), StructureFlags), info());\n"); } else { push(@headerContent, " return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info());\n"); } push(@headerContent, " }\n\n"); # Custom pushEventHandlerScope function push(@headerContent, " JSC::JSScope* pushEventHandlerScope(JSC::ExecState*, JSC::JSScope*) const;\n\n") if $interface->extendedAttributes->{"JSCustomPushEventHandlerScope"}; # Custom call functions push(@headerContent, " static JSC::CallType getCallData(JSC::JSCell*, JSC::CallData&);\n\n") if $interface->extendedAttributes->{"CustomCall"}; # Custom deleteProperty function push(@headerContent, " static bool deleteProperty(JSC::JSCell*, JSC::ExecState*, JSC::PropertyName);\n") if $interface->extendedAttributes->{"CustomDeleteProperty"}; push(@headerContent, " static bool deletePropertyByIndex(JSC::JSCell*, JSC::ExecState*, unsigned);\n") if $interface->extendedAttributes->{"CustomDeleteProperty"}; # Custom getPropertyNames function exists on DOMWindow if ($interfaceName eq "DOMWindow") { push(@headerContent, " static void getPropertyNames(JSC::JSObject*, JSC::ExecState*, JSC::PropertyNameArray&, JSC::EnumerationMode = JSC::EnumerationMode());\n"); push(@headerContent, " static void getGenericPropertyNames(JSC::JSObject*, JSC::ExecState*, JSC::PropertyNameArray&, JSC::EnumerationMode = JSC::EnumerationMode());\n"); push(@headerContent, " static void getStructurePropertyNames(JSC::JSObject*, JSC::ExecState*, JSC::PropertyNameArray&, JSC::EnumerationMode = JSC::EnumerationMode());\n"); push(@headerContent, " static uint32_t getEnumerableLength(JSC::ExecState*, JSC::JSObject*);\n"); $structureFlags{"JSC::OverridesGetPropertyNames"} = 1; } # Custom getOwnPropertyNames function if ($interface->extendedAttributes->{"CustomEnumerateProperty"} || $indexedGetterFunction || $namedGetterFunction) { push(@headerContent, " static void getOwnPropertyNames(JSC::JSObject*, JSC::ExecState*, JSC::PropertyNameArray&, JSC::EnumerationMode = JSC::EnumerationMode());\n"); $structureFlags{"JSC::OverridesGetPropertyNames"} = 1; } # Custom defineOwnProperty function push(@headerContent, " static bool defineOwnProperty(JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, const JSC::PropertyDescriptor&, bool shouldThrow);\n") if $interface->extendedAttributes->{"JSCustomDefineOwnProperty"}; # Override toBoolean to return false for objects that want to 'MasqueradesAsUndefined'. if ($interface->extendedAttributes->{"MasqueradesAsUndefined"}) { $structureFlags{"JSC::MasqueradesAsUndefined"} = 1; } # Constructor object getter unless ($interface->extendedAttributes->{"NoInterfaceObject"}) { push(@headerContent, " static JSC::JSValue getConstructor(JSC::VM&, const JSC::JSGlobalObject*);\n"); push(@headerContent, " static JSC::JSValue getNamedConstructor(JSC::VM&, JSC::JSGlobalObject*);\n") if $interface->extendedAttributes->{"NamedConstructor"}; } my $numCustomFunctions = 0; my $numCustomAttributes = 0; my $hasForwardDeclaringFunctions = 0; my $hasForwardDeclaringAttributes = 0; # Attribute and function enums if ($numAttributes > 0) { foreach (@{$interface->attributes}) { my $attribute = $_; $numCustomAttributes++ if HasCustomGetter($attribute->signature->extendedAttributes); $numCustomAttributes++ if HasCustomSetter($attribute->signature->extendedAttributes); if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) { my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature); push(@headerContent, "#if ${conditionalString}\n") if $conditionalString; push(@headerContent, " mutable JSC::WriteBarrier m_" . $attribute->signature->name . ";\n"); $numCachedAttributes++; $needsVisitChildren = 1; push(@headerContent, "#endif\n") if $conditionalString; } if ($attribute->signature->extendedAttributes->{"ForwardDeclareInHeader"}) { $hasForwardDeclaringAttributes = 1; } } } # visit function if ($needsVisitChildren) { push(@headerContent, " static void visitChildren(JSCell*, JSC::SlotVisitor&);\n"); push(@headerContent, " void visitAdditionalChildren(JSC::SlotVisitor&);\n") if $interface->extendedAttributes->{"JSCustomMarkFunction"}; push(@headerContent, "\n"); } if (InstanceNeedsEstimatedSize($interface)) { push(@headerContent, " static size_t estimatedSize(JSCell*);\n"); } if ($numCustomAttributes > 0) { push(@headerContent, "\n // Custom attributes\n"); foreach my $attribute (@{$interface->attributes}) { my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature); if (HasCustomGetter($attribute->signature->extendedAttributes)) { push(@headerContent, "#if ${conditionalString}\n") if $conditionalString; my $methodName = $codeGenerator->WK_lcfirst($attribute->signature->name); push(@headerContent, " JSC::JSValue " . $methodName . "(JSC::ExecState&) const;\n"); push(@headerContent, "#endif\n") if $conditionalString; } if (HasCustomSetter($attribute->signature->extendedAttributes) && !IsReadonly($attribute)) { push(@headerContent, "#if ${conditionalString}\n") if $conditionalString; push(@headerContent, " void set" . $codeGenerator->WK_ucfirst($attribute->signature->name) . "(JSC::ExecState&, JSC::JSValue);\n"); push(@headerContent, "#endif\n") if $conditionalString; } } } foreach my $function (@{$interface->functions}) { $numCustomFunctions++ if HasCustomMethod($function->signature->extendedAttributes); if ($function->signature->extendedAttributes->{"ForwardDeclareInHeader"}) { $hasForwardDeclaringFunctions = 1; } } if ($numCustomFunctions > 0) { my $inAppleCopyright = 0; push(@headerContent, "\n // Custom functions\n"); foreach my $function (@{$interface->functions}) { my $needsAppleCopyright = $function->signature->extendedAttributes->{"AppleCopyright"}; if ($needsAppleCopyright) { if (!$inAppleCopyright) { push(@headerContent, $beginAppleCopyrightForHeaderFiles); $inAppleCopyright = 1; } } elsif ($inAppleCopyright) { push(@headerContent, $endAppleCopyright); $inAppleCopyright = 0; } next unless HasCustomMethod($function->signature->extendedAttributes); next if $function->{overloads} && $function->{overloadIndex} != 1; my $conditionalString = $codeGenerator->GenerateConditionalString($function->signature); push(@headerContent, "#if ${conditionalString}\n") if $conditionalString; my $functionImplementationName = $function->signature->extendedAttributes->{"ImplementedAs"} || $codeGenerator->WK_lcfirst($function->signature->name); push(@headerContent, " " . ($function->isStatic ? "static " : "") . "JSC::JSValue " . $functionImplementationName . "(JSC::ExecState&);\n"); push(@headerContent, "#endif\n") if $conditionalString; } push(@headerContent, $endAppleCopyright) if $inAppleCopyright; } if (NeedsImplementationClass($interface)) { if ($hasParent) { push(@headerContent, " $interfaceName& wrapped() const\n"); push(@headerContent, " {\n"); push(@headerContent, " return static_cast<$interfaceName&>(Base::wrapped());\n"); push(@headerContent, " }\n"); } } # structure flags if (%structureFlags) { push(@headerContent, "public:\n"); push(@headerContent, " static const unsigned StructureFlags = "); foreach my $structureFlag (sort (keys %structureFlags)) { push(@headerContent, $structureFlag . " | "); } push(@headerContent, "Base::StructureFlags;\n"); } push(@headerContent, "protected:\n"); # Constructor if ($interfaceName eq "DOMWindow") { push(@headerContent, " $className(JSC::VM&, JSC::Structure*, Ref<$implType>&&, JSDOMWindowShell*);\n"); } elsif ($codeGenerator->InheritsInterface($interface, "WorkerGlobalScope")) { push(@headerContent, " $className(JSC::VM&, JSC::Structure*, Ref<$implType>&&);\n"); } elsif (!NeedsImplementationClass($interface)) { push(@headerContent, " $className(JSC::Structure*, JSDOMGlobalObject&);\n\n"); } else { push(@headerContent, " $className(JSC::Structure*, JSDOMGlobalObject&, Ref<$implType>&&);\n\n"); push(@headerContent, " void finishCreation(JSC::VM& vm)\n"); push(@headerContent, " {\n"); push(@headerContent, " Base::finishCreation(vm);\n"); push(@headerContent, " ASSERT(inherits(info()));\n"); push(@headerContent, " }\n\n"); } if (IsDOMGlobalObject($interface)) { if ($interfaceName eq "DOMWindow") { push(@headerContent, " void finishCreation(JSC::VM&, JSDOMWindowShell*);\n"); } else { push(@headerContent, " void finishCreation(JSC::VM&, JSC::JSProxy*);\n"); } } # Index setter if ($interface->extendedAttributes->{"CustomIndexedSetter"}) { push(@headerContent, " void indexSetter(JSC::ExecState*, unsigned index, JSC::JSValue);\n"); } # Name getter if ($namedGetterFunction || $interface->extendedAttributes->{"CustomNamedGetter"}) { push(@headerContent, "private:\n"); push(@headerContent, " bool nameGetter(JSC::ExecState*, JSC::PropertyName, JSC::JSValue&);\n"); } push(@headerContent, "};\n\n"); if (ShouldGenerateWrapperOwnerCode($hasParent, $interface)) { if ($interfaceName ne "Node" && $codeGenerator->InheritsInterface($interface, "Node")) { $headerIncludes{"JSNode.h"} = 1; push(@headerContent, "class JS${interfaceName}Owner : public JSNodeOwner {\n"); } else { push(@headerContent, "class JS${interfaceName}Owner : public JSC::WeakHandleOwner {\n"); } $headerIncludes{""} = 1; push(@headerContent, "public:\n"); push(@headerContent, " virtual bool isReachableFromOpaqueRoots(JSC::Handle, void* context, JSC::SlotVisitor&);\n"); push(@headerContent, " virtual void finalize(JSC::Handle, void* context);\n"); push(@headerContent, "};\n"); push(@headerContent, "\n"); push(@headerContent, "inline JSC::WeakHandleOwner* wrapperOwner(DOMWrapperWorld&, $implType*)\n"); push(@headerContent, "{\n"); push(@headerContent, " static NeverDestroyed owner;\n"); push(@headerContent, " return &owner.get();\n"); push(@headerContent, "}\n"); push(@headerContent, "\n"); push(@headerContent, "inline void* wrapperKey($implType* wrappableObject)\n"); push(@headerContent, "{\n"); push(@headerContent, " return wrappableObject;\n"); push(@headerContent, "}\n"); push(@headerContent, "\n"); } if (ShouldGenerateToJSDeclaration($hasParent, $interface)) { # Node and NodeList have custom inline implementations which thus cannot be exported. # FIXME: The special case for Node and NodeList should probably be implemented via an IDL attribute. if ($implType eq "Node" or $implType eq "NodeList") { push(@headerContent, "JSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject*, $implType&);\n"); } else { push(@headerContent, $exportMacro."JSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject*, $implType&);\n"); } push(@headerContent, "inline JSC::JSValue toJS(JSC::ExecState* state, JSDOMGlobalObject* globalObject, $implType* impl) { return impl ? toJS(state, globalObject, *impl) : JSC::jsNull(); }\n"); push(@headerContent, "JSC::JSValue toJSNewlyCreated(JSC::ExecState*, JSDOMGlobalObject*, Ref<$implType>&&);\n"); push(@headerContent, "inline JSC::JSValue toJSNewlyCreated(JSC::ExecState* state, JSDOMGlobalObject* globalObject, RefPtr<$implType>&& impl) { return impl ? toJSNewlyCreated(state, globalObject, impl.releaseNonNull()) : JSC::jsNull(); }\n"); } push(@headerContent, "\n"); GeneratePrototypeDeclaration(\@headerContent, $className, $interface) if HeaderNeedsPrototypeDeclaration($interface); if ($hasForwardDeclaringFunctions) { my $inAppleCopyright = 0; push(@headerContent,"// Functions\n\n"); foreach my $function (@{$interface->functions}) { next if $function->{overloadIndex} && $function->{overloadIndex} > 1; next unless $function->signature->extendedAttributes->{"ForwardDeclareInHeader"}; my $needsAppleCopyright = $function->signature->extendedAttributes->{"AppleCopyright"}; if ($needsAppleCopyright) { if (!$inAppleCopyright) { push(@headerContent, $beginAppleCopyrightForHeaderFiles); $inAppleCopyright = 1; } } elsif ($inAppleCopyright) { push(@headerContent, $endAppleCopyright); $inAppleCopyright = 0; } my $conditionalString = $codeGenerator->GenerateConditionalString($function->signature); push(@headerContent, "#if ${conditionalString}\n") if $conditionalString; my $functionName = GetFunctionName($interface, $className, $function); push(@headerContent, "JSC::EncodedJSValue JSC_HOST_CALL ${functionName}(JSC::ExecState*);\n"); push(@headerContent, "#endif\n") if $conditionalString; } push(@headerContent, $endAppleCopyright) if $inAppleCopyright; push(@headerContent,"\n"); } if ($hasForwardDeclaringAttributes) { push(@headerContent,"// Attributes\n\n"); foreach my $attribute (@{$interface->attributes}) { next unless $attribute->signature->extendedAttributes->{"ForwardDeclareInHeader"}; my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature); push(@headerContent, "#if ${conditionalString}\n") if $conditionalString; my $getter = GetAttributeGetterName($interface, $className, $attribute); push(@headerContent, "JSC::EncodedJSValue ${getter}(JSC::ExecState*, JSC::EncodedJSValue, JSC::PropertyName);\n"); if (!IsReadonly($attribute)) { my $setter = GetAttributeSetterName($interface, $className, $attribute); push(@headerContent, "bool ${setter}(JSC::ExecState*, JSC::EncodedJSValue, JSC::EncodedJSValue);\n"); } push(@headerContent, "#endif\n") if $conditionalString; } } if (HasCustomConstructor($interface)) { push(@headerContent, "// Custom constructor\n"); push(@headerContent, "JSC::EncodedJSValue JSC_HOST_CALL construct${className}(JSC::ExecState&);\n\n"); } if ($codeGenerator->IsConstructorTemplate($interface, "Event")) { push(@headerContent, "bool fill${interfaceName}Init(${interfaceName}Init&, JSDictionary&);\n\n"); } my $conditionalString = $codeGenerator->GenerateConditionalString($interface); push(@headerContent, "\n} // namespace WebCore\n"); push(@headerContent, "\n#endif // ${conditionalString}\n") if $conditionalString; if ($interface->extendedAttributes->{"AppleCopyright"}) { push(@headerContent, "\n"); push(@headerContent, split("\r", $endAppleCopyright)); } } sub GeneratePropertiesHashTable { my ($object, $interface, $isInstance, $hashKeys, $hashSpecials, $hashValue1, $hashValue2, $conditionals, $runtimeEnabledFunctions, $runtimeEnabledAttributes) = @_; # FIXME: These should be functions on $interface. my $interfaceName = $interface->name; my $className = "JS$interfaceName"; # - Add all properties in a hashtable definition my $propertyCount = $isInstance ? InstancePropertyCount($interface) : PrototypePropertyCount($interface); if (!$isInstance && NeedsConstructorProperty($interface)) { die if !$propertyCount; push(@$hashKeys, "constructor"); my $getter = "js" . $interfaceName . "Constructor"; push(@$hashValue1, $getter); my $setter = "setJS" . $interfaceName . "Constructor"; push(@$hashValue2, $setter); push(@$hashSpecials, "DontEnum"); } return 0 if !$propertyCount; foreach my $attribute (@{$interface->attributes}) { next if ($attribute->isStatic); next if AttributeShouldBeOnInstance($interface, $attribute) != $isInstance; # Global objects add RuntimeEnabled attributes after creation so do not add them to the static table. if (IsDOMGlobalObject($interface) && $attribute->signature->extendedAttributes->{"EnabledAtRuntime"}) { $propertyCount -= 1; next; } my $name = $attribute->signature->name; push(@$hashKeys, $name); my $special = GetJSCAttributesForAttribute($interface, $attribute); push(@$hashSpecials, $special); my $getter = GetAttributeGetterName($interface, $className, $attribute); push(@$hashValue1, $getter); if (IsReadonly($attribute)) { push(@$hashValue2, "0"); } else { my $setter = GetAttributeSetterName($interface, $className, $attribute); push(@$hashValue2, $setter); } my $conditional = $attribute->signature->extendedAttributes->{"Conditional"}; if ($conditional) { $conditionals->{$name} = $conditional; } if ($attribute->signature->extendedAttributes->{"EnabledAtRuntime"}) { if ($isInstance) { die "We currently do not support [EnabledAtRuntime] attributes on the instance (except for global objects)."; } else { push(@$runtimeEnabledAttributes, $attribute); } } } my @functions = @{$interface->functions}; push(@functions, @{$interface->iterable->functions}) if IsKeyValueIterableInterface($interface); foreach my $function (@functions) { next if ($function->signature->extendedAttributes->{"PrivateIdentifier"} and not $function->signature->extendedAttributes->{"PublicIdentifier"}); next if ($function->isStatic); next if $function->{overloadIndex} && $function->{overloadIndex} > 1; next if OperationShouldBeOnInstance($interface, $function) != $isInstance; next if $function->signature->name eq "[Symbol.Iterator]"; # Global objects add RuntimeEnabled operations after creation so do not add them to the static table. if (IsDOMGlobalObject($interface) && $function->signature->extendedAttributes->{"EnabledAtRuntime"}) { $propertyCount -= 1; next; } my $name = $function->signature->name; push(@$hashKeys, $name); my $functionName = GetFunctionName($interface, $className, $function); push(@$hashValue1, $functionName); my $functionLength = GetFunctionLength($function); push(@$hashValue2, $functionLength); push(@$hashSpecials, ComputeFunctionSpecial($interface, $function)); my $conditional = $function->signature->extendedAttributes->{"Conditional"}; if ($conditional) { $conditionals->{$name} = $conditional; } if ($function->signature->extendedAttributes->{"EnabledAtRuntime"}) { if ($isInstance) { die "We currently do not support [EnabledAtRuntime] operations on the instance (except for global objects)."; } else { push(@$runtimeEnabledFunctions, $function); } } } return $propertyCount; } sub GenerateParametersCheckExpression { my $numParameters = shift; my $function = shift; my @andExpression = (); push(@andExpression, "argsCount == $numParameters"); my $parameterIndex = 0; my %usedArguments = (); foreach my $parameter (@{$function->parameters}) { last if $parameterIndex >= $numParameters; my $value = "arg$parameterIndex"; my $type = $parameter->type; # For DOMString with StrictTypeChecking only Null, Undefined and Object # are accepted for compatibility. Otherwise, no restrictions are made to # match the non-overloaded behavior. # FIXME: Implement WebIDL overload resolution algorithm. if ($type eq "DOMString" || $codeGenerator->IsEnumType($type)) { if ($parameter->extendedAttributes->{"StrictTypeChecking"}) { push(@andExpression, "(${value}.isUndefinedOrNull() || ${value}.isString() || ${value}.isObject())"); $usedArguments{$parameterIndex} = 1; } } elsif ($codeGenerator->IsCallbackInterface($parameter->type)) { # For Callbacks only checks if the value is null or object. if ($codeGenerator->IsFunctionOnlyCallbackInterface($parameter->type)) { push(@andExpression, "(${value}.isNull() || ${value}.isFunction())"); } else { push(@andExpression, "(${value}.isNull() || ${value}.isObject())"); } $usedArguments{$parameterIndex} = 1; } elsif ($codeGenerator->IsDictionaryType($parameter->type)) { push(@andExpression, "(${value}.isUndefinedOrNull() || ${value}.isObject())"); $usedArguments{$parameterIndex} = 1; } elsif (($codeGenerator->GetArrayOrSequenceType($type) || $codeGenerator->IsTypedArrayType($type) || $codeGenerator->IsWrapperType($type)) && $type ne "EventListener") { my $condition = ""; if ($parameter->isNullable) { $condition .= "${value}.isUndefinedOrNull() || "; } elsif ($parameter->isOptional) { $condition .= "${value}.isUndefined() || "; } if ($codeGenerator->GetArrayOrSequenceType($type)) { # FIXME: Add proper support for T[], T[]?, sequence. $condition .= "(${value}.isObject() && isJSArray(${value}))"; } else { $condition .= "(${value}.isObject() && asObject(${value})->inherits(JS${type}::info()))"; } push(@andExpression, "(" . $condition . ")"); $usedArguments{$parameterIndex} = 1; } $parameterIndex++; } my $res = join(" && ", @andExpression); $res = "($res)" if @andExpression > 1; return ($res, sort {$a <=> $b} (keys %usedArguments)); } # As per Web IDL specification, the length of a function Object is its number of mandatory parameters. sub GetFunctionLength { my $function = shift; # FIXME: EventTarget.addEventListener() / removeEventListener() currently specifies all the parameters as optional. return 2 if $function->signature->name eq "addEventListener" || $function->signature->name eq "removeEventListener"; my $length = 0; foreach my $parameter (@{$function->parameters}) { # Abort as soon as we find the first optional parameter as no mandatory # parameter can follow an optional one. last if $parameter->isOptional || $parameter->isVariadic; $length++; } return $length; } sub GenerateFunctionParametersCheck { my $function = shift; my @orExpression = (); my $numParameters = 0; my @neededArguments = (); my $hasVariadic = 0; my $numMandatoryParams = @{$function->parameters}; foreach my $parameter (@{$function->parameters}) { if ($parameter->isOptional) { my ($expression, @usedArguments) = GenerateParametersCheckExpression($numParameters, $function); push(@orExpression, $expression); push(@neededArguments, @usedArguments); $numMandatoryParams--; } if ($parameter->isVariadic) { $hasVariadic = 1; last; } $numParameters++; } if (!$hasVariadic) { my ($expression, @usedArguments) = GenerateParametersCheckExpression($numParameters, $function); push(@orExpression, $expression); push(@neededArguments, @usedArguments); } return ($numMandatoryParams, join(" || ", @orExpression), @neededArguments); } sub LengthOfLongestFunctionParameterList { my ($overloads) = @_; my $result = 0; foreach my $overload (@{$overloads}) { my @parameters = @{$overload->parameters}; $result = @parameters if $result < @parameters; } return $result; } sub GenerateOverloadedFunction { my ($function, $interface) = @_; # Generate code for choosing the correct overload to call. Overloads are # chosen based on the total number of arguments passed and the type of # values passed in non-primitive argument slots. When more than a single # overload is applicable, precedence is given according to the order of # declaration in the IDL. my $kind = $function->isStatic ? "Constructor" : (OperationShouldBeOnInstance($interface, $function) ? "Instance" : "Prototype"); my $interfaceName = $interface->name; my $functionName = "js${interfaceName}${kind}Function" . $codeGenerator->WK_ucfirst($function->signature->name); # FIXME: Implement support for overloaded functions with variadic arguments. my $lengthOfLongestOverloadedFunctionParameterList = LengthOfLongestFunctionParameterList($function->{overloads}); push(@implContent, "EncodedJSValue JSC_HOST_CALL ${functionName}(ExecState* state)\n"); push(@implContent, <($lengthOfLongestOverloadedFunctionParameterList, state->argumentCount()); END my %fetchedArguments = (); my $leastNumMandatoryParams = 255; foreach my $overload (@{$function->{overloads}}) { my ($numMandatoryParams, $parametersCheck, @neededArguments) = GenerateFunctionParametersCheck($overload); $leastNumMandatoryParams = $numMandatoryParams if ($numMandatoryParams < $leastNumMandatoryParams); foreach my $parameterIndex (@neededArguments) { next if exists $fetchedArguments{$parameterIndex}; push(@implContent, " JSValue arg$parameterIndex(state->argument($parameterIndex));\n"); $fetchedArguments{$parameterIndex} = 1; } my $conditionalString = $codeGenerator->GenerateConditionalString($overload->signature); push(@implContent, "#if ${conditionalString}\n") if $conditionalString; push(@implContent, " if ($parametersCheck)\n"); push(@implContent, " return ${functionName}$overload->{overloadIndex}(state);\n"); push(@implContent, "#endif\n\n") if $conditionalString; } if ($leastNumMandatoryParams >= 1) { push(@implContent, " if (UNLIKELY(argsCount < $leastNumMandatoryParams))\n"); push(@implContent, " return throwVMError(state, createNotEnoughArgumentsError(state));\n"); } push(@implContent, <name; $interfaceName = $codeGenerator->GetSVGTypeNeedingTearOff($interfaceName) if $codeGenerator->IsSVGTypeNeedingTearOff($interfaceName); return $interfaceName; } # See http://refspecs.linux-foundation.org/cxxabi-1.83.html. sub GetGnuVTableRefForInterface { my $interface = shift; my $vtableName = GetGnuVTableNameForInterface($interface); if (!$vtableName) { return "0"; } my $typename = GetNativeTypeForConversions($interface); my $offset = GetGnuVTableOffsetForType($typename); return "&" . $vtableName . "[" . $offset . "]"; } sub GetGnuVTableNameForInterface { my $interface = shift; my $typename = GetNativeTypeForConversions($interface); my $templatePosition = index($typename, "<"); return "" if $templatePosition != -1; return "" if GetImplementationLacksVTableForInterface($interface); return "" if GetSkipVTableValidationForInterface($interface); return "_ZTV" . GetGnuMangledNameForInterface($interface); } sub GetGnuMangledNameForInterface { my $interface = shift; my $typename = GetNativeTypeForConversions($interface); my $templatePosition = index($typename, "<"); if ($templatePosition != -1) { return ""; } my $mangledType = length($typename) . $typename; my $namespace = GetNamespaceForInterface($interface); my $mangledNamespace = "N" . length($namespace) . $namespace; return $mangledNamespace . $mangledType . "E"; } sub GetGnuVTableOffsetForType { my $typename = shift; if ($typename eq "SVGAElement" || $typename eq "SVGCircleElement" || $typename eq "SVGClipPathElement" || $typename eq "SVGDefsElement" || $typename eq "SVGEllipseElement" || $typename eq "SVGForeignObjectElement" || $typename eq "SVGGElement" || $typename eq "SVGImageElement" || $typename eq "SVGLineElement" || $typename eq "SVGPathElement" || $typename eq "SVGPolyElement" || $typename eq "SVGPolygonElement" || $typename eq "SVGPolylineElement" || $typename eq "SVGRectElement" || $typename eq "SVGSVGElement" || $typename eq "SVGGraphicsElement" || $typename eq "SVGSwitchElement" || $typename eq "SVGTextElement" || $typename eq "SVGUseElement") { return "3"; } return "2"; } # See http://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B_Name_Mangling. sub GetWinVTableRefForInterface { my $interface = shift; my $vtableName = GetWinVTableNameForInterface($interface); return 0 if !$vtableName; return "__identifier(\"" . $vtableName . "\")"; } sub GetWinVTableNameForInterface { my $interface = shift; my $typename = GetNativeTypeForConversions($interface); my $templatePosition = index($typename, "<"); return "" if $templatePosition != -1; return "" if GetImplementationLacksVTableForInterface($interface); return "" if GetSkipVTableValidationForInterface($interface); return "??_7" . GetWinMangledNameForInterface($interface) . "6B@"; } sub GetWinMangledNameForInterface { my $interface = shift; my $typename = GetNativeTypeForConversions($interface); my $namespace = GetNamespaceForInterface($interface); return $typename . "@" . $namespace . "@@"; } sub GetNamespaceForInterface { my $interface = shift; return $interface->extendedAttributes->{"ImplementationNamespace"} || "WebCore"; } sub GetImplementationLacksVTableForInterface { my $interface = shift; return $interface->extendedAttributes->{"ImplementationLacksVTable"}; } sub GetSkipVTableValidationForInterface { my $interface = shift; return $interface->extendedAttributes->{"SkipVTableValidation"}; } # URL becomes url, but SetURL becomes setURL. sub ToMethodName { my $param = shift; my $ret = lcfirst($param); $ret =~ s/cSS/css/ if $ret =~ /^cSS/; $ret =~ s/dOM/dom/ if $ret =~ /^dOM/; $ret =~ s/hTML/html/ if $ret =~ /^hTML/; $ret =~ s/jS/js/ if $ret =~ /^jS/; $ret =~ s/uRL/url/ if $ret =~ /^uRL/; $ret =~ s/xML/xml/ if $ret =~ /^xML/; $ret =~ s/xSLT/xslt/ if $ret =~ /^xSLT/; # For HTML5 FileSystem API Flags attributes. # (create is widely used to instantiate an object and must be avoided.) $ret =~ s/^create/isCreate/ if $ret =~ /^create$/; $ret =~ s/^exclusive/isExclusive/ if $ret =~ /^exclusive$/; return $ret; } # Returns the RuntimeEnabledFeatures function name that is hooked up to check if a method/attribute is enabled. sub GetRuntimeEnableFunctionName { my $signature = shift; # If a parameter is given (e.g. "EnabledAtRuntime=FeatureName") return the RuntimeEnabledFeatures::sharedFeatures().{FeatureName}Enabled() method. return "RuntimeEnabledFeatures::sharedFeatures()." . ToMethodName($signature->extendedAttributes->{"EnabledAtRuntime"}) . "Enabled" if ($signature->extendedAttributes->{"EnabledAtRuntime"} && $signature->extendedAttributes->{"EnabledAtRuntime"} ne "VALUE_IS_MISSING"); # Otherwise return a function named RuntimeEnabledFeatures::sharedFeatures().{methodName}Enabled(). return "RuntimeEnabledFeatures::sharedFeatures()." . ToMethodName($signature->name) . "Enabled"; } sub GetCastingHelperForThisObject { my $interface = shift; my $interfaceName = $interface->name; return "jsNodeCast" if $interfaceName eq "Node"; return "jsElementCast" if $interfaceName eq "Element"; return "jsDocumentCast" if $interfaceName eq "Document"; return "jsEventTargetCast" if $interfaceName eq "EventTarget"; return "jsDynamicCast"; } sub GetIndexedGetterExpression { my $indexedGetterFunction = shift; if ($indexedGetterFunction->signature->type eq "DOMString") { return "jsStringOrUndefined(state, thisObject->wrapped().item(index))"; } return "toJS(state, thisObject->globalObject(), thisObject->wrapped().item(index))"; } sub GenerateImplementation { my ($object, $interface, $enumerations, $dictionaries) = @_; my $interfaceName = $interface->name; my $className = "JS$interfaceName"; my $hasLegacyParent = $interface->extendedAttributes->{"JSLegacyParent"}; my $hasRealParent = $interface->parent; my $hasParent = $hasLegacyParent || $hasRealParent; my $parentClassName = GetParentClassName($interface); my $visibleInterfaceName = $codeGenerator->GetVisibleInterfaceName($interface); my $eventTarget = $codeGenerator->InheritsInterface($interface, "EventTarget") && $interface->name ne "EventTarget"; my $needsVisitChildren = InstanceNeedsVisitChildren($interface); my $namedGetterFunction = GetNamedGetterFunction($interface); my $indexedGetterFunction = GetIndexedGetterFunction($interface); # - Add default header template push(@implContentHeader, GenerateImplementationContentHeader($interface)); $implIncludes{"JSDOMBinding.h"} = 1; $implIncludes{""} = 1; $implIncludes{""} = 1 if $indexedGetterFunction; my $implType = GetImplClassName($interfaceName); AddJSBuiltinIncludesIfNeeded($interface); @implContent = (); push(@implContent, "\nusing namespace JSC;\n\n"); push(@implContent, "namespace WebCore {\n\n"); push(@implContent, GenerateEnumerationImplementationContent($interface, $enumerations)); push(@implContent, GenerateDictionaryImplementationContent($interface, $dictionaries)); my @functions = @{$interface->functions}; push(@functions, @{$interface->iterable->functions}) if IsKeyValueIterableInterface($interface); my $numConstants = @{$interface->constants}; my $numFunctions = @functions; my $numAttributes = @{$interface->attributes}; if ($numFunctions > 0) { my $inAppleCopyright = 0; push(@implContent,"// Functions\n\n"); foreach my $function (@functions) { next if $function->{overloadIndex} && $function->{overloadIndex} > 1; next if $function->signature->extendedAttributes->{"ForwardDeclareInHeader"}; next if IsJSBuiltin($interface, $function); my $needsAppleCopyright = $function->signature->extendedAttributes->{"AppleCopyright"}; if ($needsAppleCopyright) { if (!$inAppleCopyright) { push(@implContent, $beginAppleCopyrightForHeaderFiles); $inAppleCopyright = 1; } } elsif ($inAppleCopyright) { push(@implContent, $endAppleCopyright); $inAppleCopyright = 0; } my $conditionalString = $codeGenerator->GenerateConditionalString($function->signature); push(@implContent, "#if ${conditionalString}\n") if $conditionalString; my $functionName = GetFunctionName($interface, $className, $function); push(@implContent, "JSC::EncodedJSValue JSC_HOST_CALL ${functionName}(JSC::ExecState*);\n"); push(@implContent, "#endif\n") if $conditionalString; } push(@implContent, $endAppleCopyright) if $inAppleCopyright; push(@implContent, "\n"); } if ($numAttributes > 0 || NeedsConstructorProperty($interface)) { push(@implContent, "// Attributes\n\n"); foreach my $attribute (@{$interface->attributes}) { next if $attribute->signature->extendedAttributes->{"ForwardDeclareInHeader"}; next if IsJSBuiltin($interface, $attribute); my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature); push(@implContent, "#if ${conditionalString}\n") if $conditionalString; my $getter = GetAttributeGetterName($interface, $className, $attribute); push(@implContent, "JSC::EncodedJSValue ${getter}(JSC::ExecState*, JSC::EncodedJSValue, JSC::PropertyName);\n"); if (!IsReadonly($attribute)) { my $setter = GetAttributeSetterName($interface, $className, $attribute); push(@implContent, "bool ${setter}(JSC::ExecState*, JSC::EncodedJSValue, JSC::EncodedJSValue);\n"); } push(@implContent, "#endif\n") if $conditionalString; } if (NeedsConstructorProperty($interface)) { my $getter = "js" . $interfaceName . "Constructor"; push(@implContent, "JSC::EncodedJSValue ${getter}(JSC::ExecState*, JSC::EncodedJSValue, JSC::PropertyName);\n"); } my $constructorFunctionName = "setJS" . $interfaceName . "Constructor"; push(@implContent, "bool ${constructorFunctionName}(JSC::ExecState*, JSC::EncodedJSValue, JSC::EncodedJSValue);\n"); push(@implContent, "\n"); } GeneratePrototypeDeclaration(\@implContent, $className, $interface) if !HeaderNeedsPrototypeDeclaration($interface); GenerateConstructorDeclaration(\@implContent, $className, $interface) if NeedsConstructorProperty($interface); my @hashKeys = (); my @hashValue1 = (); my @hashValue2 = (); my @hashSpecials = (); my %conditionals = (); my $hashName = $className . "Table"; my @runtimeEnabledFunctions = (); my @runtimeEnabledAttributes = (); # Generate hash table for properties on the instance. my $numInstanceProperties = GeneratePropertiesHashTable($object, $interface, 1, \@hashKeys, \@hashSpecials, \@hashValue1, \@hashValue2, \%conditionals, \@runtimeEnabledFunctions, \@runtimeEnabledAttributes); $object->GenerateHashTable($hashName, $numInstanceProperties, \@hashKeys, \@hashSpecials, \@hashValue1, \@hashValue2, \%conditionals, 0) if $numInstanceProperties > 0; # - Add all interface object (aka constructor) properties (constants, static attributes, static operations). if (NeedsConstructorProperty($interface)) { my $hashSize = 0; my $hashName = $className . "ConstructorTable"; my @hashKeys = (); my @hashValue1 = (); my @hashValue2 = (); my @hashSpecials = (); my %conditionals = (); my $needsConstructorTable = 0; foreach my $constant (@{$interface->constants}) { my $name = $constant->name; push(@hashKeys, $name); push(@hashValue1, $constant->value); push(@hashValue2, "0"); push(@hashSpecials, "DontDelete | ReadOnly | ConstantInteger"); my $implementedBy = $constant->extendedAttributes->{"ImplementedBy"}; if ($implementedBy) { $implIncludes{"${implementedBy}.h"} = 1; } my $conditional = $constant->extendedAttributes->{"Conditional"}; if ($conditional) { $conditionals{$name} = $conditional; } $hashSize++; } foreach my $attribute (@{$interface->attributes}) { next unless ($attribute->isStatic); my $name = $attribute->signature->name; push(@hashKeys, $name); my @specials = (); push(@specials, "DontDelete") unless $attribute->signature->extendedAttributes->{"Deletable"}; push(@specials, "ReadOnly") if IsReadonly($attribute); my $special = (@specials > 0) ? join(" | ", @specials) : "0"; push(@hashSpecials, $special); my $getter = GetAttributeGetterName($interface, $className, $attribute); push(@hashValue1, $getter); if (IsReadonly($attribute)) { push(@hashValue2, "0"); } else { my $setter = GetAttributeSetterName($interface, $className, $attribute); push(@hashValue2, $setter); } my $conditional = $attribute->signature->extendedAttributes->{"Conditional"}; if ($conditional) { $conditionals{$name} = $conditional; } $hashSize++; } foreach my $function (@{$interface->functions}) { next unless ($function->isStatic); next if $function->{overloadIndex} && $function->{overloadIndex} > 1; my $name = $function->signature->name; push(@hashKeys, $name); my $functionName = GetFunctionName($interface, $className, $function); push(@hashValue1, $functionName); my $functionLength = GetFunctionLength($function); push(@hashValue2, $functionLength); push(@hashSpecials, ComputeFunctionSpecial($interface, $function)); my $conditional = $function->signature->extendedAttributes->{"Conditional"}; if ($conditional) { $conditionals{$name} = $conditional; } $hashSize++; } $object->GenerateHashTable($hashName, $hashSize, \@hashKeys, \@hashSpecials, \@hashValue1, \@hashValue2, \%conditionals, 1) if $hashSize > 0; push(@implContent, $codeGenerator->GenerateCompileTimeCheckForEnumsIfNeeded($interface)); my $protoClassName = "${className}Prototype"; GenerateConstructorDefinitions(\@implContent, $className, $protoClassName, $visibleInterfaceName, $interface); if ($interface->extendedAttributes->{"NamedConstructor"}) { GenerateConstructorDefinitions(\@implContent, $className, $protoClassName, $interface->extendedAttributes->{"NamedConstructor"}, $interface, "GeneratingNamedConstructor"); } } # - Add functions and constants to a hashtable definition $hashName = $className . "PrototypeTable"; @hashKeys = (); @hashValue1 = (); @hashValue2 = (); @hashSpecials = (); %conditionals = (); @runtimeEnabledFunctions = (); @runtimeEnabledAttributes = (); # Generate hash table for properties on the prototype. my $numPrototypeProperties = GeneratePropertiesHashTable($object, $interface, 0, \@hashKeys, \@hashSpecials, \@hashValue1, \@hashValue2, \%conditionals, \@runtimeEnabledFunctions, \@runtimeEnabledAttributes); my $hashSize = $numPrototypeProperties; foreach my $constant (@{$interface->constants}) { my $name = $constant->name; push(@hashKeys, $name); push(@hashValue1, $constant->value); push(@hashValue2, "0"); push(@hashSpecials, "DontDelete | ReadOnly | ConstantInteger"); my $conditional = $constant->extendedAttributes->{"Conditional"}; if ($conditional) { $conditionals{$name} = $conditional; } $hashSize++; } my $justGenerateValueArray = !IsDOMGlobalObject($interface); $object->GenerateHashTable($hashName, $hashSize, \@hashKeys, \@hashSpecials, \@hashValue1, \@hashValue2, \%conditionals, $justGenerateValueArray); if ($justGenerateValueArray) { push(@implContent, "const ClassInfo ${className}Prototype::s_info = { \"${visibleInterfaceName}Prototype\", &Base::s_info, 0, CREATE_METHOD_TABLE(${className}Prototype) };\n\n"); } else { push(@implContent, "const ClassInfo ${className}Prototype::s_info = { \"${visibleInterfaceName}Prototype\", &Base::s_info, &${className}PrototypeTable, CREATE_METHOD_TABLE(${className}Prototype) };\n\n"); } if (PrototypeHasStaticPropertyTable($interface) && !IsDOMGlobalObject($interface)) { push(@implContent, "void ${className}Prototype::finishCreation(VM& vm)\n"); push(@implContent, "{\n"); push(@implContent, " Base::finishCreation(vm);\n"); push(@implContent, " reifyStaticProperties(vm, ${className}PrototypeTableValues, *this);\n"); my @runtimeEnabledProperties = @runtimeEnabledFunctions; push(@runtimeEnabledProperties, @runtimeEnabledAttributes); foreach my $functionOrAttribute (@runtimeEnabledProperties) { my $signature = $functionOrAttribute->signature; my $conditionalString = $codeGenerator->GenerateConditionalString($signature); push(@implContent, "#if ${conditionalString}\n") if $conditionalString; AddToImplIncludes("RuntimeEnabledFeatures.h"); my $enable_function = GetRuntimeEnableFunctionName($signature); my $name = $signature->name; push(@implContent, " if (!${enable_function}()) {\n"); push(@implContent, " Identifier propertyName = Identifier::fromString(&vm, reinterpret_cast(\"$name\"), strlen(\"$name\"));\n"); push(@implContent, " VM::DeletePropertyModeScope scope(vm, VM::DeletePropertyMode::IgnoreConfigurable);\n"); push(@implContent, " JSObject::deleteProperty(this, globalObject()->globalExec(), propertyName);\n"); push(@implContent, " }\n"); push(@implContent, "#endif\n") if $conditionalString; } my $firstPrivateFunction = 1; foreach my $function (@{$interface->functions}) { next unless ($function->signature->extendedAttributes->{"PrivateIdentifier"}); AddToImplIncludes("WebCoreJSClientData.h"); push(@implContent, " JSVMClientData& clientData = *static_cast(vm.clientData);\n") if $firstPrivateFunction; $firstPrivateFunction = 0; push(@implContent, " putDirect(vm, clientData.builtinNames()." . $function->signature->name . "PrivateName(), JSFunction::create(vm, globalObject(), 0, String(), " . GetFunctionName($interface, $className, $function) . "), ReadOnly | DontEnum);\n"); } if ($interface->iterable) { addIterableProperties($interface, $className); } push(@implContent, "}\n\n"); } if ($interface->extendedAttributes->{"JSCustomNamedGetterOnPrototype"}) { push(@implContent, "bool ${className}Prototype::put(JSCell* cell, ExecState* state, PropertyName propertyName, JSValue value, PutPropertySlot& slot)\n"); push(@implContent, "{\n"); push(@implContent, " auto* thisObject = jsCast<${className}Prototype*>(cell);\n"); push(@implContent, " bool putResult = false;\n"); push(@implContent, " if (thisObject->putDelegate(state, propertyName, value, slot, putResult))\n"); push(@implContent, " return putResult;\n"); push(@implContent, " return Base::put(thisObject, state, propertyName, value, slot);\n"); push(@implContent, "}\n\n"); } # - Initialize static ClassInfo object push(@implContent, "const ClassInfo $className" . "::s_info = { \"${visibleInterfaceName}\", &Base::s_info, "); if ($numInstanceProperties > 0) { push(@implContent, "&${className}Table"); } else { push(@implContent, "0"); } push(@implContent, ", CREATE_METHOD_TABLE($className) };\n\n"); my ($svgPropertyType, $svgListPropertyType, $svgNativeType) = GetSVGPropertyTypes($interfaceName); my $svgPropertyOrListPropertyType; $svgPropertyOrListPropertyType = $svgPropertyType if $svgPropertyType; $svgPropertyOrListPropertyType = $svgListPropertyType if $svgListPropertyType; # Constructor if ($interfaceName eq "DOMWindow") { AddIncludesForTypeInImpl("JSDOMWindowShell"); push(@implContent, "${className}::$className(VM& vm, Structure* structure, Ref<$implType>&& impl, JSDOMWindowShell* shell)\n"); push(@implContent, " : $parentClassName(vm, structure, WTFMove(impl), shell)\n"); push(@implContent, "{\n"); push(@implContent, "}\n\n"); } elsif ($codeGenerator->InheritsInterface($interface, "WorkerGlobalScope")) { AddIncludesForTypeInImpl($interfaceName); push(@implContent, "${className}::$className(VM& vm, Structure* structure, Ref<$implType>&& impl)\n"); push(@implContent, " : $parentClassName(vm, structure, WTFMove(impl))\n"); push(@implContent, "{\n"); push(@implContent, "}\n\n"); } elsif (!NeedsImplementationClass($interface)) { push(@implContent, "${className}::$className(Structure* structure, JSDOMGlobalObject& globalObject)\n"); push(@implContent, " : $parentClassName(structure, globalObject) { }\n\n"); } else { push(@implContent, "${className}::$className(Structure* structure, JSDOMGlobalObject& globalObject, Ref<$implType>&& impl)\n"); push(@implContent, " : $parentClassName(structure, globalObject, WTFMove(impl))\n"); push(@implContent, "{\n"); push(@implContent, "}\n\n"); } if (IsDOMGlobalObject($interface)) { if ($interfaceName eq "DOMWindow") { push(@implContent, "void ${className}::finishCreation(VM& vm, JSDOMWindowShell* shell)\n"); push(@implContent, "{\n"); push(@implContent, " Base::finishCreation(vm, shell);\n\n"); } else { push(@implContent, "void ${className}::finishCreation(VM& vm, JSProxy* proxy)\n"); push(@implContent, "{\n"); push(@implContent, " Base::finishCreation(vm, proxy);\n\n"); } # Support for RuntimeEnabled attributes on global objects. foreach my $attribute (@{$interface->attributes}) { next unless $attribute->signature->extendedAttributes->{"EnabledAtRuntime"}; AddToImplIncludes("RuntimeEnabledFeatures.h"); my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature); push(@implContent, "#if ${conditionalString}\n") if $conditionalString; my $enable_function = GetRuntimeEnableFunctionName($attribute->signature); my $attributeName = $attribute->signature->name; push(@implContent, " if (${enable_function}()) {\n"); my $getter = GetAttributeGetterName($interface, $className, $attribute); my $setter = IsReadonly($attribute) ? "nullptr" : GetAttributeSetterName($interface, $className, $attribute); push(@implContent, " auto* customGetterSetter = CustomGetterSetter::create(vm, $getter, $setter);\n"); my $jscAttributes = GetJSCAttributesForAttribute($interface, $attribute); push(@implContent, " putDirectCustomAccessor(vm, vm.propertyNames->$attributeName, customGetterSetter, attributesForStructure($jscAttributes));\n"); push(@implContent, " }\n"); push(@implContent, "#endif\n") if $conditionalString; } # Support PrivateIdentifier attributes on global objects foreach my $attribute (@{$interface->attributes}) { next unless $attribute->signature->extendedAttributes->{"PrivateIdentifier"}; AddToImplIncludes("WebCoreJSClientData.h"); my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature); my $attributeName = $attribute->signature->name; my $getter = GetAttributeGetterName($interface, $className, $attribute); push(@implContent, "#if ${conditionalString}\n") if $conditionalString; push(@implContent, " putDirectCustomAccessor(vm, static_cast(vm.clientData)->builtinNames()." . $attributeName . "PrivateName(), CustomGetterSetter::create(vm, $getter, nullptr), attributesForStructure(DontDelete | ReadOnly));\n"); push(@implContent, "#endif\n") if $conditionalString; } # Support for RuntimeEnabled operations on global objects. foreach my $function (@{$interface->functions}) { next unless $function->signature->extendedAttributes->{"EnabledAtRuntime"}; next if $function->{overloadIndex} && $function->{overloadIndex} > 1; AddToImplIncludes("RuntimeEnabledFeatures.h"); my $conditionalString = $codeGenerator->GenerateConditionalString($function->signature); push(@implContent, "#if ${conditionalString}\n") if $conditionalString; my $enable_function = GetRuntimeEnableFunctionName($function->signature); my $functionName = $function->signature->name; my $implementationFunction = GetFunctionName($interface, $className, $function); my $functionLength = GetFunctionLength($function); my $jsAttributes = ComputeFunctionSpecial($interface, $function); push(@implContent, " if (${enable_function}())\n"); push(@implContent, " putDirectNativeFunction(vm, this, vm.propertyNames->$functionName, $functionLength, $implementationFunction, NoIntrinsic, attributesForStructure($jsAttributes));\n"); push(@implContent, "#endif\n") if $conditionalString; } push(@implContent, "}\n\n"); } unless (ShouldUseGlobalObjectPrototype($interface)) { push(@implContent, "JSObject* ${className}::createPrototype(VM& vm, JSGlobalObject* globalObject)\n"); push(@implContent, "{\n"); if ($interface->parent) { my $parentClassNameForPrototype = "JS" . $interface->parent; push(@implContent, " return ${className}Prototype::create(vm, globalObject, ${className}Prototype::createStructure(vm, globalObject, ${parentClassNameForPrototype}::prototype(vm, globalObject)));\n"); } else { my $prototype = $interface->isException ? "errorPrototype" : "objectPrototype"; push(@implContent, " return ${className}Prototype::create(vm, globalObject, ${className}Prototype::createStructure(vm, globalObject, globalObject->${prototype}()));\n"); } push(@implContent, "}\n\n"); push(@implContent, "JSObject* ${className}::prototype(VM& vm, JSGlobalObject* globalObject)\n"); push(@implContent, "{\n"); push(@implContent, " return getDOMPrototype<${className}>(vm, globalObject);\n"); push(@implContent, "}\n\n"); } if (!$hasParent) { push(@implContent, "void ${className}::destroy(JSC::JSCell* cell)\n"); push(@implContent, "{\n"); push(@implContent, " ${className}* thisObject = static_cast<${className}*>(cell);\n"); push(@implContent, " thisObject->${className}::~${className}();\n"); push(@implContent, "}\n\n"); } my $hasGetter = InstanceOverridesGetOwnPropertySlot($interface); # Attributes if ($hasGetter) { if (!$interface->extendedAttributes->{"CustomGetOwnPropertySlot"}) { push(@implContent, "bool ${className}::getOwnPropertySlot(JSObject* object, ExecState* state, PropertyName propertyName, PropertySlot& slot)\n"); push(@implContent, "{\n"); push(@implContent, " auto* thisObject = jsCast<${className}*>(object);\n"); push(@implContent, " ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n"); push(@implContent, GenerateGetOwnPropertySlotBody($interface, $className, 0)); push(@implContent, "}\n\n"); } if ($indexedGetterFunction || $namedGetterFunction || $interface->extendedAttributes->{"CustomNamedGetter"} || $interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}) { push(@implContent, "bool ${className}::getOwnPropertySlotByIndex(JSObject* object, ExecState* state, unsigned index, PropertySlot& slot)\n"); push(@implContent, "{\n"); push(@implContent, " auto* thisObject = jsCast<${className}*>(object);\n"); push(@implContent, " ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n"); # Sink the int-to-string conversion that happens when we create a PropertyName # to the point where we actually need it. my $generatedPropertyName = 0; my $propertyNameGeneration = sub { if ($generatedPropertyName) { return; } push(@implContent, " Identifier propertyName = Identifier::from(state, index);\n"); $generatedPropertyName = 1; }; if ($indexedGetterFunction) { if ($indexedGetterFunction->signature->type eq "DOMString") { push(@implContent, " if (LIKELY(index <= MAX_ARRAY_INDEX)) {\n"); } else { push(@implContent, " if (LIKELY(index < thisObject->wrapped().length())) {\n"); } # Assume that if there's a setter, the index will be writable if ($interface->extendedAttributes->{"CustomIndexedSetter"}) { push(@implContent, " unsigned attributes = DontDelete;\n"); } else { push(@implContent, " unsigned attributes = DontDelete | ReadOnly;\n"); } push(@implContent, " slot.setValue(thisObject, attributes, " . GetIndexedGetterExpression($indexedGetterFunction) . ");\n"); push(@implContent, " return true;\n"); push(@implContent, " }\n"); } # Indexing an object with an integer that is not a supported property index should not call the named property getter. # https://heycam.github.io/webidl/#idl-indexed-properties if (!$indexedGetterFunction && ($namedGetterFunction || $interface->extendedAttributes->{"CustomNamedGetter"})) { &$propertyNameGeneration(); # This condition is to make sure we use the subclass' named getter instead of the base class one when possible. push(@implContent, " if (thisObject->classInfo() == info()) {\n"); push(@implContent, " JSValue value;\n"); push(@implContent, " if (thisObject->nameGetter(state, propertyName, value)) {\n"); push(@implContent, " slot.setValue(thisObject, ReadOnly | DontDelete | DontEnum, value);\n"); push(@implContent, " return true;\n"); push(@implContent, " }\n"); push(@implContent, " }\n"); $implIncludes{"wtf/text/AtomicString.h"} = 1; } if ($interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}) { &$propertyNameGeneration(); push(@implContent, " if (thisObject->getOwnPropertySlotDelegate(state, propertyName, slot))\n"); push(@implContent, " return true;\n"); } push(@implContent, " return Base::getOwnPropertySlotByIndex(thisObject, state, index, slot);\n"); push(@implContent, "}\n\n"); } } $numAttributes = $numAttributes + 1 if NeedsConstructorProperty($interface); if ($numAttributes > 0) { foreach my $attribute (@{$interface->attributes}) { next if IsJSBuiltin($interface, $attribute); my $name = $attribute->signature->name; my $type = $attribute->signature->type; $codeGenerator->AssertNotSequenceType($type); my $getFunctionName = GetAttributeGetterName($interface, $className, $attribute); my $implGetterFunctionName = $codeGenerator->WK_lcfirst($attribute->signature->extendedAttributes->{"ImplementedAs"} || $name); my $getterExceptionsWithMessage = $attribute->signature->extendedAttributes->{"GetterRaisesExceptionWithMessage"}; my $getterExceptions = $attribute->signature->extendedAttributes->{"GetterRaisesException"} || $getterExceptionsWithMessage; if ($getterExceptions) { $implIncludes{"ExceptionCode.h"} = 1; } my $attributeConditionalString = $codeGenerator->GenerateConditionalString($attribute->signature); push(@implContent, "#if ${attributeConditionalString}\n") if $attributeConditionalString; push(@implContent, "EncodedJSValue ${getFunctionName}(ExecState* state, EncodedJSValue thisValue, PropertyName)\n"); push(@implContent, "{\n"); push(@implContent, " UNUSED_PARAM(state);\n"); push(@implContent, " UNUSED_PARAM(thisValue);\n"); if (!$attribute->isStatic || $attribute->signature->type =~ /Constructor$/) { push(@implContent, " JSValue decodedThisValue = JSValue::decode(thisValue);\n"); my $castingFunction = $interface->extendedAttributes->{"CustomProxyToJSObject"} ? "to${className}" : GetCastingHelperForThisObject($interface); # http://heycam.github.io/webidl/#ImplicitThis if ($interface->extendedAttributes->{"ImplicitThis"}) { push(@implContent, " auto* castedThis = decodedThisValue.isUndefinedOrNull() ? $castingFunction(state->thisValue().toThis(state, NotStrictMode)) : $castingFunction(decodedThisValue);\n"); } else { push(@implContent, " auto* castedThis = $castingFunction(decodedThisValue);\n"); } push(@implContent, " if (UNLIKELY(!castedThis)) {\n"); if ($attribute->signature->extendedAttributes->{"LenientThis"}) { push(@implContent, " return JSValue::encode(jsUndefined());\n"); } elsif (InterfaceRequiresAttributesOnInstanceForCompatibility($interface)) { # Fallback to trying to searching the prototype chain for compatibility reasons. push(@implContent, " JSObject* thisObject = JSValue::decode(thisValue).getObject();\n"); push(@implContent, " for (thisObject = thisObject ? thisObject->getPrototypeDirect().getObject() : nullptr; thisObject; thisObject = thisObject->getPrototypeDirect().getObject()) {\n"); push(@implContent, " if ((castedThis = " . GetCastingHelperForThisObject($interface) . "(thisObject)))\n"); push(@implContent, " break;\n"); push(@implContent, " }\n"); push(@implContent, " if (!castedThis)\n"); push(@implContent, " return throwGetterTypeError(*state, \"$interfaceName\", \"$name\");\n"); push(@implContent, " reportDeprecatedGetterError(*state, \"$interfaceName\", \"$name\");\n"); } else { push(@implContent, " return throwGetterTypeError(*state, \"$interfaceName\", \"$name\");\n"); } push(@implContent, " }\n"); } my @arguments = (); if ($getterExceptions && !HasCustomGetter($attribute->signature->extendedAttributes)) { push(@arguments, "ec"); if ($getterExceptionsWithMessage) { push(@implContent, " ExceptionCodeWithMessage ec;\n"); } else { push(@implContent, " ExceptionCode ec = 0;\n"); } } # Global constructors can be disabled at runtime. if ($attribute->signature->type =~ /Constructor$/) { if ($attribute->signature->extendedAttributes->{"EnabledBySetting"}) { AddToImplIncludes("Frame.h"); AddToImplIncludes("Settings.h"); my $enable_function = ToMethodName($attribute->signature->extendedAttributes->{"EnabledBySetting"}) . "Enabled"; push(@implContent, " if (UNLIKELY(!castedThis->wrapped().frame()))\n"); push(@implContent, " return JSValue::encode(jsUndefined());\n"); push(@implContent, " Settings& settings = castedThis->wrapped().frame()->settings();\n"); push(@implContent, " if (!settings.$enable_function())\n"); push(@implContent, " return JSValue::encode(jsUndefined());\n"); } } if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) { $needsVisitChildren = 1; } if ($interface->extendedAttributes->{"CheckSecurity"} && !$attribute->signature->extendedAttributes->{"DoNotCheckSecurity"} && !$attribute->signature->extendedAttributes->{"DoNotCheckSecurityOnGetter"}) { if ($interfaceName eq "DOMWindow") { push(@implContent, " if (!BindingSecurity::shouldAllowAccessToDOMWindow(state, castedThis->wrapped()))\n"); } else { push(@implContent, " if (!shouldAllowAccessToFrame(state, castedThis->wrapped().frame()))\n"); } push(@implContent, " return JSValue::encode(jsUndefined());\n"); } if ($attribute->signature->extendedAttributes->{"Nondeterministic"}) { AddToImplIncludes("MemoizedDOMResult.h", "WEB_REPLAY"); AddToImplIncludes("", "WEB_REPLAY"); AddToImplIncludes("", "WEB_REPLAY"); push(@implContent, "#if ENABLE(WEB_REPLAY)\n"); push(@implContent, " JSGlobalObject* globalObject = state->lexicalGlobalObject();\n"); push(@implContent, " InputCursor& cursor = globalObject->inputCursor();\n"); my $nativeType = GetNativeType($interface, $type); my $memoizedType = GetNativeTypeForMemoization($interface, $type); my $exceptionCode = $getterExceptionsWithMessage ? "ec.code" : ($getterExceptions ? "ec" : "0"); push(@implContent, " static NeverDestroyed bindingName(\"$interfaceName.$name\", AtomicString::ConstructFromLiteral);\n"); push(@implContent, " if (cursor.isCapturing()) {\n"); push(@implContent, " $memoizedType memoizedResult = castedThis->wrapped().$implGetterFunctionName(" . join(", ", @arguments) . ");\n"); push(@implContent, " cursor.appendInput>(bindingName.get().string(), memoizedResult, $exceptionCode);\n"); push(@implContent, " JSValue result = " . NativeToJSValue($attribute->signature, 0, $interface, "memoizedResult", "castedThis") . ";\n"); push(@implContent, " setDOMException(state, ec);\n") if $getterExceptions; push(@implContent, " return JSValue::encode(result);\n"); push(@implContent, " }\n"); push(@implContent, "\n"); push(@implContent, " if (cursor.isReplaying()) {\n"); push(@implContent, " $memoizedType memoizedResult;\n"); push(@implContent, " MemoizedDOMResultBase* input = cursor.fetchInput();\n"); push(@implContent, " if (input && input->convertTo<$memoizedType>(memoizedResult)) {\n"); # FIXME: the generated code should report an error if an input cannot be fetched or converted. push(@implContent, " JSValue result = " . NativeToJSValue($attribute->signature, 0, $interface, "memoizedResult", "castedThis") . ";\n"); push(@implContent, " setDOMException(state, input->exceptionCode());\n") if $getterExceptions; push(@implContent, " return JSValue::encode(result);\n"); push(@implContent, " }\n"); push(@implContent, " }\n"); push(@implContent, "#endif\n"); } # attribute Nondeterministic if (HasCustomGetter($attribute->signature->extendedAttributes)) { push(@implContent, " return JSValue::encode(castedThis->$implGetterFunctionName(*state));\n"); } elsif ($attribute->signature->extendedAttributes->{"CheckSecurityForNode"}) { $implIncludes{"JSDOMBinding.h"} = 1; push(@implContent, " auto& impl = castedThis->wrapped();\n"); push(@implContent, " return JSValue::encode(shouldAllowAccessToNode(state, impl." . $attribute->signature->name . "()) ? " . NativeToJSValue($attribute->signature, 0, $interface, "impl.$implGetterFunctionName()", "castedThis") . " : jsNull());\n"); } elsif ($type eq "EventHandler") { $implIncludes{"EventNames.h"} = 1; my $getter = $attribute->signature->extendedAttributes->{"WindowEventHandler"} ? "windowEventHandlerAttribute" : $attribute->signature->extendedAttributes->{"DocumentEventHandler"} ? "documentEventHandlerAttribute" : "eventHandlerAttribute"; my $eventName = EventHandlerAttributeEventName($attribute); push(@implContent, " UNUSED_PARAM(state);\n"); push(@implContent, " return JSValue::encode($getter(castedThis->wrapped(), $eventName));\n"); } elsif ($attribute->signature->type =~ /Constructor$/) { my $constructorType = $attribute->signature->type; $constructorType =~ s/Constructor$//; # When Constructor attribute is used by DOMWindow.idl, it's correct to pass castedThis as the global object # When JSDOMWrappers have a back-pointer to the globalObject we can pass castedThis->globalObject() if ($interfaceName eq "DOMWindow") { my $named = ($constructorType =~ /Named$/) ? "Named" : ""; $constructorType =~ s/Named$//; push(@implContent, " return JSValue::encode(JS" . $constructorType . "::get${named}Constructor(state->vm(), castedThis));\n"); } else { AddToImplIncludes("JS" . $constructorType . ".h", $attribute->signature->extendedAttributes->{"Conditional"}); push(@implContent, " return JSValue::encode(JS" . $constructorType . "::getConstructor(state->vm(), castedThis->globalObject()));\n"); } } elsif (!$attribute->signature->extendedAttributes->{"GetterRaisesException"} && !$attribute->signature->extendedAttributes->{"GetterRaisesExceptionWithMessage"}) { my $cacheIndex = 0; if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) { $cacheIndex = $currentCachedAttribute; $currentCachedAttribute++; push(@implContent, " if (JSValue cachedValue = castedThis->m_" . $attribute->signature->name . ".get())\n"); push(@implContent, " return JSValue::encode(cachedValue);\n"); } my @callWithArgs = GenerateCallWith($attribute->signature->extendedAttributes->{"CallWith"}, \@implContent, "JSValue::encode(jsUndefined())"); if ($svgListPropertyType) { push(@implContent, " JSValue result = " . NativeToJSValue($attribute->signature, 0, $interface, "castedThis->wrapped().$implGetterFunctionName(" . (join ", ", @callWithArgs) . ")", "castedThis") . ";\n"); } elsif ($svgPropertyOrListPropertyType) { push(@implContent, " $svgPropertyOrListPropertyType& impl = castedThis->wrapped().propertyReference();\n"); if ($svgPropertyOrListPropertyType eq "float") { # Special case for JSSVGNumber push(@implContent, " JSValue result = " . NativeToJSValue($attribute->signature, 0, $interface, "impl", "castedThis") . ";\n"); } else { push(@implContent, " JSValue result = " . NativeToJSValue($attribute->signature, 0, $interface, "impl.$implGetterFunctionName(" . (join ", ", @callWithArgs) . ")", "castedThis") . ";\n"); } } else { my ($functionName, @arguments) = $codeGenerator->GetterExpression(\%implIncludes, $interfaceName, $attribute); if ($attribute->signature->extendedAttributes->{"ImplementedBy"}) { my $implementedBy = $attribute->signature->extendedAttributes->{"ImplementedBy"}; $implIncludes{"${implementedBy}.h"} = 1; $functionName = "WebCore::${implementedBy}::${functionName}"; unshift(@arguments, "impl") if !$attribute->isStatic; } elsif ($attribute->isStatic) { $functionName = "${interfaceName}::${functionName}"; } else { $functionName = "impl.${functionName}"; } unshift(@arguments, @callWithArgs); my $jsType = NativeToJSValue($attribute->signature, 0, $interface, "${functionName}(" . join(", ", @arguments) . ")", "castedThis"); push(@implContent, " auto& impl = castedThis->wrapped();\n") if !$attribute->isStatic; if ($codeGenerator->IsSVGAnimatedType($type)) { push(@implContent, " auto obj = $jsType;\n"); push(@implContent, " JSValue result = toJS(state, castedThis->globalObject(), obj.get());\n"); } else { push(@implContent, " JSValue result = $jsType;\n"); } } push(@implContent, " castedThis->m_" . $attribute->signature->name . ".set(state->vm(), castedThis, result);\n") if ($attribute->signature->extendedAttributes->{"CachedAttribute"}); push(@implContent, " return JSValue::encode(result);\n"); } else { unshift(@arguments, GenerateCallWith($attribute->signature->extendedAttributes->{"CallWith"}, \@implContent, "JSValue::encode(jsUndefined())")); if ($svgPropertyOrListPropertyType) { push(@implContent, " $svgPropertyOrListPropertyType impl(*castedThis->wrapped());\n"); push(@implContent, " JSValue result = " . NativeToJSValue($attribute->signature, 0, $interface, "impl.$implGetterFunctionName(" . join(", ", @arguments) . ")", "castedThis") . ";\n"); } else { push(@implContent, " auto& impl = castedThis->wrapped();\n"); push(@implContent, " JSValue result = " . NativeToJSValue($attribute->signature, 0, $interface, "impl.$implGetterFunctionName(" . join(", ", @arguments) . ")", "castedThis") . ";\n"); } push(@implContent, " setDOMException(state, ec);\n"); push(@implContent, " return JSValue::encode(result);\n"); } push(@implContent, "}\n\n"); push(@implContent, "#endif\n") if $attributeConditionalString; push(@implContent, "\n"); } if (NeedsConstructorProperty($interface)) { my $constructorFunctionName = "js" . $interfaceName . "Constructor"; push(@implContent, "EncodedJSValue ${constructorFunctionName}(ExecState* state, EncodedJSValue thisValue, PropertyName)\n"); push(@implContent, "{\n"); push(@implContent, " ${className}Prototype* domObject = jsDynamicCast<${className}Prototype*>(JSValue::decode(thisValue));\n"); push(@implContent, " if (UNLIKELY(!domObject))\n"); push(@implContent, " return throwVMTypeError(state);\n"); if (!$interface->extendedAttributes->{"NoInterfaceObject"}) { push(@implContent, " return JSValue::encode(${className}::getConstructor(state->vm(), domObject->globalObject()));\n"); } else { push(@implContent, " JSValue constructor = ${className}Constructor::create(state->vm(), ${className}Constructor::createStructure(state->vm(), *domObject->globalObject(), domObject->globalObject()->objectPrototype()), *jsCast(domObject->globalObject()));\n"); push(@implContent, " // Shadowing constructor property to ensure reusing the same constructor object\n"); push(@implContent, " domObject->putDirect(state->vm(), state->propertyNames().constructor, constructor, DontEnum | ReadOnly);\n"); push(@implContent, " return JSValue::encode(constructor);\n"); } push(@implContent, "}\n\n"); } my $constructorFunctionName = "setJS" . $interfaceName . "Constructor"; push(@implContent, "bool ${constructorFunctionName}(ExecState* state, EncodedJSValue thisValue, EncodedJSValue encodedValue)\n"); push(@implContent, "{\n"); push(@implContent, " JSValue value = JSValue::decode(encodedValue);\n"); push(@implContent, " ${className}Prototype* domObject = jsDynamicCast<${className}Prototype*>(JSValue::decode(thisValue));\n"); push(@implContent, " if (UNLIKELY(!domObject)) {\n"); push(@implContent, " throwVMTypeError(state);\n"); push(@implContent, " return false;\n"); push(@implContent, " }\n"); push(@implContent, " // Shadowing a built-in constructor\n"); push(@implContent, " return domObject->putDirect(state->vm(), state->propertyNames().constructor, value);\n"); push(@implContent, "}\n\n"); } my $hasCustomSetter = $interface->extendedAttributes->{"CustomNamedSetter"} || $interface->extendedAttributes->{"CustomIndexedSetter"}; if ($hasCustomSetter) { if (!$interface->extendedAttributes->{"CustomPutFunction"}) { push(@implContent, "bool ${className}::put(JSCell* cell, ExecState* state, PropertyName propertyName, JSValue value, PutPropertySlot& slot)\n"); push(@implContent, "{\n"); push(@implContent, " auto* thisObject = jsCast<${className}*>(cell);\n"); push(@implContent, " ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n"); if ($interface->extendedAttributes->{"CustomIndexedSetter"}) { push(@implContent, " if (Optional index = parseIndex(propertyName)) {\n"); push(@implContent, " thisObject->indexSetter(state, index.value(), value);\n"); push(@implContent, " return true;\n"); push(@implContent, " }\n"); } if ($interface->extendedAttributes->{"CustomNamedSetter"}) { push(@implContent, " bool putResult = false;\n"); push(@implContent, " if (thisObject->putDelegate(state, propertyName, value, slot, putResult))\n"); push(@implContent, " return putResult;\n"); } push(@implContent, " return Base::put(thisObject, state, propertyName, value, slot);\n"); push(@implContent, "}\n\n"); if ($interface->extendedAttributes->{"CustomIndexedSetter"} || $interface->extendedAttributes->{"CustomNamedSetter"}) { push(@implContent, "bool ${className}::putByIndex(JSCell* cell, ExecState* state, unsigned index, JSValue value, bool shouldThrow)\n"); push(@implContent, "{\n"); push(@implContent, " auto* thisObject = jsCast<${className}*>(cell);\n"); push(@implContent, " ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n"); if ($interface->extendedAttributes->{"CustomIndexedSetter"}) { push(@implContent, " if (LIKELY(index <= MAX_ARRAY_INDEX)) {\n"); push(@implContent, " thisObject->indexSetter(state, index, value);\n"); push(@implContent, " return true;\n"); push(@implContent, " }\n"); } if ($interface->extendedAttributes->{"CustomNamedSetter"}) { push(@implContent, " Identifier propertyName = Identifier::from(state, index);\n"); push(@implContent, " PutPropertySlot slot(thisObject, shouldThrow);\n"); push(@implContent, " bool putResult = false;\n"); push(@implContent, " if (thisObject->putDelegate(state, propertyName, value, slot, putResult))\n"); push(@implContent, " return putResult;\n"); } push(@implContent, " return Base::putByIndex(cell, state, index, value, shouldThrow);\n"); push(@implContent, "}\n\n"); } } } foreach my $attribute (@{$interface->attributes}) { if (!IsReadonly($attribute)) { next if IsJSBuiltin($interface, $attribute); my $name = $attribute->signature->name; my $type = $attribute->signature->type; my $putFunctionName = GetAttributeSetterName($interface, $className, $attribute); my $implSetterFunctionName = $codeGenerator->WK_ucfirst($name); my $setterRaisesExceptionWithMessage = $attribute->signature->extendedAttributes->{"SetterRaisesExceptionWithMessage"}; my $setterRaisesException = $attribute->signature->extendedAttributes->{"SetterRaisesException"} || $setterRaisesExceptionWithMessage; if ($setterRaisesException) { $implIncludes{"ExceptionCode.h"} = 1; } my $attributeConditionalString = $codeGenerator->GenerateConditionalString($attribute->signature); push(@implContent, "#if ${attributeConditionalString}\n") if $attributeConditionalString; push(@implContent, "bool ${putFunctionName}(ExecState* state, EncodedJSValue thisValue, EncodedJSValue encodedValue)\n"); push(@implContent, "{\n"); push(@implContent, " JSValue value = JSValue::decode(encodedValue);\n"); push(@implContent, " UNUSED_PARAM(thisValue);\n") if !$attribute->isStatic; if (!$attribute->isStatic) { if ($interface->extendedAttributes->{"CustomProxyToJSObject"}) { push(@implContent, " ${className}* castedThis = to${className}(JSValue::decode(thisValue));\n"); } else { push(@implContent, " ${className}* castedThis = " . GetCastingHelperForThisObject($interface) . "(JSValue::decode(thisValue));\n"); } push(@implContent, " if (UNLIKELY(!castedThis)) {\n"); if ($attribute->signature->extendedAttributes->{"LenientThis"}) { push(@implContent, " return false;\n"); } elsif (InterfaceRequiresAttributesOnInstanceForCompatibility($interface)) { # Fallback to trying to searching the prototype chain for compatibility reasons. push(@implContent, " JSObject* thisObject = JSValue::decode(thisValue).getObject();\n"); push(@implContent, " for (thisObject = thisObject ? thisObject->getPrototypeDirect().getObject() : nullptr; thisObject; thisObject = thisObject->getPrototypeDirect().getObject()) {\n"); push(@implContent, " if ((castedThis = " . GetCastingHelperForThisObject($interface) . "(thisObject)))\n"); push(@implContent, " break;\n"); push(@implContent, " }\n"); push(@implContent, " if (!castedThis)\n"); push(@implContent, " return throwSetterTypeError(*state, \"$interfaceName\", \"$name\");\n"); push(@implContent, " reportDeprecatedSetterError(*state, \"$interfaceName\", \"$name\");\n"); } else { push(@implContent, " return throwSetterTypeError(*state, \"$interfaceName\", \"$name\");\n"); } push(@implContent, " }\n"); } if ($interface->extendedAttributes->{"CheckSecurity"} && !$attribute->signature->extendedAttributes->{"DoNotCheckSecurity"} && !$attribute->signature->extendedAttributes->{"DoNotCheckSecurityOnSetter"}) { if ($interfaceName eq "DOMWindow") { push(@implContent, " if (!BindingSecurity::shouldAllowAccessToDOMWindow(state, castedThis->wrapped()))\n"); } else { push(@implContent, " if (!shouldAllowAccessToFrame(state, castedThis->wrapped().frame()))\n"); } push(@implContent, " return false;\n"); } if (HasCustomSetter($attribute->signature->extendedAttributes)) { push(@implContent, " castedThis->set$implSetterFunctionName(*state, value);\n"); push(@implContent, " return true;\n"); } elsif ($type eq "EventHandler") { $implIncludes{"JSEventListener.h"} = 1; my $eventName = EventHandlerAttributeEventName($attribute); # FIXME: Find a way to do this special case without hardcoding the class and attribute names here. if ((($interfaceName eq "DOMWindow") or ($interfaceName eq "WorkerGlobalScope")) and $name eq "onerror") { $implIncludes{"JSErrorHandler.h"} = 1; push(@implContent, " castedThis->wrapped().setAttributeEventListener($eventName, createJSErrorHandler(state, value, castedThis));\n"); } else { $implIncludes{"JSEventListener.h"} = 1; my $setter = $attribute->signature->extendedAttributes->{"WindowEventHandler"} ? "setWindowEventHandlerAttribute" : $attribute->signature->extendedAttributes->{"DocumentEventHandler"} ? "setDocumentEventHandlerAttribute" : "setEventHandlerAttribute"; push(@implContent, " $setter(*state, *castedThis, castedThis->wrapped(), $eventName, value);\n"); } push(@implContent, " return true;\n"); } elsif ($type =~ /Constructor$/) { my $constructorType = $type; $constructorType =~ s/Constructor$//; # $constructorType ~= /Constructor$/ indicates that it is NamedConstructor. # We do not generate the header file for NamedConstructor of class XXXX, # since we generate the NamedConstructor declaration into the header file of class XXXX. if ($constructorType ne "any" and $constructorType !~ /Named$/) { AddToImplIncludes("JS" . $constructorType . ".h", $attribute->signature->extendedAttributes->{"Conditional"}); } push(@implContent, " // Shadowing a built-in constructor.\n"); push(@implContent, " return castedThis->putDirect(state->vm(), Identifier::fromString(state, \"$name\"), value);\n"); } elsif ($attribute->signature->extendedAttributes->{"Replaceable"}) { push(@implContent, " // Shadowing a built-in property.\n"); if (AttributeShouldBeOnInstance($interface, $attribute)) { push(@implContent, " return replaceStaticPropertySlot(state->vm(), castedThis, Identifier::fromString(state, \"$name\"), value);\n"); } else { push(@implContent, " return castedThis->putDirect(state->vm(), Identifier::fromString(state, \"$name\"), value);\n"); } } else { if (!$attribute->isStatic) { my $putForwards = $attribute->signature->extendedAttributes->{"PutForwards"}; if ($putForwards) { my $implGetterFunctionName = $codeGenerator->WK_lcfirst($attribute->signature->extendedAttributes->{"ImplementedAs"} || $name); if ($attribute->signature->isNullable) { push(@implContent, " RefPtr<${type}> forwardedImpl = castedThis->wrapped().${implGetterFunctionName}();\n"); push(@implContent, " if (!forwardedImpl)\n"); push(@implContent, " return false;\n"); push(@implContent, " auto& impl = *forwardedImpl;\n"); } else { # Attribute is not nullable, the implementation is expected to return a reference. push(@implContent, " Ref<${type}> forwardedImpl = castedThis->wrapped().${implGetterFunctionName}();\n"); push(@implContent, " auto& impl = forwardedImpl.get();\n"); } $attribute = $codeGenerator->GetAttributeFromInterface($interface, $type, $putForwards); } else { push(@implContent, " auto& impl = castedThis->wrapped();\n"); } } if ($setterRaisesExceptionWithMessage) { push(@implContent, " ExceptionCodeWithMessage ec;\n"); } elsif ($setterRaisesException) { push(@implContent, " ExceptionCode ec = 0;\n"); } my $shouldPassByReference = ShouldPassWrapperByReference($attribute->signature, $interface); # If the "StrictTypeChecking" extended attribute is present, and the attribute's type is an # interface type, then if the incoming value does not implement that interface, a TypeError # is thrown rather than silently passing NULL to the C++ code. # Per the Web IDL and ECMAScript specifications, incoming values can always be converted to # both strings and numbers, so do not throw TypeError if the attribute is of these types. my ($nativeValue, $mayThrowException) = JSValueToNative($interface, $attribute->signature, "value", $attribute->signature->extendedAttributes->{"Conditional"}); if ($attribute->signature->extendedAttributes->{"StrictTypeChecking"} && !$shouldPassByReference && $codeGenerator->IsWrapperType($type)) { $implIncludes{""} = 1; push(@implContent, " " . GetNativeTypeFromSignature($interface, $attribute->signature) . " nativeValue = nullptr;\n"); push(@implContent, " if (!value.isUndefinedOrNull()) {\n"); push(@implContent, " nativeValue = $nativeValue;\n"); if ($mayThrowException) { push(@implContent, " if (UNLIKELY(state->hadException()))\n"); push(@implContent, " return false;\n"); } push(@implContent, " if (UNLIKELY(!nativeValue)) {\n"); push(@implContent, " throwAttributeTypeError(*state, \"$interfaceName\", \"$name\", \"$type\");\n"); push(@implContent, " return false;\n"); push(@implContent, " }\n"); push(@implContent, " }\n"); } else { push(@implContent, " auto nativeValue = $nativeValue;\n"); if ($mayThrowException) { push(@implContent, " if (UNLIKELY(state->hadException()))\n"); push(@implContent, " return false;\n"); } } if ($codeGenerator->IsEnumType($type)) { push (@implContent, " if (UNLIKELY(!nativeValue))\n"); push (@implContent, " return false;\n"); } if ($shouldPassByReference) { push(@implContent, " if (UNLIKELY(!nativeValue)) {\n"); push(@implContent, " throwAttributeTypeError(*state, \"$interfaceName\", \"$name\", \"$type\");\n"); push(@implContent, " return false;\n"); push(@implContent, " }\n"); } if ($svgPropertyOrListPropertyType) { if ($svgPropertyType) { push(@implContent, " if (impl.isReadOnly()) {\n"); push(@implContent, " setDOMException(state, NO_MODIFICATION_ALLOWED_ERR);\n"); push(@implContent, " return false;\n"); push(@implContent, " }\n"); $implIncludes{"ExceptionCode.h"} = 1; } push(@implContent, " $svgPropertyOrListPropertyType& podImpl = impl.propertyReference();\n"); if ($svgPropertyOrListPropertyType eq "float") { # Special case for JSSVGNumber push(@implContent, " podImpl = nativeValue;\n"); } else { push(@implContent, " podImpl.set$implSetterFunctionName(nativeValue"); push(@implContent, ", ec") if $setterRaisesException; push(@implContent, ");\n"); push(@implContent, " setDOMException(state, ec);\n") if $setterRaisesException; } if ($svgPropertyType) { if ($setterRaisesExceptionWithMessage) { push(@implContent, " if (LIKELY(!ec.code))\n"); push(@implContent, " impl.commitChange();\n"); } elsif ($setterRaisesException) { push(@implContent, " if (LIKELY(!ec))\n"); push(@implContent, " impl.commitChange();\n"); } else { push(@implContent, " impl.commitChange();\n"); } } push(@implContent, " return true;\n"); } else { my ($functionName, @arguments) = $codeGenerator->SetterExpression(\%implIncludes, $interfaceName, $attribute); if ($codeGenerator->IsTypedArrayType($type) and not $type eq "ArrayBuffer") { push(@arguments, "nativeValue.get()"); } elsif ($codeGenerator->IsEnumType($type)) { push(@arguments, "nativeValue.value()"); } else { push(@arguments, $shouldPassByReference ? "*nativeValue" : "WTFMove(nativeValue)"); } if ($attribute->signature->extendedAttributes->{"ImplementedBy"}) { my $implementedBy = $attribute->signature->extendedAttributes->{"ImplementedBy"}; AddToImplIncludes("${implementedBy}.h", $attribute->signature->extendedAttributes->{"Conditional"}); unshift(@arguments, "impl") if !$attribute->isStatic; $functionName = "WebCore::${implementedBy}::${functionName}"; } elsif ($attribute->isStatic) { $functionName = "${interfaceName}::${functionName}"; } else { $functionName = "impl.${functionName}"; } unshift(@arguments, GenerateCallWith($attribute->signature->extendedAttributes->{"SetterCallWith"}, \@implContent, "false")); unshift(@arguments, GenerateCallWith($attribute->signature->extendedAttributes->{"CallWith"}, \@implContent, "false")); push(@arguments, "ec") if $setterRaisesException; push(@implContent, " ${functionName}(" . join(", ", @arguments) . ");\n"); push(@implContent, " setDOMException(state, ec);\n") if $setterRaisesException; push(@implContent, " return true;\n"); } } push(@implContent, "}\n\n"); push(@implContent, "#endif\n") if $attributeConditionalString; push(@implContent, "\n"); } } if (($indexedGetterFunction || $namedGetterFunction) && !$interface->extendedAttributes->{"CustomEnumerateProperty"}) { push(@implContent, "void ${className}::getOwnPropertyNames(JSObject* object, ExecState* state, PropertyNameArray& propertyNames, EnumerationMode mode)\n"); push(@implContent, "{\n"); push(@implContent, " auto* thisObject = jsCast<${className}*>(object);\n"); push(@implContent, " ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n"); if ($indexedGetterFunction) { push(@implContent, " for (unsigned i = 0, count = thisObject->wrapped().length(); i < count; ++i)\n"); push(@implContent, " propertyNames.add(Identifier::from(state, i));\n"); } if ($namedGetterFunction) { # FIXME: We may need to add an IDL extended attribute at some point if an interface needs enumerable named properties. push(@implContent, " if (mode.includeDontEnumProperties()) {\n"); push(@implContent, " for (auto& propertyName : thisObject->wrapped().supportedPropertyNames())\n"); push(@implContent, " propertyNames.add(Identifier::fromString(state, propertyName));\n"); push(@implContent, " }\n"); } push(@implContent, " Base::getOwnPropertyNames(thisObject, state, propertyNames, mode);\n"); push(@implContent, "}\n\n"); } if (!$interface->extendedAttributes->{"NoInterfaceObject"}) { push(@implContent, "JSValue ${className}::getConstructor(VM& vm, const JSGlobalObject* globalObject)\n{\n"); push(@implContent, " return getDOMConstructor<${className}Constructor>(vm, *jsCast(globalObject));\n"); push(@implContent, "}\n\n"); if ($interface->extendedAttributes->{"NamedConstructor"}) { push(@implContent, "JSValue ${className}::getNamedConstructor(VM& vm, JSGlobalObject* globalObject)\n{\n"); push(@implContent, " return getDOMConstructor<${className}NamedConstructor>(vm, *jsCast(globalObject));\n"); push(@implContent, "}\n\n"); } } # Functions if ($numFunctions > 0) { my $inAppleCopyright = 0; foreach my $function (@{$interface->functions}) { next if IsJSBuiltin($interface, $function); my $needsAppleCopyright = $function->signature->extendedAttributes->{"AppleCopyright"}; if ($needsAppleCopyright) { if (!$inAppleCopyright) { push(@implContent, $beginAppleCopyrightForSourceFiles); $inAppleCopyright = 1; } } elsif ($inAppleCopyright) { push(@implContent, $endAppleCopyright); $inAppleCopyright = 0; } my $isCustom = HasCustomMethod($function->signature->extendedAttributes); my $isOverloaded = $function->{overloads} && @{$function->{overloads}} > 1; die "RaisesException and RaisesExceptionWithMessage are mutually exclusive" if $function->signature->extendedAttributes->{"RaisesException"} && $function->signature->extendedAttributes->{"RaisesExceptionWithMessage"}; my $raisesExceptionWithMessage = $function->signature->extendedAttributes->{"RaisesExceptionWithMessage"}; my $raisesException = $function->signature->extendedAttributes->{"RaisesException"} || $raisesExceptionWithMessage; next if $isCustom && $isOverloaded && $function->{overloadIndex} > 1; AddIncludesForTypeInImpl($function->signature->type) unless $isCustom or IsReturningPromise($function); my $functionName = GetFunctionName($interface, $className, $function); my $conditional = $function->signature->extendedAttributes->{"Conditional"}; if ($conditional) { my $conditionalString = $codeGenerator->GenerateConditionalStringFromAttributeValue($conditional); push(@implContent, "#if ${conditionalString}\n"); } my $functionReturn = "EncodedJSValue JSC_HOST_CALL"; if (!$isCustom && $isOverloaded) { # Append a number to an overloaded method's name to make it unique: $functionName = $functionName . $function->{overloadIndex}; # Make this function static to avoid compiler warnings, since we don't generate a prototype for it in the header. $functionReturn = "static inline EncodedJSValue"; } my $functionImplementationName = $function->signature->extendedAttributes->{"ImplementedAs"} || $codeGenerator->WK_lcfirst($function->signature->name); if (IsReturningPromise($function) && !$isCustom) { AddToImplIncludes("JSDOMPromise.h"); push(@implContent, <"} = 1; if ($function->signature->extendedAttributes->{"InvokesCustomElementLifecycleCallbacks"}) { push(@implContent, "#if ENABLE(CUSTOM_ELEMENTS)\n"); push(@implContent, " CustomElementLifecycleProcessingStack customElementLifecycleProcessingStack;\n"); push(@implContent, "#endif\n"); $implIncludes{"LifecycleCallbackQueue.h"} = 1; } if ($function->isStatic) { if ($isCustom) { GenerateArgumentsCountCheck(\@implContent, $function, $interface); push(@implContent, " return JSValue::encode(${className}::" . $functionImplementationName . "(state));\n"); } else { GenerateArgumentsCountCheck(\@implContent, $function, $interface); if ($raisesExceptionWithMessage) { push(@implContent, " ExceptionCodeWithMessage ec;\n"); } elsif ($raisesException) { push(@implContent, " ExceptionCode ec = 0;\n"); } my ($functionString, $dummy) = GenerateParametersCheck(\@implContent, $function, $interface, $functionImplementationName, $svgPropertyType, $svgPropertyOrListPropertyType, $svgListPropertyType); GenerateImplementationFunctionCall($function, $functionString, " ", $svgPropertyType, $interface); } } else { GenerateFunctionCastedThis($interface, $className, $function); if ($interface->extendedAttributes->{"CheckSecurity"} and !$function->signature->extendedAttributes->{"DoNotCheckSecurity"}) { if ($interfaceName eq "DOMWindow") { push(@implContent, " if (!BindingSecurity::shouldAllowAccessToDOMWindow(state, castedThis->wrapped()))\n"); } else { push(@implContent, " if (!shouldAllowAccessToFrame(state, castedThis->wrapped().frame()))\n"); } push(@implContent, " return JSValue::encode(jsUndefined());\n"); } if ($isCustom) { push(@implContent, " return JSValue::encode(castedThis->" . $functionImplementationName . "(*state));\n"); } else { push(@implContent, " auto& impl = castedThis->wrapped();\n"); if ($svgPropertyType) { push(@implContent, " if (impl.isReadOnly()) {\n"); push(@implContent, " setDOMException(state, NO_MODIFICATION_ALLOWED_ERR);\n"); push(@implContent, " return JSValue::encode(jsUndefined());\n"); push(@implContent, " }\n"); push(@implContent, " $svgPropertyType& podImpl = impl.propertyReference();\n"); $implIncludes{"ExceptionCode.h"} = 1; } # EventTarget needs to do some extra checks if castedThis is a JSDOMWindow. if ($interface->name eq "EventTarget") { $implIncludes{"DOMWindow.h"} = 1; push(@implContent, " if (auto* window = castedThis->wrapped().toDOMWindow()) {\n"); push(@implContent, " if (!window->frame() || !BindingSecurity::shouldAllowAccessToDOMWindow(state, *window))\n"); push(@implContent, " return JSValue::encode(jsUndefined());\n"); push(@implContent, " }\n"); } GenerateArgumentsCountCheck(\@implContent, $function, $interface); if ($raisesExceptionWithMessage) { push(@implContent, " ExceptionCodeWithMessage ec;\n"); } elsif ($raisesException) { push(@implContent, " ExceptionCode ec = 0;\n"); } if ($function->signature->extendedAttributes->{"CheckSecurityForNode"}) { push(@implContent, " if (!shouldAllowAccessToNode(state, impl." . $function->signature->name . "(" . ($raisesException ? "ec" : "") .")))\n"); push(@implContent, " return JSValue::encode(jsNull());\n"); $implIncludes{"JSDOMBinding.h"} = 1; } my ($functionString, $dummy) = GenerateParametersCheck(\@implContent, $function, $interface, $functionImplementationName, $svgPropertyType, $svgPropertyOrListPropertyType, $svgListPropertyType); GenerateImplementationFunctionCall($function, $functionString, " ", $svgPropertyType, $interface); } } push(@implContent, "}\n\n"); push(@implContent, "#endif\n\n") if $conditional; # Generate a function dispatching call to the rest of the overloads. GenerateOverloadedFunction($function, $interface) if !$isCustom && $isOverloaded && $function->{overloadIndex} == @{$function->{overloads}}; } push(@implContent, $endAppleCopyright) if $inAppleCopyright; } if ($interface->iterable) { GenerateImplementationIterableFunctions($interface); } if ($needsVisitChildren) { push(@implContent, "void ${className}::visitChildren(JSCell* cell, SlotVisitor& visitor)\n"); push(@implContent, "{\n"); push(@implContent, " auto* thisObject = jsCast<${className}*>(cell);\n"); push(@implContent, " ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n"); push(@implContent, " Base::visitChildren(thisObject, visitor);\n"); if ($codeGenerator->InheritsInterface($interface, "EventTarget")) { push(@implContent, " thisObject->wrapped().visitJSEventListeners(visitor);\n"); } push(@implContent, " thisObject->visitAdditionalChildren(visitor);\n") if $interface->extendedAttributes->{"JSCustomMarkFunction"}; if ($interface->extendedAttributes->{"ReportExtraMemoryCost"}) { push(@implContent, " visitor.reportExtraMemoryVisited(thisObject->wrapped().memoryCost());\n"); if ($interface->extendedAttributes->{"ReportExternalMemoryCost"}) {; push(@implContent, "#if ENABLE(RESOURCE_USAGE)\n"); push(@implContent, " visitor.reportExternalMemoryVisited(thisObject->wrapped().externalMemoryCost());\n"); push(@implContent, "#endif\n"); } } if ($numCachedAttributes > 0) { foreach (@{$interface->attributes}) { my $attribute = $_; if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) { push(@implContent, " visitor.append(&thisObject->m_" . $attribute->signature->name . ");\n"); } } } push(@implContent, "}\n\n"); } if (InstanceNeedsEstimatedSize($interface)) { push(@implContent, "size_t ${className}::estimatedSize(JSCell* cell)\n"); push(@implContent, "{\n"); push(@implContent, " auto* thisObject = jsCast<${className}*>(cell);\n"); push(@implContent, " return Base::estimatedSize(thisObject) + thisObject->wrapped().memoryCost();\n"); push(@implContent, "}\n\n"); } # Cached attributes are indeed allowed when there is a custom mark/visitChildren function. # The custom function must make sure to account for the cached attribute. # Uncomment the below line to temporarily enforce generated mark functions when cached attributes are present. # die "Can't generate binding for class with cached attribute and custom mark." if (($numCachedAttributes > 0) and ($interface->extendedAttributes->{"JSCustomMarkFunction"})); if ($indexedGetterFunction) { if ($indexedGetterFunction->signature->type eq "DOMString") { $implIncludes{"URL.h"} = 1; } if ($interfaceName =~ /^HTML\w*Collection$/ or $interfaceName eq "RadioNodeList") { $implIncludes{"JSNode.h"} = 1; $implIncludes{"Node.h"} = 1; } } if (ShouldGenerateWrapperOwnerCode($hasParent, $interface) && !GetCustomIsReachable($interface)) { push(@implContent, "bool JS${interfaceName}Owner::isReachableFromOpaqueRoots(JSC::Handle handle, void*, SlotVisitor& visitor)\n"); push(@implContent, "{\n"); # All ActiveDOMObjects implement hasPendingActivity(), but not all of them # increment their C++ reference counts when hasPendingActivity() becomes # true. As a result, ActiveDOMObjects can be prematurely destroyed before # their pending activities complete. To wallpaper over this bug, JavaScript # wrappers unconditionally keep ActiveDOMObjects with pending activity alive. # FIXME: Fix this lifetime issue in the DOM, and move this hasPendingActivity # check just above the (GetGenerateIsReachable($interface) eq "Impl") check below. my $emittedJSCast = 0; if ($codeGenerator->InheritsExtendedAttribute($interface, "ActiveDOMObject")) { push(@implContent, " auto* js${interfaceName} = jsCast(handle.slot()->asCell());\n"); $emittedJSCast = 1; push(@implContent, " if (js${interfaceName}->wrapped().hasPendingActivity())\n"); push(@implContent, " return true;\n"); } if ($codeGenerator->InheritsInterface($interface, "EventTarget")) { if (!$emittedJSCast) { push(@implContent, " auto* js${interfaceName} = jsCast(handle.slot()->asCell());\n"); $emittedJSCast = 1; } push(@implContent, " if (js${interfaceName}->wrapped().isFiringEventListeners())\n"); push(@implContent, " return true;\n"); } if ($codeGenerator->InheritsInterface($interface, "Node")) { if (!$emittedJSCast) { push(@implContent, " auto* js${interfaceName} = jsCast(handle.slot()->asCell());\n"); $emittedJSCast = 1; } push(@implContent, " if (JSNodeOwner::isReachableFromOpaqueRoots(handle, 0, visitor))\n"); push(@implContent, " return true;\n"); } if (GetGenerateIsReachable($interface)) { if (!$emittedJSCast) { push(@implContent, " auto* js${interfaceName} = jsCast(handle.slot()->asCell());\n"); $emittedJSCast = 1; } my $rootString; if (GetGenerateIsReachable($interface) eq "Impl") { $rootString = " ${implType}* root = &js${interfaceName}->wrapped();\n"; } elsif (GetGenerateIsReachable($interface) eq "ImplWebGLRenderingContext") { $rootString = " WebGLRenderingContextBase* root = WTF::getPtr(js${interfaceName}->wrapped().context());\n"; } elsif (GetGenerateIsReachable($interface) eq "ImplFrame") { $rootString = " Frame* root = WTF::getPtr(js${interfaceName}->wrapped().frame());\n"; $rootString .= " if (!root)\n"; $rootString .= " return false;\n"; } elsif (GetGenerateIsReachable($interface) eq "ImplDocument") { $rootString = " Document* root = WTF::getPtr(js${interfaceName}->wrapped().document());\n"; $rootString .= " if (!root)\n"; $rootString .= " return false;\n"; } elsif (GetGenerateIsReachable($interface) eq "ImplElementRoot") { $implIncludes{"Element.h"} = 1; $implIncludes{"JSNodeCustom.h"} = 1; $rootString = " Element* element = WTF::getPtr(js${interfaceName}->wrapped().element());\n"; $rootString .= " if (!element)\n"; $rootString .= " return false;\n"; $rootString .= " void* root = WebCore::root(element);\n"; } elsif ($interfaceName eq "CanvasRenderingContext") { $implIncludes{"Element.h"} = 1; $implIncludes{"JSNodeCustom.h"} = 1; $rootString = " void* root = WebCore::root(js${interfaceName}->wrapped().canvas());\n"; } elsif (GetGenerateIsReachable($interface) eq "ImplOwnerNodeRoot") { $implIncludes{"Element.h"} = 1; $implIncludes{"JSNodeCustom.h"} = 1; $rootString = " void* root = WebCore::root(js${interfaceName}->wrapped().ownerNode());\n"; } else { $rootString = " void* root = WebCore::root(&js${interfaceName}->wrapped());\n"; } push(@implContent, $rootString); push(@implContent, " return visitor.containsOpaqueRoot(root);\n"); } else { if (!$emittedJSCast) { push(@implContent, " UNUSED_PARAM(handle);\n"); } push(@implContent, " UNUSED_PARAM(visitor);\n"); push(@implContent, " return false;\n"); } push(@implContent, "}\n\n"); } if (ShouldGenerateWrapperOwnerCode($hasParent, $interface) && !$interface->extendedAttributes->{"JSCustomFinalize"}) { push(@implContent, "void JS${interfaceName}Owner::finalize(JSC::Handle handle, void* context)\n"); push(@implContent, "{\n"); push(@implContent, " auto* js${interfaceName} = jsCast(handle.slot()->asCell());\n"); push(@implContent, " auto& world = *static_cast(context);\n"); push(@implContent, " uncacheWrapper(world, &js${interfaceName}->wrapped(), js${interfaceName});\n"); push(@implContent, "}\n\n"); } if (ShouldGenerateToJSImplementation($hasParent, $interface)) { my $vtableNameGnu = GetGnuVTableNameForInterface($interface); my $vtableRefGnu = GetGnuVTableRefForInterface($interface); my $vtableRefWin = GetWinVTableRefForInterface($interface); push(@implContent, <&& impl)\n"); push(@implContent, "{\n"); push(@implContent, <(impl.ptr())); #if PLATFORM(WIN) void* expectedVTablePointer = reinterpret_cast(${vtableRefWin}); #else void* expectedVTablePointer = ${vtableRefGnu}; #if COMPILER(CLANG) // If this fails $implType does not have a vtable, so you need to add the // ImplementationLacksVTable attribute to the interface definition static_assert(__is_polymorphic($implType), "${implType} is not polymorphic"); #endif #endif // If you hit this assertion you either have a use after free bug, or // $implType has subclasses. If $implType has subclasses that get passed // to toJS() we currently require $interfaceName you to opt out of binding hardening // by adding the SkipVTableValidation attribute to the interface IDL definition RELEASE_ASSERT(actualVTablePointer == expectedVTablePointer); #endif END push(@implContent, <extendedAttributes->{"ImplementationLacksVTable"}; #if COMPILER(CLANG) // If you hit this failure the interface definition has the ImplementationLacksVTable // attribute. You should remove that attribute. If the class has subclasses // that may be passed through this toJS() function you should use the SkipVTableValidation // attribute to $interfaceName. static_assert(!__is_polymorphic($implType), "${implType} is polymorphic but the IDL claims it is not"); #endif END push(@implContent, <extendedAttributes->{"ReportExtraMemoryCost"}; globalObject->vm().heap.reportExtraMemoryAllocated(impl->memoryCost()); END push(@implContent, " return createWrapper<$className, $implType>(globalObject, WTFMove(impl));\n"); push(@implContent, "}\n\n"); push(@implContent, "JSC::JSValue toJS(JSC::ExecState* state, JSDOMGlobalObject* globalObject, $implType& impl)\n"); push(@implContent, "{\n"); push(@implContent, " return wrap(state, globalObject, impl);\n"); push(@implContent, "}\n\n"); } if (ShouldGenerateToWrapped($hasParent, $interface) and !$interface->extendedAttributes->{"JSCustomToNativeObject"}) { push(@implContent, "$implType* ${className}::toWrapped(JSC::JSValue value)\n"); push(@implContent, "{\n"); push(@implContent, " if (auto* wrapper = " . GetCastingHelperForThisObject($interface) . "(value))\n"); push(@implContent, " return &wrapper->wrapped();\n"); push(@implContent, " return nullptr;\n"); push(@implContent, "}\n"); } push(@implContent, "\n}\n"); my $conditionalString = $codeGenerator->GenerateConditionalString($interface); push(@implContent, "\n#endif // ${conditionalString}\n") if $conditionalString; } sub GenerateFunctionCastedThis { my ($interface, $className, $function) = @_; if ($interface->extendedAttributes->{"CustomProxyToJSObject"}) { push(@implContent, " $className* castedThis = to${className}(state->thisValue().toThis(state, NotStrictMode));\n"); push(@implContent, " if (UNLIKELY(!castedThis))\n"); push(@implContent, " return throwVMTypeError(state);\n"); } else { push(@implContent, " JSValue thisValue = state->thisValue();\n"); my $castingHelper = GetCastingHelperForThisObject($interface); my $interfaceName = $interface->name; if ($interfaceName eq "EventTarget") { # We allow calling the EventTarget API without an explicit 'this' value and fall back to using the global object instead. # As of early 2016, this matches Firefox and Chrome's behavior. push(@implContent, " auto castedThis = $castingHelper(thisValue.toThis(state, NotStrictMode));\n"); } else { push(@implContent, " auto castedThis = $castingHelper(thisValue);\n"); } my $domFunctionName = $function->signature->name; push(@implContent, " if (UNLIKELY(!castedThis))\n"); push(@implContent, " return throwThisTypeError(*state, \"$interfaceName\", \"$domFunctionName\");\n"); } push(@implContent, " ASSERT_GC_OBJECT_INHERITS(castedThis, ${className}::info());\n") unless $interface->name eq "EventTarget"; } sub GenerateCallWith { my $callWith = shift; return () unless $callWith; my $outputArray = shift; my $returnValue = shift; my $function = shift; my @callWithArgs; push(@callWithArgs, "*state") if $codeGenerator->ExtendedAttributeContains($callWith, "ScriptState"); if ($codeGenerator->ExtendedAttributeContains($callWith, "ScriptExecutionContext")) { push(@$outputArray, " auto* context = jsCast(state->lexicalGlobalObject())->scriptExecutionContext();\n"); push(@$outputArray, " if (!context)\n"); push(@$outputArray, " return" . ($returnValue ? " " . $returnValue : "") . ";\n"); push(@callWithArgs, "*context"); } if ($codeGenerator->ExtendedAttributeContains($callWith, "Document")) { $implIncludes{"Document.h"} = 1; push(@$outputArray, " auto* context = jsCast(state->lexicalGlobalObject())->scriptExecutionContext();\n"); push(@$outputArray, " if (!context)\n"); push(@$outputArray, " return" . ($returnValue ? " " . $returnValue : "") . ";\n"); push(@$outputArray, " ASSERT(context->isDocument());\n"); push(@$outputArray, " auto& document = downcast(*context);\n"); push(@callWithArgs, "document"); } if ($codeGenerator->ExtendedAttributeContains($callWith, "CallerDocument")) { $implIncludes{"Document.h"} = 1; push(@$outputArray, " auto* document = callerDOMWindow(state).document();\n"); push(@$outputArray, " if (!document)\n"); push(@$outputArray, " return" . ($returnValue ? " " . $returnValue : "") . ";\n"); push(@callWithArgs, "*document"); } if ($function and $codeGenerator->ExtendedAttributeContains($callWith, "ScriptArguments")) { push(@$outputArray, " RefPtr scriptArguments(Inspector::createScriptArguments(state, " . @{$function->parameters} . "));\n"); $implIncludes{""} = 1; $implIncludes{""} = 1; push(@callWithArgs, "WTFMove(scriptArguments)"); } push(@callWithArgs, "activeDOMWindow(state)") if $codeGenerator->ExtendedAttributeContains($callWith, "ActiveWindow"); push(@callWithArgs, "firstDOMWindow(state)") if $codeGenerator->ExtendedAttributeContains($callWith, "FirstWindow"); push(@callWithArgs, "callerDOMWindow(state)") if $codeGenerator->ExtendedAttributeContains($callWith, "CallerWindow"); return @callWithArgs; } sub GenerateArgumentsCountCheck { my $outputArray = shift; my $function = shift; my $interface = shift; my $numMandatoryParams = @{$function->parameters}; foreach my $param (reverse(@{$function->parameters})) { if ($param->isOptional or $param->isVariadic) { $numMandatoryParams--; } else { last; } } if ($numMandatoryParams >= 1) { push(@$outputArray, " if (UNLIKELY(state->argumentCount() < $numMandatoryParams))\n"); push(@$outputArray, " return throwVMError(state, createNotEnoughArgumentsError(state));\n"); } } my %automaticallyGeneratedDefaultValues = ( "any" => "undefined", # toString() will convert undefined to the string "undefined"; # (note that this optimizes a behavior that is almost never useful) "DOMString" => "\"undefined\"", # Dictionary(state, undefined) will construct an empty Dictionary. "Dictionary" => "[]", # JSValue::toBoolean() will convert undefined to false. "boolean" => "false", # JSValue::toInt*() / JSValue::toUint*() will convert undefined to 0. "byte" => "0", "long long" => "0", "long" => "0", "octet" => "0", "short" => "0", "unsigned long long" => "0", "unsigned long" => "0", "unsigned short" => "0", # toNumber() / toFloat() convert undefined to NaN. "double" => "NaN", "float" => "NaN", "unrestricted double" => "NaN", "unrestricted float" => "NaN", ); sub WillConvertUndefinedToDefaultParameterValue { my $parameterType = shift; my $defaultValue = shift; my $automaticallyGeneratedDefaultValue = $automaticallyGeneratedDefaultValues{$parameterType}; return 1 if defined $automaticallyGeneratedDefaultValue && $automaticallyGeneratedDefaultValue eq $defaultValue; # toRefPtrNativeArray() will convert undefined to an empty Vector. return 1 if $defaultValue eq "[]" && $codeGenerator->GetArrayOrSequenceType($parameterType); return 1 if $defaultValue eq "null" && $codeGenerator->IsWrapperType($parameterType); return 0; } sub GenerateParametersCheck { my ($outputArray, $function, $interface, $functionImplementationName, $svgPropertyType, $svgPropertyOrListPropertyType, $svgListPropertyType) = @_; my $interfaceName = $interface->name; my @arguments; my $functionName; my $implementedBy = $function->signature->extendedAttributes->{"ImplementedBy"}; my $numParameters = @{$function->parameters}; if ($implementedBy) { AddToImplIncludes("${implementedBy}.h", $function->signature->extendedAttributes->{"Conditional"}); unshift(@arguments, "impl") if !$function->isStatic; $functionName = "WebCore::${implementedBy}::${functionImplementationName}"; } elsif ($function->isStatic) { $functionName = "${interfaceName}::${functionImplementationName}"; } elsif ($svgPropertyOrListPropertyType and !$svgListPropertyType) { $functionName = "podImpl.${functionImplementationName}"; } else { $functionName = "impl.${functionImplementationName}"; } my $quotedFunctionName; if (!$function->signature->extendedAttributes->{"Constructor"}) { my $name = $function->signature->name; $quotedFunctionName = "\"$name\""; push(@arguments, GenerateCallWith($function->signature->extendedAttributes->{"CallWith"}, \@$outputArray, "JSValue::encode(jsUndefined())", $function)); } else { $quotedFunctionName = "nullptr"; } $implIncludes{"ExceptionCode.h"} = 1; $implIncludes{"JSDOMBinding.h"} = 1; my $argumentIndex = 0; foreach my $parameter (@{$function->parameters}) { my $type = $parameter->type; die "Optional parameters of non-nullable wrapper types are not supported" if $parameter->isOptional && !$parameter->isNullable && $codeGenerator->IsWrapperType($type); die "Optional parameters preceding variadic parameters are not supported" if ($parameter->isOptional && @{$function->parameters}[$numParameters - 1]->isVariadic); if ($parameter->isOptional && !defined($parameter->default)) { # As per Web IDL, optional dictionary parameters are always considered to have a default value of an empty dictionary, unless otherwise specified. $parameter->default("[]") if $type eq "Dictionary" or $codeGenerator->IsDictionaryType($type); # We use undefined as default value for optional parameters of type 'any' unless specified otherwise. $parameter->default("undefined") if $type eq "any"; # We use the null string as default value for parameters of type DOMString unless specified otherwise. $parameter->default("null") if $type eq "DOMString"; # As per Web IDL, passing undefined for a nullable parameter is treated as null. Therefore, use null as # default value for nullable parameters unless otherwise specified. $parameter->default("null") if $parameter->isNullable; # For callback parameters, the generated bindings treat undefined as null, so use null as implicit default value. $parameter->default("null") if $codeGenerator->IsCallbackInterface($type); } my $name = $parameter->name; my $value = $name; if ($codeGenerator->IsCallbackInterface($type)) { my $callbackClassName = GetCallbackClassName($type); $implIncludes{"$callbackClassName.h"} = 1; if ($parameter->isOptional) { push(@$outputArray, " RefPtr<$type> $name;\n"); push(@$outputArray, " if (!state->argument($argumentIndex).isUndefinedOrNull()) {\n"); if ($codeGenerator->IsFunctionOnlyCallbackInterface($type)) { push(@$outputArray, " if (!state->uncheckedArgument($argumentIndex).isFunction())\n"); } else { push(@$outputArray, " if (!state->uncheckedArgument($argumentIndex).isObject())\n"); } push(@$outputArray, " return throwArgumentMustBeFunctionError(*state, $argumentIndex, \"$name\", \"$interfaceName\", $quotedFunctionName);\n"); if ($function->isStatic) { AddToImplIncludes("CallbackFunction.h"); push(@$outputArray, " $name = createFunctionOnlyCallback<${callbackClassName}>(state, jsCast(state->lexicalGlobalObject()), state->uncheckedArgument($argumentIndex));\n"); } else { push(@$outputArray, " $name = ${callbackClassName}::create(asObject(state->uncheckedArgument($argumentIndex)), castedThis->globalObject());\n"); } push(@$outputArray, " }\n"); } else { if ($codeGenerator->IsFunctionOnlyCallbackInterface($type)) { push(@$outputArray, " if (UNLIKELY(!state->argument($argumentIndex).isFunction()))\n"); } else { push(@$outputArray, " if (UNLIKELY(!state->argument($argumentIndex).isObject()))\n"); } push(@$outputArray, " return throwArgumentMustBeFunctionError(*state, $argumentIndex, \"$name\", \"$interfaceName\", $quotedFunctionName);\n"); if ($function->isStatic) { AddToImplIncludes("CallbackFunction.h"); push(@$outputArray, " auto $name = createFunctionOnlyCallback<${callbackClassName}>(state, jsCast(state->lexicalGlobalObject()), state->uncheckedArgument($argumentIndex));\n"); } else { push(@$outputArray, " auto $name = ${callbackClassName}::create(asObject(state->uncheckedArgument($argumentIndex)), castedThis->globalObject());\n"); } } $value = "WTFMove($name)"; } elsif ($parameter->isVariadic) { my $nativeElementType = GetNativeType($interface, $type); if (!IsNativeType($type)) { push(@$outputArray, " Vector<$nativeElementType> $name;\n"); push(@$outputArray, " ASSERT($argumentIndex <= state->argumentCount());\n"); push(@$outputArray, " $name.reserveInitialCapacity(state->argumentCount() - $argumentIndex);\n"); push(@$outputArray, " for (unsigned i = $argumentIndex, count = state->argumentCount(); i < count; ++i) {\n"); push(@$outputArray, " auto* item = JS${type}::toWrapped(state->uncheckedArgument(i));\n"); push(@$outputArray, " if (!item)\n"); push(@$outputArray, " return throwArgumentTypeError(*state, i, \"$name\", \"$interfaceName\", $quotedFunctionName, \"$type\");\n"); push(@$outputArray, " $name.uncheckedAppend(item);\n"); push(@$outputArray, " }\n") } else { push(@$outputArray, " Vector<$nativeElementType> $name = toNativeArguments<$nativeElementType>(*state, $argumentIndex);\n"); push(@$outputArray, " if (UNLIKELY(state->hadException()))\n"); push(@$outputArray, " return JSValue::encode(jsUndefined());\n"); } $value = "WTFMove($name)"; } elsif ($codeGenerator->IsEnumType($type)) { my $className = GetEnumerationClassName($interface, $type); $implIncludes{""} = 1; my $nativeType = $className; my $optionalValue = "optionalValue"; my $defineOptionalValue = "auto optionalValue"; my $indent = ""; if ($parameter->isOptional && !defined($parameter->default)) { $nativeType = "Optional<$className>"; $optionalValue = $name; $defineOptionalValue = $name; } push(@$outputArray, " auto ${name}Value = state->argument($argumentIndex);\n"); push(@$outputArray, " $nativeType $name;\n"); if ($parameter->isOptional) { if (!defined $parameter->default) { push(@$outputArray, " if (!${name}Value.isUndefined()) {\n"); } else { push(@$outputArray, " if (${name}Value.isUndefined()) {\n"); push(@$outputArray, " $name = " . GenerateDefaultValue($interface, $parameter) . ";\n"); push(@$outputArray, " } else {\n"); } $indent = " "; } push(@$outputArray, "$indent $defineOptionalValue = parse<$className>(*state, ${name}Value);\n"); push(@$outputArray, "$indent if (UNLIKELY(state->hadException()))\n"); push(@$outputArray, "$indent return JSValue::encode(jsUndefined());\n"); push(@$outputArray, "$indent if (UNLIKELY(!$optionalValue))\n"); push(@$outputArray, "$indent return throwArgumentMustBeEnumError(*state, $argumentIndex, \"$name\", \"$interfaceName\", $quotedFunctionName, expectedEnumerationValues<$className>());\n"); push(@$outputArray, "$indent $name = optionalValue.value();\n") if $optionalValue ne $name; push(@$outputArray, " }\n") if $indent ne ""; } else { my $outer; my $inner; my $nativeType = GetNativeTypeFromSignature($interface, $parameter); my $isTearOff = $codeGenerator->IsSVGTypeNeedingTearOff($type) && $interfaceName !~ /List$/; my $shouldPassByReference = $isTearOff || ShouldPassWrapperByReference($parameter, $interface); if ($function->signature->extendedAttributes->{"StrictTypeChecking"} && !$shouldPassByReference && $codeGenerator->IsWrapperType($type)) { $implIncludes{""} = 1; my $checkedArgument = "state->argument($argumentIndex)"; my $uncheckedArgument = "state->uncheckedArgument($argumentIndex)"; my ($nativeValue, $mayThrowException) = JSValueToNative($interface, $parameter, $uncheckedArgument, $function->signature->extendedAttributes->{"Conditional"}); push(@$outputArray, " $nativeType $name = nullptr;\n"); push(@$outputArray, " if (!$checkedArgument.isUndefinedOrNull()) {\n"); push(@$outputArray, " $name = $nativeValue;\n"); if ($mayThrowException) { push(@$outputArray, " if (UNLIKELY(state->hadException()))\n"); push(@$outputArray, " return JSValue::encode(jsUndefined());\n"); } push(@$outputArray, " if (UNLIKELY(!$name))\n"); push(@$outputArray, " return throwArgumentTypeError(*state, $argumentIndex, \"$name\", \"$interfaceName\", $quotedFunctionName, \"$type\");\n"); push(@$outputArray, " }\n"); } else { if ($parameter->isOptional && defined($parameter->default) && !WillConvertUndefinedToDefaultParameterValue($type, $parameter->default)) { my $defaultValue = $parameter->default; # String-related optimizations. if ($type eq "DOMString") { my $useAtomicString = $parameter->extendedAttributes->{"AtomicString"}; if ($defaultValue eq "null") { $defaultValue = $useAtomicString ? "nullAtom" : "String()"; } elsif ($defaultValue eq "\"\"") { $defaultValue = $useAtomicString ? "emptyAtom" : "emptyString()"; } else { $defaultValue = $useAtomicString ? "AtomicString($defaultValue, AtomicString::ConstructFromLiteral)" : "ASCIILiteral($defaultValue)"; } } else { $defaultValue = "nullptr" if $defaultValue eq "null"; $defaultValue = "PNaN" if $defaultValue eq "NaN"; $defaultValue = "$nativeType()" if $defaultValue eq "[]"; $defaultValue = "JSValue::JSUndefined" if $defaultValue eq "undefined"; } $outer = "state->argument($argumentIndex).isUndefined() ? $defaultValue : "; $inner = "state->uncheckedArgument($argumentIndex)"; } elsif ($parameter->isOptional && !defined($parameter->default)) { # Use WTF::Optional<>() for optional parameters that are missing or undefined and that do not have a default value in the IDL. $outer = "state->argument($argumentIndex).isUndefined() ? Optional<$nativeType>() : "; $inner = "state->uncheckedArgument($argumentIndex)"; } else { $outer = ""; $inner = "state->argument($argumentIndex)"; } my ($nativeValue, $mayThrowException) = JSValueToNative($interface, $parameter, $inner, $function->signature->extendedAttributes->{"Conditional"}); push(@$outputArray, " auto $name = ${outer}${nativeValue};\n"); $value = "WTFMove($name)"; if ($mayThrowException) { push(@$outputArray, " if (UNLIKELY(state->hadException()))\n"); push(@$outputArray, " return JSValue::encode(jsUndefined());\n"); } } if ($shouldPassByReference) { push(@$outputArray, " if (UNLIKELY(!$name))\n"); push(@$outputArray, " return throwArgumentTypeError(*state, $argumentIndex, \"$name\", \"$interfaceName\", $quotedFunctionName, \"$type\");\n"); $value = $isTearOff ? "$name->propertyReference()" : "*$name"; } if ($codeGenerator->IsTypedArrayType($type) and $parameter->type ne "ArrayBuffer") { $value = $shouldPassByReference ? "$name.releaseNonNull()" : "WTFMove($name)"; } } push(@arguments, $value); $argumentIndex++; } push @arguments, GenerateReturnParameters($function); return ("$functionName(" . join(", ", @arguments) . ")", scalar @arguments); } sub GenerateReturnParameters { my $function = shift; my @arguments; if (IsReturningPromise($function)) { if ($function->isStatic) { push(@arguments, "DeferredWrapper(state, jsCast(state->lexicalGlobalObject()), promiseDeferred)"); } else { push(@arguments, "DeferredWrapper(state, castedThis->globalObject(), promiseDeferred)"); } } push(@arguments, "ec") if $function->signature->extendedAttributes->{"RaisesException"} || $function->signature->extendedAttributes->{"RaisesExceptionWithMessage"}; return @arguments; } sub GenerateCallbackHeader { my ($object, $interface) = @_; my $interfaceName = $interface->name; my $className = "JS$interfaceName"; # - Add default header template and header protection push(@headerContentHeader, GenerateHeaderContentHeader($interface)); $headerIncludes{"ActiveDOMCallback.h"} = 1; $headerIncludes{"$interfaceName.h"} = 1; $headerIncludes{"JSCallbackData.h"} = 1; $headerIncludes{""} = 1; push(@headerContent, "\nnamespace WebCore {\n\n"); push(@headerContent, "class $className : public $interfaceName, public ActiveDOMCallback {\n"); push(@headerContent, "public:\n"); # The static create() method. push(@headerContent, " static Ref<$className> create(JSC::JSObject* callback, JSDOMGlobalObject* globalObject)\n"); push(@headerContent, " {\n"); push(@headerContent, " return adoptRef(*new $className(callback, globalObject));\n"); push(@headerContent, " }\n\n"); # ScriptExecutionContext push(@headerContent, " virtual ScriptExecutionContext* scriptExecutionContext() const { return ContextDestructionObserver::scriptExecutionContext(); }\n\n"); # Destructor push(@headerContent, " virtual ~$className();\n"); push(@headerContent, " " . GetJSCallbackDataType($interface) . "* callbackData() { return m_data; }\n"); # Constructor object getter. if (@{$interface->constants}) { push(@headerContent, " static JSC::JSValue getConstructor(JSC::VM&, const JSC::JSGlobalObject*);\n"); } if ($interface->extendedAttributes->{"CallbackNeedsOperatorEqual"}) { push(@headerContent, " virtual bool operator==(const $interfaceName&) const;\n\n") } # Functions my $numFunctions = @{$interface->functions}; if ($numFunctions > 0) { push(@headerContent, "\n // Functions\n"); foreach my $function (@{$interface->functions}) { my @arguments = (); foreach my $parameter (@{$function->parameters}) { push(@arguments, GetNativeTypeForCallbacks($interface, $parameter->type) . " " . $parameter->name); } push(@headerContent, " virtual " . GetNativeTypeForCallbacks($interface, $function->signature->type) . " " . $function->signature->name . "(" . join(", ", @arguments) . ");\n"); } } push(@headerContent, "\nprivate:\n"); # Constructor push(@headerContent, " $className(JSC::JSObject* callback, JSDOMGlobalObject*);\n\n"); # Private members push(@headerContent, " " . GetJSCallbackDataType($interface) . "* m_data;\n"); push(@headerContent, "};\n\n"); # toJS(). push(@headerContent, "JSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject*, $interfaceName&);\n"); push(@headerContent, "inline JSC::JSValue toJS(JSC::ExecState* state, JSDOMGlobalObject* globalObject, $interfaceName* impl) { return impl ? toJS(state, globalObject, *impl) : JSC::jsNull(); }\n\n"); push(@headerContent, "} // namespace WebCore\n"); my $conditionalString = $codeGenerator->GenerateConditionalString($interface); push(@headerContent, "\n#endif // ${conditionalString}\n") if $conditionalString; } sub GenerateCallbackImplementation { my ($object, $interface, $enumerations) = @_; my $interfaceName = $interface->name; my $visibleInterfaceName = $codeGenerator->GetVisibleInterfaceName($interface); my $className = "JS$interfaceName"; # - Add default header template push(@implContentHeader, GenerateImplementationContentHeader($interface)); $implIncludes{"ScriptExecutionContext.h"} = 1; $implIncludes{""} = 1; @implContent = (); push(@implContent, "\nusing namespace JSC;\n\n"); push(@implContent, "namespace WebCore {\n\n"); push(@implContent, GenerateEnumerationImplementationContent($interface, $enumerations)); # Constructor push(@implContent, "${className}::${className}(JSObject* callback, JSDOMGlobalObject* globalObject)\n"); if ($interface->extendedAttributes->{"CallbackNeedsOperatorEqual"}) { push(@implContent, " : ${interfaceName}(${className}Type)\n"); } else { push(@implContent, " : ${interfaceName}()\n"); } push(@implContent, " , ActiveDOMCallback(globalObject->scriptExecutionContext())\n"); push(@implContent, " , m_data(new " . GetJSCallbackDataType($interface) . "(callback, this))\n"); push(@implContent, "{\n"); push(@implContent, "}\n\n"); # Destructor push(@implContent, "${className}::~${className}()\n"); push(@implContent, "{\n"); push(@implContent, " ScriptExecutionContext* context = scriptExecutionContext();\n"); push(@implContent, " // When the context is destroyed, all tasks with a reference to a callback\n"); push(@implContent, " // should be deleted. So if the context is 0, we are on the context thread.\n"); push(@implContent, " if (!context || context->isContextThread())\n"); push(@implContent, " delete m_data;\n"); push(@implContent, " else\n"); push(@implContent, " context->postTask(DeleteCallbackDataTask(m_data));\n"); push(@implContent, "#ifndef NDEBUG\n"); push(@implContent, " m_data = nullptr;\n"); push(@implContent, "#endif\n"); push(@implContent, "}\n\n"); if ($interface->extendedAttributes->{"CallbackNeedsOperatorEqual"}) { push(@implContent, "bool ${className}::operator==(const ${interfaceName}& other) const\n"); push(@implContent, "{\n"); push(@implContent, " if (other.type() != type())\n"); push(@implContent, " return false;\n"); push(@implContent, " return static_cast(&other)->m_data->callback() == m_data->callback();\n"); push(@implContent, "}\n\n"); } # Constants. my $numConstants = @{$interface->constants}; if ($numConstants > 0) { GenerateConstructorDeclaration(\@implContent, $className, $interface, $interfaceName); my $hashSize = 0; my $hashName = $className . "ConstructorTable"; my @hashKeys = (); my @hashValue1 = (); my @hashValue2 = (); my @hashSpecials = (); my %conditionals = (); foreach my $constant (@{$interface->constants}) { my $name = $constant->name; push(@hashKeys, $name); push(@hashValue1, $constant->value); push(@hashValue2, "0"); push(@hashSpecials, "DontDelete | ReadOnly | ConstantInteger"); my $implementedBy = $constant->extendedAttributes->{"ImplementedBy"}; if ($implementedBy) { $implIncludes{"${implementedBy}.h"} = 1; } my $conditional = $constant->extendedAttributes->{"Conditional"}; if ($conditional) { $conditionals{$name} = $conditional; } $hashSize++; } $object->GenerateHashTable($hashName, $hashSize, \@hashKeys, \@hashSpecials, \@hashValue1, \@hashValue2, \%conditionals, 1) if $hashSize > 0; push(@implContent, $codeGenerator->GenerateCompileTimeCheckForEnumsIfNeeded($interface)); GenerateConstructorDefinitions(\@implContent, $className, "", $visibleInterfaceName, $interface); push(@implContent, "JSValue ${className}::getConstructor(VM& vm, const JSGlobalObject* globalObject)\n{\n"); push(@implContent, " return getDOMConstructor<${className}Constructor>(vm, *jsCast(globalObject));\n"); push(@implContent, "}\n\n"); } # Functions. my $numFunctions = @{$interface->functions}; if ($numFunctions > 0) { push(@implContent, "\n// Functions\n"); foreach my $function (@{$interface->functions}) { my @params = @{$function->parameters}; if ($function->signature->extendedAttributes->{"Custom"} || GetNativeType($interface, $function->signature->type) ne "bool") { next; } AddIncludesForTypeInImpl($function->signature->type); my $functionName = $function->signature->name; push(@implContent, "\n" . GetNativeTypeForCallbacks($interface, $function->signature->type) . " ${className}::${functionName}("); my @args = (); my @argsCheck = (); foreach my $param (@params) { my $paramName = $param->name; AddIncludesForTypeInImpl($param->type, 1); push(@args, GetNativeTypeForCallbacks($interface, $param->type) . " " . $paramName); } push(@implContent, join(", ", @args)); push(@implContent, ")\n"); push(@implContent, "{\n"); push(@implContent, @argsCheck) if @argsCheck; push(@implContent, " if (!canInvokeCallback())\n"); push(@implContent, " return true;\n\n"); push(@implContent, " Ref<$className> protectedThis(*this);\n\n"); push(@implContent, " JSLockHolder lock(m_data->globalObject()->vm());\n\n"); push(@implContent, " ExecState* state = m_data->globalObject()->globalExec();\n"); push(@implContent, " MarkedArgumentBuffer args;\n"); foreach my $param (@params) { my $paramName = $param->name; push(@implContent, " args.append(" . NativeToJSValue($param, 1, $interface, $paramName, "m_data") . ");\n"); } push(@implContent, "\n NakedPtr returnedException;\n"); my $propertyToLookup = "Identifier::fromString(state, \"${functionName}\")"; my $invokeMethod = "JSCallbackData::CallbackType::FunctionOrObject"; if ($codeGenerator->ExtendedAttributeContains($interface->extendedAttributes->{"Callback"}, "FunctionOnly")) { # For callback functions, do not look up callable property on the user object. # https://heycam.github.io/webidl/#es-callback-function $invokeMethod = "JSCallbackData::CallbackType::Function"; $propertyToLookup = "Identifier()"; push(@implContent, " UNUSED_PARAM(state);\n"); } elsif ($numFunctions > 1) { # The callback interface has more than one operation so we should not call the user object as a function. # instead, we should look for a property with the same name as the operation on the user object. # https://heycam.github.io/webidl/#es-user-objects $invokeMethod = "JSCallbackData::CallbackType::Object"; } push(@implContent, " m_data->invokeCallback(args, $invokeMethod, $propertyToLookup, returnedException);\n"); # FIXME: We currently just report the exception. We should probably add an extended attribute to indicate when # we want the exception to be rethrown instead. push(@implContent, " if (returnedException)\n"); push(@implContent, " reportException(state, returnedException);\n"); push(@implContent, " return !returnedException;\n"); push(@implContent, "}\n"); } } # toJS() implementation. push(@implContent, "\nJSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject*, $interfaceName& impl)\n"); push(@implContent, "{\n"); push(@implContent, " if (!static_cast<${className}&>(impl).callbackData())\n"); push(@implContent, " return jsNull();\n\n"); push(@implContent, " return static_cast<${className}&>(impl).callbackData()->callback();\n\n"); push(@implContent, "}\n"); push(@implContent, "\n}\n"); my $conditionalString = $codeGenerator->GenerateConditionalString($interface); push(@implContent, "\n#endif // ${conditionalString}\n") if $conditionalString; if ($interface->extendedAttributes->{"AppleCopyright"}) { push(@implContent, split("\r", $endAppleCopyright)); } } sub GenerateImplementationFunctionCall() { my ($function, $functionString, $indent, $svgPropertyType, $interface) = @_; my $nondeterministic = $function->signature->extendedAttributes->{"Nondeterministic"}; my $raisesExceptionWithMessage = $function->signature->extendedAttributes->{"RaisesExceptionWithMessage"}; my $raisesException = $function->signature->extendedAttributes->{"RaisesException"} || $raisesExceptionWithMessage; if ($function->signature->type eq "void" || IsReturningPromise($function)) { if ($nondeterministic) { AddToImplIncludes("", "WEB_REPLAY"); push(@implContent, "#if ENABLE(WEB_REPLAY)\n"); push(@implContent, $indent . "InputCursor& cursor = state->lexicalGlobalObject()->inputCursor();\n"); push(@implContent, $indent . "if (!cursor.isReplaying()) {\n"); push(@implContent, $indent . " $functionString;\n"); push(@implContent, $indent . " setDOMException(state, ec);\n") if $raisesException; push(@implContent, $indent . "}\n"); push(@implContent, "#else\n"); push(@implContent, $indent . "$functionString;\n"); push(@implContent, $indent . "setDOMException(state, ec);\n") if $raisesException; push(@implContent, "#endif\n"); } else { push(@implContent, $indent . "$functionString;\n"); push(@implContent, $indent . "setDOMException(state, ec);\n") if $raisesException; } if ($svgPropertyType and !$function->isStatic) { if ($raisesExceptionWithMessage) { push(@implContent, $indent . "if (LIKELY(!ec.code))\n"); push(@implContent, $indent . " impl.commitChange();\n"); } elsif ($raisesException) { push(@implContent, $indent . "if (LIKELY(!ec))\n"); push(@implContent, $indent . " impl.commitChange();\n"); } else { push(@implContent, $indent . "impl.commitChange();\n"); } } push(@implContent, $indent . "return JSValue::encode(jsUndefined());\n"); } else { my $thisObject = $function->isStatic ? 0 : "castedThis"; if ($nondeterministic) { AddToImplIncludes("MemoizedDOMResult.h", "WEB_REPLAY"); AddToImplIncludes("", "WEB_REPLAY"); AddToImplIncludes("", "WEB_REPLAY"); my $nativeType = GetNativeTypeFromSignature($interface, $function->signature); my $memoizedType = GetNativeTypeForMemoization($interface, $function->signature->type); my $bindingName = $interface->name . "." . $function->signature->name; push(@implContent, $indent . "JSValue result;\n"); push(@implContent, "#if ENABLE(WEB_REPLAY)\n"); push(@implContent, $indent . "InputCursor& cursor = state->lexicalGlobalObject()->inputCursor();\n"); push(@implContent, $indent . "static NeverDestroyed bindingName(\"$bindingName\", AtomicString::ConstructFromLiteral);\n"); push(@implContent, $indent . "if (cursor.isCapturing()) {\n"); push(@implContent, $indent . " $nativeType memoizedResult = $functionString;\n"); my $exceptionCode = $raisesExceptionWithMessage ? "ec.code" : ($raisesException ? "ec" : "0"); push(@implContent, $indent . " cursor.appendInput>(bindingName.get().string(), memoizedResult, $exceptionCode);\n"); push(@implContent, $indent . " result = " . NativeToJSValue($function->signature, 1, $interface, "memoizedResult", $thisObject) . ";\n"); push(@implContent, $indent . "} else if (cursor.isReplaying()) {\n"); push(@implContent, $indent . " MemoizedDOMResultBase* input = cursor.fetchInput();\n"); push(@implContent, $indent . " $memoizedType memoizedResult;\n"); # FIXME: the generated code should report an error if an input cannot be fetched or converted. push(@implContent, $indent . " if (input && input->convertTo<$memoizedType>(memoizedResult)) {\n"); push(@implContent, $indent . " result = " . NativeToJSValue($function->signature, 1, $interface, "memoizedResult", $thisObject) . ";\n"); push(@implContent, $indent . " ec.code = input->exceptionCode();\n") if $raisesExceptionWithMessage; push(@implContent, $indent . " ec = input->exceptionCode();\n") if $raisesException && !$raisesExceptionWithMessage; push(@implContent, $indent . " } else\n"); push(@implContent, $indent . " result = " . NativeToJSValue($function->signature, 1, $interface, $functionString, $thisObject) . ";\n"); push(@implContent, $indent . "} else\n"); push(@implContent, $indent . " result = " . NativeToJSValue($function->signature, 1, $interface, $functionString, $thisObject) . ";\n"); push(@implContent, "#else\n"); push(@implContent, $indent . "result = " . NativeToJSValue($function->signature, 1, $interface, $functionString, $thisObject) . ";\n"); push(@implContent, "#endif\n"); } else { push(@implContent, $indent . "JSValue result = " . NativeToJSValue($function->signature, 1, $interface, $functionString, $thisObject) . ";\n"); } push(@implContent, "\n" . $indent . "setDOMException(state, ec);\n") if $raisesException; if ($codeGenerator->ExtendedAttributeContains($function->signature->extendedAttributes->{"CallWith"}, "ScriptState")) { push(@implContent, $indent . "if (UNLIKELY(state->hadException()))\n"); push(@implContent, $indent . " return JSValue::encode(jsUndefined());\n"); } push(@implContent, $indent . "return JSValue::encode(result);\n"); } } sub IsValueIterableInterface { my $interface = shift; return 0 unless $interface->iterable; return 0 if length $interface->iterable->keyType; # FIXME: See https://webkit.org/b/159140, we should die if the next check is false. return 0 unless GetIndexedGetterFunction($interface); return 1; } sub IsKeyValueIterableInterface { my $interface = shift; return 0 unless $interface->iterable; return 0 if IsValueIterableInterface($interface); return 1; } sub GenerateImplementationIterableFunctions { my $interface = shift; my $interfaceName = $interface->name; my $className = "JS$interfaceName"; my $visibleInterfaceName = $codeGenerator->GetVisibleInterfaceName($interface); AddToImplIncludes("JSDOMIterator.h"); return unless IsKeyValueIterableInterface($interface); push(@implContent, <; using ${interfaceName}IteratorPrototype = JSDOMIteratorPrototype<${className}>; template<> const JSC::ClassInfo ${interfaceName}Iterator::s_info = { "${visibleInterfaceName} Iterator", &Base::s_info, 0, CREATE_METHOD_TABLE(${interfaceName}Iterator) }; template<> const JSC::ClassInfo ${interfaceName}IteratorPrototype::s_info = { "${visibleInterfaceName} Iterator", &Base::s_info, 0, CREATE_METHOD_TABLE(${interfaceName}IteratorPrototype) }; END foreach my $function (@{$interface->iterable->functions}) { my $propertyName = $function->signature->name; my $functionName = GetFunctionName($interface, $className, $function); if (not $propertyName eq "forEach") { my $iterationKind = "KeyValue"; $iterationKind = "Key" if $propertyName eq "keys"; $iterationKind = "Value" if $propertyName eq "values"; $iterationKind = "Value" if $propertyName eq "[Symbol.Iterator]" and not $interface->iterable->isKeyValue; push(@implContent, <(*state, IterationKind::${iterationKind}, "${propertyName}"); } END } else { push(@implContent, <(*state, "${propertyName}"); } END } } } sub addIterableProperties() { my $interface = shift; my $className = shift; if ($interface->iterable->extendedAttributes->{"EnabledAtRuntime"}) { AddToImplIncludes("RuntimeEnabledFeatures.h"); my $enable_function = GetRuntimeEnableFunctionName($interface->iterable); push(@implContent, " if (${enable_function}()) {\n "); } if (IsKeyValueIterableInterface($interface)) { my $functionName = GetFunctionName($interface, $className, @{$interface->iterable->functions}[0]); push(@implContent, " putDirect(vm, vm.propertyNames->iteratorSymbol, JSFunction::create(vm, globalObject(), 0, ASCIILiteral(\"[Symbol.Iterator]\"), $functionName), DontEnum);\n"); } else { push(@implContent, " addValueIterableMethods(*globalObject(), *this);\n"); } if ($interface->iterable->extendedAttributes->{"EnabledAtRuntime"}) { push(@implContent, " }\n"); } } sub GetNativeTypeFromSignature { my ($interface, $signature) = @_; return GetNativeType($interface, $signature->type); } my %nativeType = ( "DOMString" => "String", "DOMStringList" => "RefPtr", "DOMTimeStamp" => "DOMTimeStamp", "Date" => "double", "Dictionary" => "Dictionary", "SerializedScriptValue" => "RefPtr", "XPathNSResolver" => "RefPtr", "any" => "JSC::JSValue", "boolean" => "bool", "byte" => "int8_t", "double" => "double", "float" => "float", "long long" => "int64_t", "long" => "int32_t", "octet" => "uint8_t", "short" => "int16_t", "unrestricted double" => "double", "unrestricted float" => "float", "unsigned long long" => "uint64_t", "unsigned long" => "uint32_t", "unsigned short" => "uint16_t", ); sub GetNativeType { my ($interface, $type) = @_; return $nativeType{$type} if exists $nativeType{$type}; return GetEnumerationClassName($interface, $type) if $codeGenerator->IsEnumType($type); return GetDictionaryClassName($interface, $type) if $codeGenerator->IsDictionaryType($type); my $tearOffType = $codeGenerator->GetSVGTypeNeedingTearOff($type); return "${tearOffType}*" if $tearOffType; return "RefPtr<${type}>" if $codeGenerator->IsTypedArrayType($type) and $type ne "ArrayBuffer"; my $arrayOrSequenceType = $codeGenerator->GetArrayOrSequenceType($type); return "Vector<" . GetNativeVectorInnerType($arrayOrSequenceType) . ">" if $arrayOrSequenceType; return "${type}*"; } sub ShouldPassWrapperByReference { my $parameter = shift; my $interface = shift; my $nativeType = GetNativeType($interface, $parameter->type); return $codeGenerator->ShouldPassWrapperByReference($parameter, $interface) && (substr($nativeType, -1) eq '*' || $nativeType =~ /^RefPtr/); } sub GetNativeVectorInnerType { my $arrayOrSequenceType = shift; return $nativeType{$arrayOrSequenceType} if exists $nativeType{$arrayOrSequenceType}; return "RefPtr<${arrayOrSequenceType}>"; } sub GetNativeTypeForCallbacks { my ($interface, $type) = @_; return "RefPtr&&" if $type eq "SerializedScriptValue"; return "RefPtr>&&" if $type eq "DOMStringList"; return "const String&" if $type eq "DOMString"; return GetNativeType($interface, $type); } sub GetNativeTypeForMemoization { my ($interface, $type) = @_; return GetNativeType($interface, $type); } sub GetSVGPropertyTypes { my $implType = shift; my $svgPropertyType; my $svgListPropertyType; my $svgNativeType; return ($svgPropertyType, $svgListPropertyType, $svgNativeType) if not $implType =~ /SVG/; $svgNativeType = $codeGenerator->GetSVGTypeNeedingTearOff($implType); return ($svgPropertyType, $svgListPropertyType, $svgNativeType) if not $svgNativeType; my $svgWrappedNativeType = $codeGenerator->GetSVGWrappedTypeNeedingTearOff($implType); if ($svgNativeType =~ /SVGPropertyTearOff/) { $svgPropertyType = $svgWrappedNativeType; $headerIncludes{"$svgWrappedNativeType.h"} = 1; $headerIncludes{"SVGAnimatedPropertyTearOff.h"} = 1; } elsif ($svgNativeType =~ /SVGListPropertyTearOff/ or $svgNativeType =~ /SVGStaticListPropertyTearOff/) { $svgListPropertyType = $svgWrappedNativeType; $headerIncludes{"$svgWrappedNativeType.h"} = 1; $headerIncludes{"SVGAnimatedListPropertyTearOff.h"} = 1; } elsif ($svgNativeType =~ /SVGTransformListPropertyTearOff/) { $svgListPropertyType = $svgWrappedNativeType; $headerIncludes{"$svgWrappedNativeType.h"} = 1; $headerIncludes{"SVGAnimatedListPropertyTearOff.h"} = 1; $headerIncludes{"SVGTransformListPropertyTearOff.h"} = 1; } elsif ($svgNativeType =~ /SVGPathSegListPropertyTearOff/) { $svgListPropertyType = $svgWrappedNativeType; $headerIncludes{"$svgWrappedNativeType.h"} = 1; $headerIncludes{"SVGAnimatedListPropertyTearOff.h"} = 1; $headerIncludes{"SVGPathSegListPropertyTearOff.h"} = 1; } return ($svgPropertyType, $svgListPropertyType, $svgNativeType); } sub IsNativeType { my $type = shift; return exists $nativeType{$type}; } sub GetIntegerConversionConfiguration { my $signature = shift; return "EnforceRange" if $signature->extendedAttributes->{"EnforceRange"}; return "Clamp" if $signature->extendedAttributes->{"Clamp"}; return "NormalConversion"; } # Returns (convertString, mayThrowException). sub JSValueToNative { my ($interface, $signature, $value, $conditional) = @_; my $type = $signature->type; if ($codeGenerator->IsIntegerType($type)) { my $nativeType = GetNativeType($interface, $type); my $conversionType = GetIntegerConversionConfiguration($signature); AddToImplIncludes("JSDOMConvert.h"); return ("convert<$nativeType>(*state, $value, $conversionType)", 1); } if ($type eq "DOMString") { return ("AtomicString($value.toString(state)->toExistingAtomicString(state))", 1) if $signature->extendedAttributes->{"RequiresExistingAtomicString"}; if ($signature->extendedAttributes->{"TreatNullAs"}) { return ("valueToStringTreatingNullAsEmptyString(state, $value)", 1) if $signature->extendedAttributes->{"TreatNullAs"} eq "EmptyString"; return ("valueToStringWithNullCheck(state, $value)", 1) if $signature->extendedAttributes->{"TreatNullAs"} eq "LegacyNullString"; } return ("valueToStringWithUndefinedOrNullCheck(state, $value)", 1) if $signature->isNullable; return ("$value.toString(state)->toAtomicString(state)", 1) if $signature->extendedAttributes->{"AtomicString"}; return ("$value.toWTFString(state)", 1); } if ($type eq "SerializedScriptValue") { AddToImplIncludes("SerializedScriptValue.h", $conditional); return ("SerializedScriptValue::create(state, $value, 0, 0)", 1); } if ($type eq "Dictionary") { AddToImplIncludes("Dictionary.h", $conditional); return ("Dictionary(state, $value)", 0); } my $arrayOrSequenceType = $codeGenerator->GetArrayOrSequenceType($type); if ($arrayOrSequenceType) { if ($codeGenerator->IsRefPtrType($arrayOrSequenceType)) { AddToImplIncludes("JS${arrayOrSequenceType}.h"); return ("(toRefPtrNativeArray<${arrayOrSequenceType}, JS${arrayOrSequenceType}>(state, $value, &JS${arrayOrSequenceType}::toWrapped))", 1); } return ("toNativeArray<" . GetNativeVectorInnerType($arrayOrSequenceType) . ">(*state, $value)", 1); } return ($value, 0) if $type eq "any"; return ("$value.toBoolean(state)", 1) if $type eq "boolean"; if ($codeGenerator->IsFloatingPointType($type)) { AddToImplIncludes("JSDOMConvert.h"); my $allowNonFinite = ShouldAllowNonFiniteForFloatingPointType($type) ? "ShouldAllowNonFinite::Yes" : "ShouldAllowNonFinite::No"; my $nativeType = GetNativeType($interface, $type); return ("convert<$nativeType>(*state, $value, $allowNonFinite)", 1); } return ("valueToDate(state, $value)", 1) if $type eq "Date"; return ("to$type($value)", 1) if $codeGenerator->IsTypedArrayType($type); return ("parse<" . GetEnumerationClassName($interface, $type) . ">(*state, $value)", 1) if $codeGenerator->IsEnumType($type); return ("convert<" . GetDictionaryClassName($interface, $type) . ">(*state, $value)", 1) if $codeGenerator->IsDictionaryType($type); AddToImplIncludes("JS$type.h", $conditional); # FIXME: EventListener should be a callback interface. return "JSEventListener::create($value, *castedThis, false, currentWorld(state))" if $type eq "EventListener"; my $extendedAttributes = $codeGenerator->getInterfaceExtendedAttributesFromName($type); return ("JS${type}::toWrapped(*state, $value)", 1) if $extendedAttributes->{"JSCustomToNativeObject"}; return ("JS${type}::toWrapped($value)", 0); } sub NativeToJSValue { my ($signature, $inFunctionCall, $interface, $value, $thisValue) = @_; my $conditional = $signature->extendedAttributes->{"Conditional"}; my $type = $signature->type; my $globalObject = $thisValue ? "$thisValue->globalObject()" : "jsCast(state->lexicalGlobalObject())"; return "jsBoolean($value)" if $type eq "boolean"; if ($type eq "Date") { my $handlingForNaN = $signature->extendedAttributes->{"TreatReturnedNaNDateAs"}; return "jsDateOrNull(state, $value)" if !defined $handlingForNaN || $handlingForNaN eq "Null"; return "jsDateOrNaN(state, $value)" if $handlingForNaN eq "NaN"; die "Unknown value for TreatReturnedNaNDateAs extended attribute"; } if ($codeGenerator->IsNumericType($type) or $type eq "DOMTimeStamp") { # We could instead overload a function to work with optional as well as non-optional numbers, but this # is slightly better because it guarantees we will fail to compile if the IDL file doesn't match the C++. my $function = $signature->isNullable ? "toNullableJSNumber" : "jsNumber"; if ($signature->extendedAttributes->{"Reflect"} and ($type eq "unsigned long" or $type eq "unsigned short")) { $value =~ s/getUnsignedIntegralAttribute/getIntegralAttribute/g; $value = "std::max(0, $value)"; } return "$function($value)"; } if ($codeGenerator->IsEnumType($type)) { AddToImplIncludes("", $conditional); return "jsStringWithCache(state, $value)"; } if ($type eq "DOMString") { AddToImplIncludes("URL.h", $conditional); return "jsStringOrNull(state, $value)" if $signature->isNullable; AddToImplIncludes("", $conditional); return "jsStringWithCache(state, $value)"; } my $arrayType = $codeGenerator->GetArrayType($type); my $arrayOrSequenceType = $arrayType || $codeGenerator->GetSequenceType($type); if ($arrayOrSequenceType) { if ($arrayType eq "DOMString") { AddToImplIncludes("JSDOMStringList.h", $conditional); } elsif ($codeGenerator->IsRefPtrType($arrayOrSequenceType)) { AddToImplIncludes("JS${arrayOrSequenceType}.h", $conditional); } AddToImplIncludes("", $conditional); return "jsArray(state, $globalObject, $value)"; } if ($type eq "any") { my $returnType = $signature->extendedAttributes->{"ImplementationReturnType"}; if (defined $returnType and ($returnType eq "IDBKeyPath" or $returnType eq "IDBKey")) { AddToImplIncludes("IDBBindingUtilities.h", $conditional); return "toJS(*state, *$globalObject, $value)"; } return $value; } if ($type eq "SerializedScriptValue") { AddToImplIncludes("SerializedScriptValue.h", $conditional); return "$value ? $value->deserialize(state, $thisValue->globalObject(), 0) : jsNull()"; } AddToImplIncludes("StyleProperties.h", $conditional) if $type eq "CSSStyleDeclaration"; AddToImplIncludes("NameNodeList.h", $conditional) if $type eq "NodeList"; AddToImplIncludes("JS$type.h", $conditional) if !$codeGenerator->IsTypedArrayType($type); return $value if $codeGenerator->IsSVGAnimatedType($type); if ($codeGenerator->IsSVGAnimatedType($interface->name) or ($interface->name eq "SVGViewSpec" and $type eq "SVGTransformList")) { # Convert from abstract RefPtr to real type, so the right toJS() method can be invoked. $value = "static_cast<" . GetNativeType($interface, $type) . ">($value.get())"; } elsif ($interface->name eq "SVGViewSpec") { # Convert from abstract SVGProperty to real type, so the right toJS() method can be invoked. $value = "static_cast<" . GetNativeType($interface, $type) . ">($value)"; } elsif ($codeGenerator->IsSVGTypeNeedingTearOff($type) and not $interface->name =~ /List$/) { my $tearOffType = $codeGenerator->GetSVGTypeNeedingTearOff($type); if ($codeGenerator->IsSVGTypeWithWritablePropertiesNeedingTearOff($type) and !$inFunctionCall and not defined $signature->extendedAttributes->{"Immutable"}) { my $getter = $value; $getter =~ s/impl\.//; $getter =~ s/impl->//; $getter =~ s/\(\)//; my $updateMethod = "&" . $interface->name . "::update" . $codeGenerator->WK_ucfirst($getter); my $selfIsTearOffType = $codeGenerator->IsSVGTypeNeedingTearOff($interface->name); if ($selfIsTearOffType) { # FIXME: Why SVGMatrix specifically? AddToImplIncludes("SVGMatrixTearOff.h", $conditional); $value = "SVGMatrixTearOff::create($thisValue->wrapped(), $value)"; } else { AddToImplIncludes("SVGStaticPropertyTearOff.h", $conditional); my $interfaceName = $interface->name; $tearOffType =~ s/SVGPropertyTearOffextendedAttributes->{"NewObject"} ? "toJSNewlyCreated" : "toJS"; return "$function(state, $globalObject, $value)"; } sub ceilingToPowerOf2 { my ($size) = @_; my $powerOf2 = 1; while ($size > $powerOf2) { $powerOf2 <<= 1; } return $powerOf2; } # Internal Helper sub GenerateHashTableValueArray { my $keys = shift; my $specials = shift; my $value1 = shift; my $value2 = shift; my $conditionals = shift; my $nameEntries = shift; my $packedSize = scalar @{$keys}; push(@implContent, "\nstatic const HashTableValue $nameEntries\[\] =\n\{\n"); my $hasSetter = "false"; my $i = 0; foreach my $key (@{$keys}) { my $conditional; my $firstTargetType; my $secondTargetType = ""; if ($conditionals) { $conditional = $conditionals->{$key}; } if ($conditional) { my $conditionalString = $codeGenerator->GenerateConditionalStringFromAttributeValue($conditional); push(@implContent, "#if ${conditionalString}\n"); } if ("@$specials[$i]" =~ m/Function/) { $firstTargetType = "static_cast"; } elsif ("@$specials[$i]" =~ m/Builtin/) { $firstTargetType = "static_cast"; } elsif ("@$specials[$i]" =~ m/ConstantInteger/) { $firstTargetType = ""; } else { $firstTargetType = "static_cast"; $secondTargetType = "static_cast"; $hasSetter = "true"; } if ("@$specials[$i]" =~ m/ConstantInteger/) { push(@implContent, " { \"$key\", @$specials[$i], NoIntrinsic, { (long long)" . $firstTargetType . "(@$value1[$i]) } },\n"); } else { push(@implContent, " { \"$key\", @$specials[$i], NoIntrinsic, { (intptr_t)" . $firstTargetType . "(@$value1[$i]), (intptr_t) " . $secondTargetType . "(@$value2[$i]) } },\n"); } if ($conditional) { push(@implContent, "#else\n") ; push(@implContent, " { 0, 0, NoIntrinsic, { 0, 0 } },\n"); push(@implContent, "#endif\n") ; } ++$i; } push(@implContent, " { 0, 0, NoIntrinsic, { 0, 0 } }\n") if (!$packedSize); push(@implContent, "};\n\n"); return $hasSetter; } sub GenerateHashTable { my $object = shift; my $name = shift; my $size = shift; my $keys = shift; my $specials = shift; my $value1 = shift; my $value2 = shift; my $conditionals = shift; my $justGenerateValueArray = shift; my $nameEntries = "${name}Values"; $nameEntries =~ s/:/_/g; my $nameIndex = "${name}Index"; $nameIndex =~ s/:/_/g; if (($name =~ /Prototype/) or ($name =~ /Constructor/)) { my $type = $name; my $implClass; if ($name =~ /Prototype/) { $type =~ s/Prototype.*//; $implClass = $type; $implClass =~ s/Wrapper$//; push(@implContent, "/* Hash table for prototype */\n"); } else { $type =~ s/Constructor.*//; $implClass = $type; $implClass =~ s/Constructor$//; push(@implContent, "/* Hash table for constructor */\n"); } } else { push(@implContent, "/* Hash table */\n"); } if ($justGenerateValueArray) { GenerateHashTableValueArray($keys, $specials, $value1, $value2, $conditionals, $nameEntries) if $size; return; } # Generate size data for compact' size hash table my @table = (); my @links = (); my $compactSize = ceilingToPowerOf2($size * 2); my $maxDepth = 0; my $collisions = 0; my $numEntries = $compactSize; my $i = 0; foreach (@{$keys}) { my $depth = 0; my $h = Hasher::GenerateHashValue($_) % $numEntries; while (defined($table[$h])) { if (defined($links[$h])) { $h = $links[$h]; $depth++; } else { $collisions++; $links[$h] = $compactSize; $h = $compactSize; $compactSize++; } } $table[$h] = $i; $i++; $maxDepth = $depth if ($depth > $maxDepth); } push(@implContent, "\nstatic const struct CompactHashIndex ${nameIndex}\[$compactSize\] = {\n"); for (my $i = 0; $i < $compactSize; $i++) { my $T = -1; if (defined($table[$i])) { $T = $table[$i]; } my $L = -1; if (defined($links[$i])) { $L = $links[$i]; } push(@implContent, " { $T, $L },\n"); } push(@implContent, "};\n\n"); # Dump the hash table my $hasSetter = GenerateHashTableValueArray($keys, $specials, $value1, $value2, $conditionals, $nameEntries); my $packedSize = scalar @{$keys}; my $compactSizeMask = $numEntries - 1; push(@implContent, "static const HashTable $name = { $packedSize, $compactSizeMask, $hasSetter, $nameEntries, $nameIndex };\n"); } sub WriteData { my $object = shift; my $interface = shift; my $outputDir = shift; my $name = $interface->name; my $prefix = FileNamePrefix; my $headerFileName = "$outputDir/$prefix$name.h"; my $implFileName = "$outputDir/$prefix$name.cpp"; my $depsFileName = "$outputDir/$prefix$name.dep"; # Update a .cpp file if the contents are changed. my $contents = join "", @implContentHeader; my @includes = (); my %implIncludeConditions = (); foreach my $include (keys %implIncludes) { my $condition = $implIncludes{$include}; my $checkType = $include; $checkType =~ s/\.h//; next if $codeGenerator->IsSVGAnimatedType($checkType); $include = "\"$include\"" unless $include =~ /^["<]/; # " if ($condition eq 1) { push @includes, $include; } else { push @{$implIncludeConditions{$codeGenerator->GenerateConditionalStringFromAttributeValue($condition)}}, $include; } } foreach my $include (sort @includes) { $contents .= "#include $include\n"; } foreach my $condition (sort keys %implIncludeConditions) { $contents .= "\n#if " . $condition . "\n"; foreach my $include (sort @{$implIncludeConditions{$condition}}) { $contents .= "#include $include\n"; } $contents .= "#endif\n"; } $contents .= join "", @implContent; $codeGenerator->UpdateFile($implFileName, $contents); @implContentHeader = (); @implContent = (); %implIncludes = (); # Update a .h file if the contents are changed. $contents = join "", @headerContentHeader; @includes = (); foreach my $include (keys %headerIncludes) { $include = "\"$include\"" unless $include =~ /^["<]/; # " push @includes, $include; } foreach my $include (sort @includes) { # "JSClassName.h" is already included right after config.h. next if $include eq "\"$prefix$name.h\""; $contents .= "#include $include\n"; } $contents .= join "", @headerContent; @includes = (); foreach my $include (keys %headerTrailingIncludes) { $include = "\"$include\"" unless $include =~ /^["<]/; # " push @includes, $include; } foreach my $include (sort @includes) { $contents .= "#include $include\n"; } $codeGenerator->UpdateFile($headerFileName, $contents); @headerContentHeader = (); @headerContent = (); %headerIncludes = (); %headerTrailingIncludes = (); if (@depsContent) { # Update a .dep file if the contents are changed. $contents = join "", @depsContent; $codeGenerator->UpdateFile($depsFileName, $contents); @depsContent = (); } } sub GeneratePrototypeDeclaration { my ($outputArray, $className, $interface) = @_; my $prototypeClassName = "${className}Prototype"; my %structureFlags = (); push(@$outputArray, "class ${prototypeClassName} : public JSC::JSNonFinalObject {\n"); push(@$outputArray, "public:\n"); push(@$outputArray, " typedef JSC::JSNonFinalObject Base;\n"); push(@$outputArray, " static ${prototypeClassName}* create(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::Structure* structure)\n"); push(@$outputArray, " {\n"); push(@$outputArray, " ${className}Prototype* ptr = new (NotNull, JSC::allocateCell<${className}Prototype>(vm.heap)) ${className}Prototype(vm, globalObject, structure);\n"); push(@$outputArray, " ptr->finishCreation(vm);\n"); push(@$outputArray, " return ptr;\n"); push(@$outputArray, " }\n\n"); push(@$outputArray, " DECLARE_INFO;\n"); push(@$outputArray, " static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)\n" . " {\n" . " return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info());\n" . " }\n"); push(@$outputArray, "\nprivate:\n"); push(@$outputArray, " ${prototypeClassName}(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure)\n"); push(@$outputArray, " : JSC::JSNonFinalObject(vm, structure)\n"); push(@$outputArray, " {\n"); push(@$outputArray, " }\n"); if (PrototypeHasStaticPropertyTable($interface)) { if (IsDOMGlobalObject($interface)) { $structureFlags{"JSC::HasStaticPropertyTable"} = 1; } else { push(@$outputArray, "\n"); push(@$outputArray, " void finishCreation(JSC::VM&);\n"); } } if ($interface->extendedAttributes->{"JSCustomNamedGetterOnPrototype"}) { push(@$outputArray, "\n"); push(@$outputArray, " static bool put(JSC::JSCell*, JSC::ExecState*, JSC::PropertyName, JSC::JSValue, JSC::PutPropertySlot&);\n"); push(@$outputArray, " bool putDelegate(JSC::ExecState*, JSC::PropertyName, JSC::JSValue, JSC::PutPropertySlot&, bool& putResult);\n"); } # Custom defineOwnProperty function if ($interface->extendedAttributes->{"JSCustomDefineOwnPropertyOnPrototype"}) { push(@$outputArray, "\n"); push(@$outputArray, " static bool defineOwnProperty(JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, const JSC::PropertyDescriptor&, bool shouldThrow);\n"); } # structure flags if (%structureFlags) { push(@$outputArray, "public:\n"); push(@$outputArray, " static const unsigned StructureFlags = "); foreach my $structureFlag (sort (keys %structureFlags)) { push(@$outputArray, $structureFlag . " | "); } push(@$outputArray, "Base::StructureFlags;\n"); } push(@$outputArray, "};\n\n"); } sub GetConstructorTemplateClassName { my $interface = shift; return "JSDOMConstructorNotConstructable" if ($interface->extendedAttributes->{"NamedConstructor"}); return "JSDOMConstructorNotConstructable" unless IsConstructable($interface); return "JSBuiltinConstructor" if IsJSBuiltinConstructor($interface); return "JSDOMConstructor"; } sub GenerateConstructorDeclaration { my ($outputArray, $className, $interface) = @_; my $interfaceName = $interface->name; my $constructorClassName = "${className}Constructor"; my $templateClassName = GetConstructorTemplateClassName($interface); $implIncludes{"JSDOMConstructor.h"} = 1; push(@$outputArray, "typedef $templateClassName<$className> ${constructorClassName};\n"); push(@$outputArray, "typedef JSDOMNamedConstructor<$className> JS${interfaceName}NamedConstructor;\n") if $interface->extendedAttributes->{"NamedConstructor"}; push(@$outputArray, "\n"); } sub GenerateConstructorDefinitions { my ($outputArray, $className, $protoClassName, $visibleInterfaceName, $interface, $generatingNamedConstructor) = @_; if (IsConstructable($interface)) { my @constructors = @{$interface->constructors}; if (@constructors > 1) { foreach my $constructor (@constructors) { GenerateConstructorDefinition($outputArray, $className, $protoClassName, $visibleInterfaceName, $interface, $generatingNamedConstructor, $constructor); } GenerateOverloadedConstructorDefinition($outputArray, $className, $interface); } elsif (@constructors == 1) { GenerateConstructorDefinition($outputArray, $className, $protoClassName, $visibleInterfaceName, $interface, $generatingNamedConstructor, $constructors[0]); } else { GenerateConstructorDefinition($outputArray, $className, $protoClassName, $visibleInterfaceName, $interface, $generatingNamedConstructor); } } GenerateConstructorHelperMethods($outputArray, $className, $protoClassName, $visibleInterfaceName, $interface, $generatingNamedConstructor); } sub GenerateOverloadedConstructorDefinition { my $outputArray = shift; my $className = shift; my $interface = shift; # FIXME: Implement support for overloaded constructors with variadic arguments. my $lengthOfLongestOverloadedConstructorParameterList = LengthOfLongestFunctionParameterList($interface->constructors); push(@$outputArray, < EncodedJSValue JSC_HOST_CALL ${className}Constructor::construct(ExecState* state) { size_t argsCount = std::min($lengthOfLongestOverloadedConstructorParameterList, state->argumentCount()); END my %fetchedArguments = (); my $leastNumMandatoryParams = 255; my @constructors = @{$interface->constructors}; foreach my $overload (@constructors) { my $functionName = "construct${className}"; my ($numMandatoryParams, $parametersCheck, @neededArguments) = GenerateFunctionParametersCheck($overload); $leastNumMandatoryParams = $numMandatoryParams if ($numMandatoryParams < $leastNumMandatoryParams); foreach my $parameterIndex (@neededArguments) { next if exists $fetchedArguments{$parameterIndex}; push(@$outputArray, " JSValue arg$parameterIndex(state->argument($parameterIndex));\n"); $fetchedArguments{$parameterIndex} = 1; } push(@$outputArray, " if ($parametersCheck)\n"); push(@$outputArray, " return ${functionName}$overload->{overloadedIndex}(state);\n"); } if ($leastNumMandatoryParams >= 1) { push(@$outputArray, " if (UNLIKELY(argsCount < $leastNumMandatoryParams))\n"); push(@$outputArray, " return throwVMError(state, createNotEnoughArgumentsError(state));\n"); } push(@$outputArray, <name; my $constructorClassName = $generatingNamedConstructor ? "${className}NamedConstructor" : "${className}Constructor"; if (IsConstructable($interface)) { if ($codeGenerator->IsConstructorTemplate($interface, "Event")) { $implIncludes{"JSDictionary.h"} = 1; $implIncludes{""} = 1; push(@$outputArray, < EncodedJSValue JSC_HOST_CALL ${constructorClassName}::construct(ExecState* state) { auto* jsConstructor = jsCast<${constructorClassName}*>(state->callee()); if (!jsConstructor->scriptExecutionContext()) return throwVMError(state, createReferenceError(state, "Constructor associated execution context is unavailable")); if (UNLIKELY(state->argumentCount() < 1)) return throwVMError(state, createNotEnoughArgumentsError(state)); AtomicString eventType = state->argument(0).toString(state)->toAtomicString(state); if (UNLIKELY(state->hadException())) return JSValue::encode(jsUndefined()); ${interfaceName}Init eventInit; JSValue initializerValue = state->argument(1); if (!initializerValue.isUndefinedOrNull()) { // Given the above test, this will always yield an object. JSObject* initializerObject = initializerValue.toObject(state); ASSERT(!state->hadException()); // Create the dictionary wrapper from the initializer object. JSDictionary dictionary(state, initializerObject); // Attempt to fill in the EventInit. if (!fill${interfaceName}Init(eventInit, dictionary)) return JSValue::encode(jsUndefined()); } Ref<${interfaceName}> event = ${interfaceName}::createForBindings(eventType, eventInit); return JSValue::encode(toJS(state, jsConstructor->globalObject(), event)); } bool fill${interfaceName}Init(${interfaceName}Init& eventInit, JSDictionary& dictionary) { END if ($interface->parent) { my $interfaceBase = $interface->parent; push(@implContent, <attributes}; $index++) { my $attribute = @{$interface->attributes}[$index]; if ($attribute->signature->extendedAttributes->{"InitializedByEventConstructor"}) { my $attributeName = $attribute->signature->name; my $attributeImplName = $attribute->signature->extendedAttributes->{"ImplementedAs"} || $attributeName; my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature); push(@implContent, "#if ${conditionalString}\n") if $conditionalString; push(@implContent, <extendedAttributes->{"CustomConstructor"}) { push(@$outputArray, "template<> JSC::EncodedJSValue JSC_HOST_CALL ${constructorClassName}::construct(JSC::ExecState* exec)\n"); push(@$outputArray, "{\n"); push(@$outputArray, " ASSERT(exec);\n"); push(@$outputArray, " return construct${className}(*exec);\n"); push(@$outputArray, "}\n\n"); } elsif (!HasCustomConstructor($interface) && (!$interface->extendedAttributes->{"NamedConstructor"} || $generatingNamedConstructor)) { if ($function->{overloadedIndex} && $function->{overloadedIndex} > 0) { push(@$outputArray, "static inline EncodedJSValue construct${className}$function->{overloadedIndex}(ExecState* state)\n"); } else { push(@$outputArray, "template<> EncodedJSValue JSC_HOST_CALL ${constructorClassName}::construct(ExecState* state)\n"); } push(@$outputArray, "{\n"); push(@$outputArray, " auto* castedThis = jsCast<${constructorClassName}*>(state->callee());\n"); my @constructorArgList; $implIncludes{""} = 1; GenerateArgumentsCountCheck($outputArray, $function, $interface); if ($function->signature->extendedAttributes->{"RaisesException"} || $function->signature->extendedAttributes->{"RaisesExceptionWithMessage"} || $interface->extendedAttributes->{"ConstructorRaisesException"}) { $implIncludes{"ExceptionCode.h"} = 1; if ($function->signature->extendedAttributes->{"RaisesExceptionWithMessage"}) { push(@$outputArray, " ExceptionCodeWithMessage ec;\n"); } else { push(@$outputArray, " ExceptionCode ec = 0;\n"); } } # FIXME: For now, we do not support SVG constructors. # FIXME: Currently [Constructor(...)] does not yet support optional arguments without [Default=...] my ($dummy, $paramIndex) = GenerateParametersCheck($outputArray, $function, $interface, "constructorCallback", undef, undef, undef); if ($codeGenerator->ExtendedAttributeContains($interface->extendedAttributes->{"ConstructorCallWith"}, "ScriptState")) { push(@constructorArgList, "*state"); } if ($codeGenerator->ExtendedAttributeContains($interface->extendedAttributes->{"ConstructorCallWith"}, "ScriptExecutionContext")) { push(@constructorArgList, "*context"); push(@$outputArray, " ScriptExecutionContext* context = castedThis->scriptExecutionContext();\n"); push(@$outputArray, " if (UNLIKELY(!context))\n"); push(@$outputArray, " return throwConstructorDocumentUnavailableError(*state, \"${interfaceName}\");\n"); } if ($codeGenerator->ExtendedAttributeContains($interface->extendedAttributes->{"ConstructorCallWith"}, "Document")) { $implIncludes{"Document.h"} = 1; push(@constructorArgList, "document"); push(@$outputArray, " ScriptExecutionContext* context = castedThis->scriptExecutionContext();\n"); push(@$outputArray, " if (UNLIKELY(!context))\n"); push(@$outputArray, " return throwConstructorDocumentUnavailableError(*state, \"${interfaceName}\");\n"); push(@$outputArray, " ASSERT(context->isDocument());\n"); push(@$outputArray, " auto& document = downcast(*context);\n"); } if ($generatingNamedConstructor) { push(@constructorArgList, "*castedThis->document()"); } my $index = 0; foreach my $parameter (@{$function->parameters}) { last if $index eq $paramIndex; if (ShouldPassWrapperByReference($parameter, $interface)) { push(@constructorArgList, "*" . $parameter->name); } else { push(@constructorArgList, $parameter->name); } $index++; } if ($interface->extendedAttributes->{"ConstructorRaisesException"}) { push(@constructorArgList, "ec"); } my $constructorArg = join(", ", @constructorArgList); if ($generatingNamedConstructor) { push(@$outputArray, " auto object = ${interfaceName}::createForJSConstructor(${constructorArg});\n"); } else { push(@$outputArray, " auto object = ${interfaceName}::create(${constructorArg});\n"); } if ($interface->extendedAttributes->{"ConstructorRaisesException"}) { push(@$outputArray, " if (UNLIKELY(ec)) {\n"); push(@$outputArray, " setDOMException(state, ec);\n"); push(@$outputArray, " return JSValue::encode(JSValue());\n"); push(@$outputArray, " }\n"); } if ($codeGenerator->ExtendedAttributeContains($interface->extendedAttributes->{"ConstructorCallWith"}, "ScriptState")) { push(@$outputArray, " if (UNLIKELY(state->hadException()))\n"); push(@$outputArray, " return JSValue::encode(jsUndefined());\n"); } push(@$outputArray, " return JSValue::encode(asObject(toJSNewlyCreated(state, castedThis->globalObject(), WTFMove(object))));\n"); push(@$outputArray, "}\n\n"); } } } sub ConstructorHasProperties { my $interface = shift; foreach my $constant (@{$interface->constants}) { return 1; } foreach my $attribute (@{$interface->attributes}) { next unless ($attribute->isStatic); return 1; } foreach my $function (@{$interface->functions}) { next unless ($function->isStatic); return 1; } return 0; } sub GenerateConstructorHelperMethods { my ($outputArray, $className, $protoClassName, $visibleInterfaceName, $interface, $generatingNamedConstructor) = @_; my $constructorClassName = $generatingNamedConstructor ? "${className}NamedConstructor" : "${className}Constructor"; my $leastConstructorLength = 0; if ($codeGenerator->IsConstructorTemplate($interface, "Event")) { $leastConstructorLength = 1; } elsif ($interface->extendedAttributes->{"Constructor"} || $interface->extendedAttributes->{"CustomConstructor"}) { my @constructors = @{$interface->constructors}; my @customConstructors = @{$interface->customConstructors}; $leastConstructorLength = 255; foreach my $constructor (@constructors, @customConstructors) { my $constructorLength = GetFunctionLength($constructor); $leastConstructorLength = $constructorLength if ($constructorLength < $leastConstructorLength); } } else { $leastConstructorLength = 0; } # If the interface has a parent interface which does not have [NoInterfaceObject], then use its interface object as prototype, # otherwise use FunctionPrototype: http://heycam.github.io/webidl/#interface-object push(@$outputArray, "template<> JSValue ${constructorClassName}::prototypeForStructure(JSC::VM& vm, const JSDOMGlobalObject& globalObject)\n"); push(@$outputArray, "{\n"); # FIXME: IDL does not allow an interface without [NoInterfaceObject] to inherit one that is marked as [NoInterfaceObject] # so we should be able to use our parent's interface object no matter what. However, some of our IDL files (e.g. CanvasRenderingContext2D) # are not valid so we need this check for now. if ($interface->parent && !$codeGenerator->getInterfaceExtendedAttributesFromName($interface->parent)->{"NoInterfaceObject"}) { my $parentClassName = "JS" . $interface->parent; push(@$outputArray, " return ${parentClassName}::getConstructor(vm, &globalObject);\n"); } else { AddToImplIncludes(""); push(@$outputArray, " UNUSED_PARAM(vm);\n"); push(@$outputArray, " return globalObject.functionPrototype();\n"); } push(@$outputArray, "}\n\n"); push(@$outputArray, "template<> void ${constructorClassName}::initializeProperties(VM& vm, JSDOMGlobalObject& globalObject)\n"); push(@$outputArray, "{\n"); # There must exist an interface prototype object for every non-callback interface defined, regardless # of whether the interface was declared with the [NoInterfaceObject] extended attribute. # https://heycam.github.io/webidl/#interface-prototype-object if (ShouldUseGlobalObjectPrototype($interface)) { push(@$outputArray, " putDirect(vm, vm.propertyNames->prototype, globalObject.getPrototypeDirect(), DontDelete | ReadOnly | DontEnum);\n"); } elsif ($interface->isCallback) { push(@$outputArray, " UNUSED_PARAM(globalObject);\n"); } else { push(@$outputArray, " putDirect(vm, vm.propertyNames->prototype, ${className}::prototype(vm, &globalObject), DontDelete | ReadOnly | DontEnum);\n"); } push(@$outputArray, " putDirect(vm, vm.propertyNames->name, jsNontrivialString(&vm, String(ASCIILiteral(\"$visibleInterfaceName\"))), ReadOnly | DontEnum);\n"); push(@$outputArray, " putDirect(vm, vm.propertyNames->length, jsNumber(${leastConstructorLength}), ReadOnly | DontEnum);\n") if defined $leastConstructorLength; push(@$outputArray, " reifyStaticProperties(vm, ${className}ConstructorTableValues, *this);\n") if ConstructorHasProperties($interface); push(@$outputArray, "}\n\n"); my $conditionalString = $codeGenerator->GenerateConstructorConditionalString($interface); if ($conditionalString) { push(@$outputArray, "template<> ConstructType ${constructorClassName}::getConstructData(JSCell* cell, ConstructData& constructData)\n"); push(@$outputArray, "{\n"); push(@$outputArray, "#if $conditionalString\n"); push(@$outputArray, " UNUSED_PARAM(cell);\n"); push(@$outputArray, " constructData.native.function = construct;\n"); push(@$outputArray, " return ConstructType::Host;\n"); push(@$outputArray, "#else\n"); push(@$outputArray, " return Base::getConstructData(cell, constructData);\n"); push(@$outputArray, "#endif\n"); push(@$outputArray, "}\n"); push(@$outputArray, "\n"); } if (IsJSBuiltinConstructor($interface)) { push(@$outputArray, "template<> FunctionExecutable* ${constructorClassName}::initializeExecutable(VM& vm)\n"); push(@$outputArray, "{\n"); push(@$outputArray, " return " . GetJSBuiltinFunctionNameFromString($interface->name, "initialize" . $interface->name) . "(vm);\n"); push(@$outputArray, "}\n"); push(@$outputArray, "\n"); } push(@$outputArray, "template<> const ClassInfo ${constructorClassName}::s_info = { \"${visibleInterfaceName}\", &Base::s_info, 0, CREATE_METHOD_TABLE($constructorClassName) };\n\n"); } sub HasCustomConstructor { my $interface = shift; return $interface->extendedAttributes->{"CustomConstructor"}; } sub HasCustomGetter { my $attrExt = shift; return $attrExt->{"Custom"} || $attrExt->{"CustomGetter"} ; } sub HasCustomSetter { my $attrExt = shift; return $attrExt->{"Custom"} || $attrExt->{"CustomSetter"}; } sub HasCustomMethod { my $attrExt = shift; return $attrExt->{"Custom"}; } sub NeedsConstructorProperty { my $interface = shift; return !$interface->extendedAttributes->{"NoInterfaceObject"} || $interface->extendedAttributes->{"CustomConstructor"}; } sub IsReturningPromise { my $function = shift; return $function->signature->type eq "Promise" if ($function->signature->type); } sub IsConstructable { my $interface = shift; return HasCustomConstructor($interface) || $interface->extendedAttributes->{"Constructor"} || $interface->extendedAttributes->{"NamedConstructor"} || $interface->extendedAttributes->{"ConstructorTemplate"} || $interface->extendedAttributes->{"JSBuiltinConstructor"}; } sub HeaderNeedsPrototypeDeclaration { my $interface = shift; return IsDOMGlobalObject($interface) || $interface->extendedAttributes->{"JSCustomNamedGetterOnPrototype"} || $interface->extendedAttributes->{"JSCustomDefineOwnPropertyOnPrototype"}; } sub IsUnforgeable { my $interface = shift; my $property = shift; return $property->signature->extendedAttributes->{"Unforgeable"} || $interface->extendedAttributes->{"Unforgeable"}; } sub ComputeFunctionSpecial { my $interface = shift; my $function = shift; my @specials = (); push(@specials, ("DontDelete", "ReadOnly")) if IsUnforgeable($interface, $function); push(@specials, "DontEnum") if $function->signature->extendedAttributes->{"NotEnumerable"}; if (IsJSBuiltin($interface, $function)) { push(@specials, "JSC::Builtin"); } else { push(@specials, "JSC::Function"); } return (@specials > 0) ? join(" | ", @specials) : "0"; } sub IsJSBuiltin { my ($interface, $object) = @_; return 0 if $object->signature->extendedAttributes->{"Custom"}; return 0 if $object->signature->extendedAttributes->{"CustomGetter"}; return 0 if $object->signature->extendedAttributes->{"CustomSetter"}; return 1 if $object->signature->extendedAttributes->{"JSBuiltin"}; return 1 if $interface->extendedAttributes->{"JSBuiltin"}; return 0; } sub IsJSBuiltinConstructor { my ($interface) = @_; return 0 if $interface->extendedAttributes->{"CustomConstructor"}; return 1 if $interface->extendedAttributes->{"JSBuiltin"}; return 1 if $interface->extendedAttributes->{"JSBuiltinConstructor"}; return 0; } sub GetJSBuiltinFunctionName { my ($className, $function) = @_; my $scopeName = $function->signature->extendedAttributes->{"ImplementedBy"}; $scopeName = substr $className, 2 unless $scopeName; return GetJSBuiltinFunctionNameFromString($scopeName, $function->signature->name); } sub GetJSBuiltinFunctionNameFromString { my ($scopeName, $functionName) = @_; return $codeGenerator->WK_lcfirst($scopeName) . $codeGenerator->WK_ucfirst($functionName) . "CodeGenerator"; } sub GetJSBuiltinScopeName { my $interface = shift; my $object = shift; return $object->signature->extendedAttributes->{"ImplementedBy"} if $object->signature->extendedAttributes->{"ImplementedBy"}; return $interface->name; } sub AddJSBuiltinIncludesIfNeeded() { my $interface = shift; if ($interface->extendedAttributes->{"JSBuiltin"} || $interface->extendedAttributes->{"JSBuiltinConstructor"}) { AddToImplIncludes($interface->name . "Builtins.h"); return; } foreach my $function (@{$interface->functions}) { AddToImplIncludes(GetJSBuiltinScopeName($interface, $function) . "Builtins.h", $function->signature->extendedAttributes->{"Conditional"}) if IsJSBuiltin($interface, $function); } foreach my $attribute (@{$interface->attributes}) { AddToImplIncludes(GetJSBuiltinScopeName($interface, $attribute) . "Builtins.h", $attribute->signature->extendedAttributes->{"Conditional"}) if IsJSBuiltin($interface, $attribute); } } 1;