Example #1
0
      def GenerateCall(
          stmts_emitter, call_emitter,
          version, signature_index, argument_count):
        name = emitter.Format('_create_$VERSION', VERSION=version)
        arguments = constructor_info.idl_args[signature_index][:argument_count]
        args = None
        call_template = ''
        if self._dart_use_blink:
            type_ids = [p.type.id for p in arguments]
            base_name, rs = \
                self.DeriveNativeEntry("constructorCallback", 'Constructor', argument_count)
            qualified_name = \
                self.DeriveQualifiedBlinkName(self._interface.id,
                                              base_name)
            args = constructor_info.ParametersAsArgumentList(argument_count)

            # Handle converting Maps to Dictionaries, etc.
            (factory_params, converted_arguments) = self._ConvertArgumentTypes(
                stmts_emitter, arguments, argument_count, constructor_info)
            args = ', '.join(converted_arguments)
            call_template = '$FACTORY_NAME($FACTORY_PARAMS)'
        else:
            qualified_name = emitter.Format(
                '$FACTORY.$NAME',
                FACTORY=factory_name,
                NAME=name)
            (factory_params, converted_arguments) = self._ConvertArgumentTypes(
                stmts_emitter, arguments, argument_count, constructor_info)
            args = ', '.join(converted_arguments)
            call_template = '$FACTORY_NAME($FACTORY_PARAMS)'
        call_emitter.Emit(call_template, FACTORY_NAME=qualified_name, FACTORY_PARAMS=args)
        self.EmitStaticFactoryOverload(constructor_info, name, arguments)
Example #2
0
  def _GenerateWebCoreInvocation(self, function_expression, arguments,
      idl_return_type, attributes, raises_dom_exceptions):
    invocation_template = '        $FUNCTION_CALL;\n'
    if idl_return_type != 'void':
      return_type_info = GetIDLTypeInfo(idl_return_type)
      self._cpp_impl_includes |= set(return_type_info.conversion_includes())

      # Generate to Dart conversion of C++ value.
      to_dart_conversion = return_type_info.to_dart_conversion('$FUNCTION_CALL', self._interface.id, attributes)
      invocation_template = emitter.Format(
          '        Dart_Handle returnValue = $TO_DART_CONVERSION;\n'
          '        if (returnValue)\n'
          '            Dart_SetReturnValue(args, returnValue);\n',
          TO_DART_CONVERSION=to_dart_conversion)

    if raises_dom_exceptions:
      # Add 'ec' argument to WebCore invocation and convert DOM exception to Dart exception.
      arguments.append('ec')
      invocation_template = emitter.Format(
          '        ExceptionCode ec = 0;\n'
          '$INVOCATION'
          '        if (UNLIKELY(ec)) {\n'
          '            exception = DartDOMWrapper::exceptionCodeToDartException(ec);\n'
          '            goto fail;\n'
          '        }\n',
          INVOCATION=invocation_template)

    if 'ImplementedBy' in attributes:
      arguments.insert(0, 'receiver')
      self._cpp_impl_includes.add('"%s.h"' % attributes['ImplementedBy'])

    return emitter.Format(invocation_template,
        FUNCTION_CALL='%s(%s)' % (function_expression, ', '.join(arguments)))
Example #3
0
    def _GenerateNativeCallback(self,
                                callback_name,
                                parameter_definitions,
                                needs_receiver,
                                invocation,
                                raises_exceptions,
                                runtime_check=None):

        head = parameter_definitions

        if needs_receiver:
            head = emitter.Format(
                '        $WEBCORE_CLASS_NAME* receiver = DartDOMWrapper::receiver< $WEBCORE_CLASS_NAME >(args);\n'
                '$HEAD\n',
                WEBCORE_CLASS_NAME=self._interface_type_info.native_type(),
                HEAD=head)

        if runtime_check:
            head = emitter.Format('$RUNTIME_CHECK\n'
                                  '$HEAD\n',
                                  RUNTIME_CHECK=runtime_check,
                                  HEAD=head)

        body = emitter.Format(
            '    {\n'
            '$HEAD'
            '$INVOCATION'
            '        return;\n'
            '    }\n',
            HEAD=head,
            INVOCATION=invocation)

        if raises_exceptions:
            body = emitter.Format(
                '    Dart_Handle exception = 0;\n'
                '$BODY'
                '\n'
                'fail:\n'
                '    Dart_ThrowException(exception);\n'
                '    ASSERT_NOT_REACHED();\n',
                BODY=body)

        self._cpp_definitions_emitter.Emit(
            '\n'
            'static void $CALLBACK_NAME(Dart_NativeArguments args)\n'
            '{\n'
            '    DartApiScope dartApiScope;\n'
            '$BODY'
            '}\n',
            CALLBACK_NAME=callback_name,
            BODY=body)
Example #4
0
 def GenerateCall(stmts_emitter, call_emitter, version,
                  signature_index, argument_count):
     name = emitter.Format('_create_$VERSION', VERSION=version)
     if self._dart_use_blink:
         qualified_name = \
             "_".join(["Native",self._interface.id,
                       name + 'constructorCallback'])
     else:
         qualified_name = emitter.Format('$FACTORY.$NAME',
                                         FACTORY=factory_name,
                                         NAME=name)
     call_emitter.Emit('$FACTORY_NAME($FACTORY_PARAMS)',
         FACTORY_NAME=qualified_name,
         FACTORY_PARAMS= \
             constructor_info.ParametersAsArgumentList(argument_count))
     self.EmitStaticFactoryOverload(
         constructor_info, name,
         constructor_info.idl_args[signature_index]
         [:argument_count])
Example #5
0
 def GenerateCall(stmts_emitter, call_emitter, version,
                  signature_index, argument_count):
     name = emitter.Format('_create_$VERSION', VERSION=version)
     call_emitter.Emit('$FACTORY.$NAME($FACTORY_PARAMS)',
         FACTORY=factory_name,
         NAME=name,
         FACTORY_PARAMS= \
             constructor_info.ParametersAsArgumentList(argument_count))
     self.EmitStaticFactoryOverload(
         constructor_info, name,
         constructor_info.idl_args[signature_index]
         [:argument_count])
Example #6
0
 def GenerateCall(
     stmts_emitter, call_emitter,
     version, signature_index, argument_count):
   name = emitter.Format('_create_$VERSION', VERSION=version)
   arguments = constructor_info.idl_args[signature_index][:argument_count]
   if self._dart_use_blink:
       type_ids = [p.type.id for p in arguments]
       base_name, rs = \
           self.DeriveNativeEntry("constructorCallback", 'Constructor', argument_count)
       qualified_name = \
           self.DeriveQualifiedBlinkName(self._interface.id,
                                         base_name)
   else:
       qualified_name = emitter.Format(
           '$FACTORY.$NAME',
           FACTORY=factory_name,
           NAME=name)
   call_emitter.Emit('$FACTORY_NAME($FACTORY_PARAMS)',
       FACTORY_NAME=qualified_name,
       FACTORY_PARAMS= \
           constructor_info.ParametersAsArgumentList(argument_count))
   self.EmitStaticFactoryOverload(constructor_info, name, arguments)
Example #7
0
  def _GenerateNativeCallback(self, callback_name, parameter_definitions,
      needs_receiver, invocation, raises_exceptions):

    if needs_receiver:
      parameter_definitions = emitter.Format(
          '        $WEBCORE_CLASS_NAME* receiver = DartDOMWrapper::receiver< $WEBCORE_CLASS_NAME >(args);\n'
          '        $PARAMETER_DEFINITIONS\n',
          WEBCORE_CLASS_NAME=self._interface_type_info.native_type(),
          PARAMETER_DEFINITIONS=parameter_definitions)

    body = emitter.Format(
        '    {\n'
        '$PARAMETER_DEFINITIONS'
        '$INVOCATION'
        '        return;\n'
        '    }\n',
        PARAMETER_DEFINITIONS=parameter_definitions,
        INVOCATION=invocation)

    if raises_exceptions:
      body = emitter.Format(
          '    Dart_Handle exception = 0;\n'
          '$BODY'
          '\n'
          'fail:\n'
          '    Dart_ThrowException(exception);\n'
          '    ASSERT_NOT_REACHED();\n',
          BODY=body)

    self._cpp_definitions_emitter.Emit(
        '\n'
        'static void $CALLBACK_NAME(Dart_NativeArguments args)\n'
        '{\n'
        '    DartApiScope dartApiScope;\n'
        '$BODY'
        '}\n',
        CALLBACK_NAME=callback_name,
        BODY=body)
Example #8
0
 def testFormat(self):
   self.assertEquals(emitter.Format('$A$B', A=1, B=2), '12')
Example #9
0
    def _AddConstructor(self, constructor_info, factory_name,
                        factory_constructor_name):
        # Hack to ignore the Image constructor used by JavaScript.
        if ((self._interface.id == 'HTMLImageElement' or self._interface.id
             == 'Blob' or self._interface.id == 'DOMException')
                and not constructor_info.pure_dart_constructor):
            return

        if self.GenerateCustomFactory(constructor_info):
            return

        metadata = self._metadata.GetFormattedMetadata(self._library_name,
                                                       self._interface,
                                                       self._interface.id,
                                                       '  ')

        if not factory_constructor_name:
            factory_constructor_name = '_create'
            factory_parameters = constructor_info.ParametersAsArgumentList()
        else:
            factory_parameters = ', '.join(constructor_info.factory_parameters)

        def InputType(type_name):
            conversion = self._InputConversion(type_name,
                                               constructor_info.declared_name)
            if conversion:
                return conversion.input_type
            else:
                return self._NarrowInputType(
                    type_name) if type_name else 'dynamic'

        if constructor_info.pure_dart_constructor:
            # TODO(antonm): use common dispatcher generation for this case as well.
            has_optional = any(param_info.is_optional
                               for param_info in constructor_info.param_infos)

            if not has_optional:
                self._members_emitter.Emit(
                    '\n  $(METADATA)'
                    'factory $CTOR($PARAMS) => '
                    '$FACTORY.$CTOR_FACTORY_NAME($FACTORY_PARAMS);\n',
                    CTOR=constructor_info._ConstructorFullName(self._DartType),
                    PARAMS=constructor_info.ParametersAsDeclaration(InputType),
                    FACTORY=factory_name,
                    METADATA=metadata,
                    CTOR_FACTORY_NAME=factory_constructor_name,
                    FACTORY_PARAMS=factory_parameters)
            else:
                inits = self._members_emitter.Emit(
                    '\n  $(METADATA)'
                    'factory $CONSTRUCTOR($PARAMS) {\n'
                    '    var e = $FACTORY.$CTOR_FACTORY_NAME($FACTORY_PARAMS);\n'
                    '$!INITS'
                    '    return e;\n'
                    '  }\n',
                    CONSTRUCTOR=constructor_info._ConstructorFullName(
                        self._DartType),
                    METADATA=metadata,
                    FACTORY=factory_name,
                    CTOR_FACTORY_NAME=factory_constructor_name,
                    PARAMS=constructor_info.ParametersAsDeclaration(InputType),
                    FACTORY_PARAMS=factory_parameters)

                for index, param_info in enumerate(
                        constructor_info.param_infos):
                    if param_info.is_optional:
                        inits.Emit('    if ($E != null) e.$E = $E;\n',
                                   E=param_info.name)
        else:
            custom_factory_ctr = self._interface.id in _custom_factories
            constructor_full_name = constructor_info._ConstructorFullName(
                self._DartType)

            def GenerateCall(stmts_emitter, call_emitter, version,
                             signature_index, argument_count):
                name = emitter.Format('_create_$VERSION', VERSION=version)
                arguments = constructor_info.idl_args[
                    signature_index][:argument_count]
                args = None
                call_template = ''
                if self._dart_use_blink:
                    type_ids = [p.type.id for p in arguments]
                    base_name, rs = \
                        self.DeriveNativeEntry("constructorCallback", 'Constructor', argument_count)
                    qualified_name = \
                        self.DeriveQualifiedBlinkName(self._interface.id,
                                                      base_name)
                    args = constructor_info.ParametersAsArgumentList(
                        argument_count)

                    # Handle converting Maps to Dictionaries, etc.
                    (factory_params,
                     converted_arguments) = self._ConvertArgumentTypes(
                         stmts_emitter, arguments, argument_count,
                         constructor_info)
                    args = ', '.join(converted_arguments)
                    call_template = 'wrap_jso($FACTORY_NAME($FACTORY_PARAMS))'
                else:
                    qualified_name = emitter.Format('$FACTORY.$NAME',
                                                    FACTORY=factory_name,
                                                    NAME=name)
                    (factory_params,
                     converted_arguments) = self._ConvertArgumentTypes(
                         stmts_emitter, arguments, argument_count,
                         constructor_info)
                    args = ', '.join(converted_arguments)
                    call_template = '$FACTORY_NAME($FACTORY_PARAMS)'
                call_emitter.Emit(call_template,
                                  FACTORY_NAME=qualified_name,
                                  FACTORY_PARAMS=args)
                self.EmitStaticFactoryOverload(constructor_info, name,
                                               arguments)

            def IsOptional(signature_index, argument):
                return self.IsConstructorArgumentOptional(argument)

            entry_declaration = emitter.Format(
                '$(METADATA)$FACTORY_KEYWORD $CTOR($PARAMS)',
                FACTORY_KEYWORD=('factory' if not custom_factory_ctr else
                                 'static %s' % constructor_full_name),
                CTOR=(('' if not custom_factory_ctr else '_factory') +
                      constructor_full_name),
                METADATA=metadata,
                PARAMS=constructor_info.ParametersAsDeclaration(InputType))

            overload_emitter = self._members_emitter
            overload_declaration = entry_declaration

            self._GenerateOverloadDispatcher(constructor_info,
                                             constructor_info.idl_args, False,
                                             overload_declaration,
                                             GenerateCall, IsOptional,
                                             overload_emitter)
Example #10
0
  def _GenerateNativeCallback(self,
      callback_name,
      needs_receiver,
      function_expression,
      node,
      arguments,
      return_type,
      raises_dom_exception):
    ext_attrs = node.ext_attrs

    cpp_arguments = []
    requires_v8_scope = \
        any((self._TypeInfo(argument.type.id).requires_v8_scope() for argument in arguments))
    runtime_check = None
    raises_exceptions = raises_dom_exception or arguments

    requires_stack_info = ext_attrs.get('CallWith') == 'ScriptArguments|CallStack'
    if requires_stack_info:
      raises_exceptions = True
      requires_v8_scope = True
      cpp_arguments = ['scriptArguments', 'scriptCallStack']
      # WebKit uses scriptArguments to reconstruct last argument, so
      # it's not needed and should be just removed.
      arguments = arguments[:-1]

    requires_script_execution_context = ext_attrs.get('CallWith') == 'ScriptExecutionContext'
    if requires_script_execution_context:
      raises_exceptions = True
      cpp_arguments = ['context']

    requires_dom_window = 'NamedConstructor' in ext_attrs
    if requires_dom_window:
      raises_exceptions = True
      cpp_arguments = ['document']

    if 'ImplementedBy' in ext_attrs:
      assert needs_receiver
      self._cpp_impl_includes.add('"%s.h"' % ext_attrs['ImplementedBy'])
      cpp_arguments.append('receiver')

    if 'Reflect' in ext_attrs:
      cpp_arguments = [self._GenerateWebCoreReflectionAttributeName(node)]

    v8EnabledPerContext = ext_attrs.get('synthesizedV8EnabledPerContext', ext_attrs.get('V8EnabledPerContext'))
    v8EnabledAtRuntime = ext_attrs.get('synthesizedV8EnabledAtRuntime', ext_attrs.get('V8EnabledAtRuntime'))
    assert(not (v8EnabledPerContext and v8EnabledAtRuntime))

    if v8EnabledPerContext:
      raises_exceptions = True
      self._cpp_impl_includes.add('"ContextFeatures.h"')
      self._cpp_impl_includes.add('"DOMWindow.h"')
      runtime_check = emitter.Format(
          '        if (!ContextFeatures::$(FEATURE)Enabled(DartUtilities::domWindowForCurrentIsolate()->document())) {\n'
          '            exception = Dart_NewString("Feature $FEATURE is not enabled");\n'
          '            goto fail;\n'
          '        }',
          FEATURE=v8EnabledPerContext)

    if v8EnabledAtRuntime:
      raises_exceptions = True
      self._cpp_impl_includes.add('"RuntimeEnabledFeatures.h"')
      runtime_check = emitter.Format(
          '        if (!RuntimeEnabledFeatures::$(FEATURE)Enabled()) {\n'
          '            exception = Dart_NewString("Feature $FEATURE is not enabled");\n'
          '            goto fail;\n'
          '        }',
          FEATURE=self._ToWebKitName(v8EnabledAtRuntime))

    body_emitter = self._cpp_definitions_emitter.Emit(
        '\n'
        'static void $CALLBACK_NAME(Dart_NativeArguments args)\n'
        '{\n'
        '    DartApiScope dartApiScope;\n'
        '$!BODY'
        '}\n',
        CALLBACK_NAME=callback_name)

    if raises_exceptions:
      body_emitter = body_emitter.Emit(
          '    Dart_Handle exception = 0;\n'
          '$!BODY'
          '\n'
          'fail:\n'
          '    Dart_ThrowException(exception);\n'
          '    ASSERT_NOT_REACHED();\n')

    body_emitter = body_emitter.Emit(
        '    {\n'
        '$!BODY'
        '        return;\n'
        '    }\n')

    if requires_v8_scope:
      body_emitter.Emit(
          '        V8Scope v8scope;\n\n')

    if runtime_check:
      body_emitter.Emit(
          '$RUNTIME_CHECK\n',
          RUNTIME_CHECK=runtime_check)

    if requires_script_execution_context:
      body_emitter.Emit(
          '        ScriptExecutionContext* context = DartUtilities::scriptExecutionContext();\n'
          '        if (!context) {\n'
          '            exception = Dart_NewString("Failed to retrieve a context");\n'
          '            goto fail;\n'
          '        }\n\n')

    if requires_dom_window:
      self._cpp_impl_includes.add('"DOMWindow.h"')
      body_emitter.Emit(
          '        DOMWindow* domWindow = DartUtilities::domWindowForCurrentIsolate();\n'
          '        if (!domWindow) {\n'
          '            exception = Dart_NewString("Failed to fetch domWindow");\n'
          '            goto fail;\n'
          '        }\n'
          '        Document* document = domWindow->document();\n')

    if needs_receiver:
      body_emitter.Emit(
          '        $WEBCORE_CLASS_NAME* receiver = DartDOMWrapper::receiver< $WEBCORE_CLASS_NAME >(args);\n',
          WEBCORE_CLASS_NAME=self._interface_type_info.native_type())

    if requires_stack_info:
      self._cpp_impl_includes.add('"ScriptArguments.h"')
      self._cpp_impl_includes.add('"ScriptCallStack.h"')
      body_emitter.Emit(
          '\n'
          '        Dart_Handle customArgument = Dart_GetNativeArgument(args, $INDEX);\n'
          '        RefPtr<ScriptArguments> scriptArguments(DartUtilities::createScriptArguments(customArgument, exception));\n'
          '        if (!scriptArguments)\n'
          '            goto fail;\n'
          '        RefPtr<ScriptCallStack> scriptCallStack(DartUtilities::createScriptCallStack());\n'
          '        if (!scriptCallStack->size())\n'
          '            return;\n',
          INDEX=len(arguments) + 1)

    # Emit arguments.
    start_index = 1 if needs_receiver else 0
    for i, argument in enumerate(arguments):
      type_info = self._TypeInfo(argument.type.id)
      argument_expression_template, type, cls, function = \
          type_info.to_native_info(argument, self._interface.id)

      if ((IsOptional(argument) and not self._IsArgumentOptionalInWebCore(node, argument)) or
          (argument.ext_attrs.get('Optional') == 'DefaultIsNullString')):
        function += 'WithNullCheck'

      argument_name = DartDomNameOfAttribute(argument)
      if type_info.pass_native_by_ref():
        invocation_template =\
            '        $TYPE $ARGUMENT_NAME;\n'\
            '        $CLS::$FUNCTION(Dart_GetNativeArgument(args, $INDEX), $ARGUMENT_NAME, exception);\n'
      else:
        invocation_template =\
            '        $TYPE $ARGUMENT_NAME = $CLS::$FUNCTION(Dart_GetNativeArgument(args, $INDEX), exception);\n'
      body_emitter.Emit(
          '\n' +
          invocation_template +
          '        if (exception)\n'
          '            goto fail;\n',
          TYPE=type,
          ARGUMENT_NAME=argument_name,
          CLS=cls,
          FUNCTION=function,
          INDEX=start_index + i)
      self._cpp_impl_includes.add('"%s.h"' % cls)
      cpp_arguments.append(argument_expression_template % argument_name)

    body_emitter.Emit('\n')

    if 'NeedsUserGestureCheck' in ext_attrs:
      cpp_arguments.append('DartUtilities::processingUserGesture')

    invocation_emitter = body_emitter
    if raises_dom_exception:
      cpp_arguments.append('ec')
      invocation_emitter = body_emitter.Emit(
        '        ExceptionCode ec = 0;\n'
        '$!INVOCATION'
        '        if (UNLIKELY(ec)) {\n'
        '            exception = DartDOMWrapper::exceptionCodeToDartException(ec);\n'
        '            goto fail;\n'
        '        }\n')

    function_call = '%s(%s)' % (function_expression, ', '.join(cpp_arguments))
    if return_type == 'void':
      invocation_emitter.Emit(
        '        $FUNCTION_CALL;\n',
        FUNCTION_CALL=function_call)
    else:
      return_type_info = self._TypeInfo(return_type)
      self._cpp_impl_includes |= set(return_type_info.conversion_includes())

      # Generate to Dart conversion of C++ value.
      to_dart_conversion = return_type_info.to_dart_conversion(function_call, self._interface.id, ext_attrs)
      invocation_emitter.Emit(
        '        Dart_Handle returnValue = $TO_DART_CONVERSION;\n'
        '        if (returnValue)\n'
        '            Dart_SetReturnValue(args, returnValue);\n',
        TO_DART_CONVERSION=to_dart_conversion)
Example #11
0
    def _AddConstructor(self, constructor_info, factory_name,
                        factory_constructor_name):
        if self.GenerateCustomFactory(constructor_info):
            return

        annotations = FormatAnnotationsAndComments(
            GetAnnotationsAndComments(self._library_name, self._interface.id,
                                      self._interface.id), '  ')

        if not factory_constructor_name:
            factory_constructor_name = '_create'
            factory_parameters = constructor_info.ParametersAsArgumentList()
            has_factory_provider = True
        else:
            factory_parameters = ', '.join(constructor_info.factory_parameters)
            has_factory_provider = False

        if constructor_info.pure_dart_constructor:
            # TODO(antonm): use common dispatcher generation for this case as well.
            has_optional = any(param_info.is_optional
                               for param_info in constructor_info.param_infos)

            if not has_optional:
                self._members_emitter.Emit(
                    '\n  $(ANNOTATIONS)'
                    'factory $CTOR($PARAMS) => '
                    '$FACTORY.$CTOR_FACTORY_NAME($FACTORY_PARAMS);\n',
                    CTOR=constructor_info._ConstructorFullName(self._DartType),
                    PARAMS=constructor_info.ParametersDeclaration(
                        self._DartType),
                    FACTORY=factory_name,
                    ANNOTATIONS=annotations,
                    CTOR_FACTORY_NAME=factory_constructor_name,
                    FACTORY_PARAMS=factory_parameters)
            else:
                if has_factory_provider:
                    dispatcher_emitter = self._members_emitter.Emit(
                        '\n  $(ANNOTATIONS)'
                        'factory $CTOR($PARAMS) {\n'
                        '$!DISPATCHER'
                        '    return $FACTORY._create($FACTORY_PARAMS);\n'
                        '  }\n',
                        CTOR=constructor_info._ConstructorFullName(
                            self._DartType),
                        PARAMS=constructor_info.ParametersDeclaration(
                            self._DartType),
                        FACTORY=factory_name,
                        ANNOTATIONS=annotations,
                        FACTORY_PARAMS=constructor_info.
                        ParametersAsArgumentList())

                    for index, param_info in enumerate(
                            constructor_info.param_infos):
                        if param_info.is_optional:
                            dispatcher_emitter.Emit(
                                '    if (!?$OPT_PARAM_NAME) {\n'
                                '      return $FACTORY._create($FACTORY_PARAMS);\n'
                                '    }\n',
                                OPT_PARAM_NAME=param_info.name,
                                FACTORY=factory_name,
                                FACTORY_PARAMS=constructor_info.
                                ParametersAsArgumentList(index))
                else:
                    inits = self._members_emitter.Emit(
                        '\n  $(ANNOTATIONS)'
                        'factory $CONSTRUCTOR($PARAMS) {\n'
                        '    var e = $FACTORY.$CTOR_FACTORY_NAME($FACTORY_PARAMS);\n'
                        '$!INITS'
                        '    return e;\n'
                        '  }\n',
                        CONSTRUCTOR=constructor_info._ConstructorFullName(
                            self._DartType),
                        ANNOTATIONS=annotations,
                        FACTORY=factory_name,
                        CTOR_FACTORY_NAME=factory_constructor_name,
                        PARAMS=constructor_info.ParametersDeclaration(
                            self._DartType),
                        FACTORY_PARAMS=factory_parameters)

                    for index, param_info in enumerate(
                            constructor_info.param_infos):
                        if param_info.is_optional:
                            inits.Emit('    if ($E != null) e.$E = $E;\n',
                                       E=param_info.name)
        else:

            def GenerateCall(stmts_emitter, call_emitter, version,
                             signature_index, argument_count):
                name = emitter.Format('_create_$VERSION', VERSION=version)
                call_emitter.Emit('$FACTORY.$NAME($FACTORY_PARAMS)',
                    FACTORY=factory_name,
                    NAME=name,
                    FACTORY_PARAMS= \
                        constructor_info.ParametersAsArgumentList(argument_count))
                self.EmitStaticFactoryOverload(
                    constructor_info, name,
                    constructor_info.idl_args[signature_index]
                    [:argument_count])

            def IsOptional(signature_index, argument):
                return self.IsConstructorArgumentOptional(argument)

            custom_factory_ctr = self._interface.id in _custom_factories
            constructor_full_name = constructor_info._ConstructorFullName(
                self._DartType)
            self._GenerateOverloadDispatcher(
                constructor_info.idl_args, False,
                [info.name for info in constructor_info.param_infos],
                emitter.Format(
                    '$(ANNOTATIONS)$FACTORY_KEYWORD $CTOR($PARAMS)',
                    FACTORY_KEYWORD=('factory' if not custom_factory_ctr else
                                     'static %s' % constructor_full_name),
                    CTOR=(('' if not custom_factory_ctr else '_factory') +
                          constructor_full_name),
                    ANNOTATIONS=annotations,
                    PARAMS=constructor_info.ParametersDeclaration(
                        self._DartType)), GenerateCall, IsOptional)
Example #12
0
    def _AddConstructor(self, constructor_info, factory_name,
                        factory_constructor_name):
        # Hack to ignore the Image constructor used by JavaScript.
        if (self._interface.id == 'HTMLImageElement'
                and not constructor_info.pure_dart_constructor):
            return

        if self.GenerateCustomFactory(constructor_info):
            return

        metadata = self._metadata.GetFormattedMetadata(self._library_name,
                                                       self._interface,
                                                       self._interface.id,
                                                       '  ')

        if not factory_constructor_name:
            factory_constructor_name = '_create'
            factory_parameters = constructor_info.ParametersAsArgumentList()
        else:
            factory_parameters = ', '.join(constructor_info.factory_parameters)

        if constructor_info.pure_dart_constructor:
            # TODO(antonm): use common dispatcher generation for this case as well.
            has_optional = any(param_info.is_optional
                               for param_info in constructor_info.param_infos)

            if not has_optional:
                self._members_emitter.Emit(
                    '\n  $(METADATA)'
                    'factory $CTOR($PARAMS) => '
                    '$FACTORY.$CTOR_FACTORY_NAME($FACTORY_PARAMS);\n',
                    CTOR=constructor_info._ConstructorFullName(self._DartType),
                    PARAMS=constructor_info.ParametersAsDeclaration(
                        self._DartType),
                    FACTORY=factory_name,
                    METADATA=metadata,
                    CTOR_FACTORY_NAME=factory_constructor_name,
                    FACTORY_PARAMS=factory_parameters)
            else:
                inits = self._members_emitter.Emit(
                    '\n  $(METADATA)'
                    'factory $CONSTRUCTOR($PARAMS) {\n'
                    '    var e = $FACTORY.$CTOR_FACTORY_NAME($FACTORY_PARAMS);\n'
                    '$!INITS'
                    '    return e;\n'
                    '  }\n',
                    CONSTRUCTOR=constructor_info._ConstructorFullName(
                        self._DartType),
                    METADATA=metadata,
                    FACTORY=factory_name,
                    CTOR_FACTORY_NAME=factory_constructor_name,
                    PARAMS=constructor_info.ParametersAsDeclaration(
                        self._DartType),
                    FACTORY_PARAMS=factory_parameters)

                for index, param_info in enumerate(
                        constructor_info.param_infos):
                    if param_info.is_optional:
                        inits.Emit('    if ($E != null) e.$E = $E;\n',
                                   E=param_info.name)
        else:

            def GenerateCall(stmts_emitter, call_emitter, version,
                             signature_index, argument_count):
                name = emitter.Format('_create_$VERSION', VERSION=version)
                call_emitter.Emit('$FACTORY.$NAME($FACTORY_PARAMS)',
                    FACTORY=factory_name,
                    NAME=name,
                    FACTORY_PARAMS= \
                        constructor_info.ParametersAsArgumentList(argument_count))
                self.EmitStaticFactoryOverload(
                    constructor_info, name,
                    constructor_info.idl_args[signature_index]
                    [:argument_count])

            def IsOptional(signature_index, argument):
                return self.IsConstructorArgumentOptional(argument)

            custom_factory_ctr = self._interface.id in _custom_factories
            constructor_full_name = constructor_info._ConstructorFullName(
                self._DartType)
            self._GenerateOverloadDispatcher(
                constructor_info, constructor_info.idl_args, False,
                emitter.Format(
                    '$(METADATA)$FACTORY_KEYWORD $CTOR($PARAMS)',
                    FACTORY_KEYWORD=('factory' if not custom_factory_ctr else
                                     'static %s' % constructor_full_name),
                    CTOR=(('' if not custom_factory_ctr else '_factory') +
                          constructor_full_name),
                    METADATA=metadata,
                    PARAMS=constructor_info.ParametersAsDeclaration(
                        self._DartType)), GenerateCall, IsOptional)
Example #13
0
    def _GenerateCPPHeader(self):
        to_native_emitter = emitter.Emitter()
        if self._interface_type_info.custom_to_native():
            return_type = 'PassRefPtr<NativeType>'
            to_native_body = ';'
        else:
            return_type = 'NativeType*'
            to_native_body = emitter.Format(
                '\n'
                '    {\n'
                '        return DartDOMWrapper::unwrapDartWrapper<Dart$INTERFACE>(handle, exception);\n'
                '    }',
                INTERFACE=self._interface.id)

        to_native_emitter.Emit(
            '    static $RETURN_TYPE toNative(Dart_Handle handle, Dart_Handle& exception)$TO_NATIVE_BODY\n'
            '\n'
            '    static $RETURN_TYPE toNativeWithNullCheck(Dart_Handle handle, Dart_Handle& exception)\n'
            '    {\n'
            '        return Dart_IsNull(handle) ? 0 : toNative(handle, exception);\n'
            '    }\n',
            RETURN_TYPE=return_type,
            TO_NATIVE_BODY=to_native_body,
            INTERFACE=self._interface.id)

        to_dart_emitter = emitter.Emitter()

        ext_attrs = self._interface.ext_attrs

        if ('CustomToJS' in ext_attrs or
            ('CustomToJSObject' in ext_attrs and 'TypedArray' not in ext_attrs)
                or 'PureInterface' in ext_attrs
                or 'CPPPureInterface' in ext_attrs
                or self._interface_type_info.custom_to_dart()):
            to_dart_emitter.Emit(
                '    static Dart_Handle toDart(NativeType* value);\n')
        else:
            to_dart_emitter.Emit(
                '    static Dart_Handle toDart(NativeType* value)\n'
                '    {\n'
                '        return DartDOMWrapper::toDart<Dart$(INTERFACE)>(value);\n'
                '    }\n',
                INTERFACE=self._interface.id)

        webcore_includes = self._GenerateCPPIncludes(
            self._interface_type_info.webcore_includes())

        is_node_test = lambda interface: interface.id == 'Node'
        is_active_test = lambda interface: 'ActiveDOMObject' in interface.ext_attrs
        is_event_target_test = lambda interface: 'EventTarget' in interface.ext_attrs

        def TypeCheckHelper(test):
            return 'true' if any(
                map(test, self._database.Hierarchy(
                    self._interface))) else 'false'

        self._cpp_header_emitter.Emit(
            self._template_loader.Load('cpp_header.template'),
            INTERFACE=self._interface.id,
            WEBCORE_INCLUDES=webcore_includes,
            WEBCORE_CLASS_NAME=self._interface_type_info.native_type(),
            DECLARATIONS=self._cpp_declarations_emitter.Fragments(),
            IS_NODE=TypeCheckHelper(is_node_test),
            IS_ACTIVE=TypeCheckHelper(is_active_test),
            IS_EVENT_TARGET=TypeCheckHelper(is_event_target_test),
            TO_NATIVE=to_native_emitter.Fragments(),
            TO_DART=to_dart_emitter.Fragments())
Example #14
0
    def _AddConstructor(self, constructor_info, factory_name,
                        factory_constructor_name):
        # Hack to ignore the Image constructor used by JavaScript.
        if (self._interface.id == 'HTMLImageElement'
                and not constructor_info.pure_dart_constructor):
            return

        if self.GenerateCustomFactory(constructor_info):
            return

        metadata = self._metadata.GetFormattedMetadata(self._library_name,
                                                       self._interface,
                                                       self._interface.id,
                                                       '  ')

        if not factory_constructor_name:
            factory_constructor_name = '_create'
            factory_parameters = constructor_info.ParametersAsArgumentList()
        else:
            factory_parameters = ', '.join(constructor_info.factory_parameters)

        if constructor_info.pure_dart_constructor:
            # TODO(antonm): use common dispatcher generation for this case as well.
            has_optional = any(param_info.is_optional
                               for param_info in constructor_info.param_infos)

            if not has_optional:
                self._members_emitter.Emit(
                    '\n  $(METADATA)'
                    'factory $CTOR($PARAMS) => '
                    '$FACTORY.$CTOR_FACTORY_NAME($FACTORY_PARAMS);\n',
                    CTOR=constructor_info._ConstructorFullName(self._DartType),
                    PARAMS=constructor_info.ParametersAsDeclaration(
                        self._DartType),
                    FACTORY=factory_name,
                    METADATA=metadata,
                    CTOR_FACTORY_NAME=factory_constructor_name,
                    FACTORY_PARAMS=factory_parameters)
            else:
                inits = self._members_emitter.Emit(
                    '\n  $(METADATA)'
                    'factory $CONSTRUCTOR($PARAMS) {\n'
                    '    var e = $FACTORY.$CTOR_FACTORY_NAME($FACTORY_PARAMS);\n'
                    '$!INITS'
                    '    return e;\n'
                    '  }\n',
                    CONSTRUCTOR=constructor_info._ConstructorFullName(
                        self._DartType),
                    METADATA=metadata,
                    FACTORY=factory_name,
                    CTOR_FACTORY_NAME=factory_constructor_name,
                    PARAMS=constructor_info.ParametersAsDeclaration(
                        self._DartType),
                    FACTORY_PARAMS=factory_parameters)

                for index, param_info in enumerate(
                        constructor_info.param_infos):
                    if param_info.is_optional:
                        inits.Emit('    if ($E != null) e.$E = $E;\n',
                                   E=param_info.name)
        else:
            custom_factory_ctr = self._interface.id in _custom_factories
            constructor_full_name = constructor_info._ConstructorFullName(
                self._DartType)

            def GenerateCall(stmts_emitter, call_emitter, version,
                             signature_index, argument_count):
                name = emitter.Format('_create_$VERSION', VERSION=version)
                if self._dart_use_blink:
                    qualified_name = \
                        "_".join(["Native",self._interface.id,
                                  name + 'constructorCallback'])
                else:
                    qualified_name = emitter.Format('$FACTORY.$NAME',
                                                    FACTORY=factory_name,
                                                    NAME=name)
                call_emitter.Emit('$FACTORY_NAME($FACTORY_PARAMS)',
                    FACTORY_NAME=qualified_name,
                    FACTORY_PARAMS= \
                        constructor_info.ParametersAsArgumentList(argument_count))
                self.EmitStaticFactoryOverload(
                    constructor_info, name,
                    constructor_info.idl_args[signature_index]
                    [:argument_count])

            def IsOptional(signature_index, argument):
                return self.IsConstructorArgumentOptional(argument)

            entry_declaration = emitter.Format(
                '$(METADATA)$FACTORY_KEYWORD $CTOR($PARAMS)',
                FACTORY_KEYWORD=('factory' if not custom_factory_ctr else
                                 'static %s' % constructor_full_name),
                CTOR=(('' if not custom_factory_ctr else '_factory') +
                      constructor_full_name),
                METADATA=metadata,
                PARAMS=constructor_info.ParametersAsDeclaration(
                    self._DartType))

            if self._dart_use_blink:
                overload_emitter = self._native_library_emitter
                mname = constructor_full_name.replace(".", "_")
                blink_name = \
                    "_".join(["Native",self._interface.id, mname])
                qual_name = self._native_library_name + "." + blink_name
                actuals_s = constructor_info.ParametersAsStringOfVariables()
                self._members_emitter.Emit(
                    '\n'
                    '  $DECLARATION => $NATIVE_NAME($ACTUALS);\n',
                    DECLARATION=entry_declaration,
                    NATIVE_NAME=qual_name,
                    ACTUALS=actuals_s)
                overload_declaration = emitter.Format(
                    '// Generated overload resolver\n'
                    '$CTOR($PARAMS)',
                    CTOR=blink_name,
                    PARAMS=actuals_s)

            else:
                overload_emitter = self._members_emitter
                overload_declaration = entry_declaration

            self._GenerateOverloadDispatcher(constructor_info,
                                             constructor_info.idl_args, False,
                                             overload_declaration,
                                             GenerateCall, IsOptional,
                                             overload_emitter)
Example #15
0
    def _GenerateConstructors(self):
        html_interface_name = self._HTMLInterfaceName(self._interface.id)

        if not self._IsConstructable():
            return

        # TODO(antonm): currently we don't have information about number of arguments expected by
        # the constructor, so name only dispatch.
        self._cpp_resolver_emitter.Emit(
            '    if (name == "$(INTERFACE_NAME)_constructor_Callback")\n'
            '        return Dart$(INTERFACE_NAME)Internal::constructorCallback;\n',
            INTERFACE_NAME=self._interface.id)

        constructor_info = AnalyzeConstructor(self._interface)
        if constructor_info:
            self._EmitFactoryProvider(self._interface.id, constructor_info)

        ext_attrs = self._interface.ext_attrs

        if 'CustomConstructor' in ext_attrs:
            # We have a custom implementation for it.
            self._cpp_declarations_emitter.Emit(
                '\n'
                'void constructorCallback(Dart_NativeArguments);\n')
            return

        raises_dom_exceptions = 'ConstructorRaisesException' in ext_attrs
        raises_exceptions = raises_dom_exceptions or len(
            constructor_info.idl_args) > 0
        arguments = []
        parameter_definitions_emitter = emitter.Emitter()
        create_function = 'create'
        if 'NamedConstructor' in ext_attrs:
            raises_exceptions = True
            self._cpp_impl_includes.add('"DOMWindow.h"')
            parameter_definitions_emitter.Emit(
                '        DOMWindow* domWindow = DartUtilities::domWindowForCurrentIsolate();\n'
                '        if (!domWindow) {\n'
                '            exception = Dart_NewString("Failed to fetch domWindow");\n'
                '            goto fail;\n'
                '        }\n'
                '        Document* document = domWindow->document();\n')
            arguments.append('document')
            create_function = 'createForJSConstructor'
        if 'CallWith' in ext_attrs:
            call_with = ext_attrs['CallWith']
            if call_with == 'ScriptExecutionContext':
                raises_exceptions = True
                parameter_definitions_emitter.Emit(
                    '        ScriptExecutionContext* context = DartUtilities::scriptExecutionContext();\n'
                    '        if (!context) {\n'
                    '            exception = Dart_NewString("Failed to create an object");\n'
                    '            goto fail;\n'
                    '        }\n')
                arguments.append('context')
            else:
                raise Exception('Unsupported CallWith=%s attribute' %
                                call_with)

        # Process constructor arguments.
        for (i, argument) in enumerate(constructor_info.idl_args):
            argument_expression = self._GenerateToNative(
                parameter_definitions_emitter, argument, i)
            arguments.append(argument_expression)

        function_expression = '%s::%s' % (
            self._interface_type_info.native_type(), create_function)
        invocation = self._GenerateWebCoreInvocation(function_expression,
                                                     arguments,
                                                     self._interface.id,
                                                     ext_attrs,
                                                     raises_dom_exceptions)

        runtime_check = None
        database = self._database
        assert (not ('synthesizedV8EnabledPerContext' in ext_attrs
                     and 'synthesizedV8EnabledAtRuntime' in ext_attrs))
        if 'synthesizedV8EnabledPerContext' in ext_attrs:
            raises_exceptions = True
            self._cpp_impl_includes.add('"ContextFeatures.h"')
            self._cpp_impl_includes.add('"DOMWindow.h"')
            runtime_check = emitter.Format(
                '        if (!ContextFeatures::$(FEATURE)Enabled(DartUtilities::domWindowForCurrentIsolate()->document())) {\n'
                '            exception = Dart_NewString("Feature $FEATURE is not enabled");\n'
                '            goto fail;\n'
                '        }',
                FEATURE=ext_attrs['synthesizedV8EnabledPerContext'])

        if 'synthesizedV8EnabledAtRuntime' in ext_attrs:
            raises_exceptions = True
            self._cpp_impl_includes.add('"RuntimeEnabledFeatures.h"')
            runtime_check = emitter.Format(
                '        if (!RuntimeEnabledFeatures::$(FEATURE)Enabled()) {\n'
                '            exception = Dart_NewString("Feature $FEATURE is not enabled");\n'
                '            goto fail;\n'
                '        }',
                FEATURE=_ToWebKitName(
                    ext_attrs['synthesizedV8EnabledAtRuntime']))

        self._GenerateNativeCallback(
            callback_name='constructorCallback',
            parameter_definitions=parameter_definitions_emitter.Fragments(),
            needs_receiver=False,
            invocation=invocation,
            raises_exceptions=raises_exceptions,
            runtime_check=runtime_check)
Example #16
0
    def _GenerateWebCoreInvocation(self, function_expression, arguments,
                                   idl_return_type, attributes,
                                   raises_dom_exceptions):
        invocation_template = '        $FUNCTION_CALL;\n'
        if idl_return_type != 'void':
            return_type_info = GetIDLTypeInfo(idl_return_type)
            self._cpp_impl_includes |= set(
                return_type_info.conversion_includes())

            # Generate C++ cast based on idl return type.
            conversion_cast = return_type_info.conversion_cast(
                '$FUNCTION_CALL')
            if isinstance(return_type_info, SVGTearOffIDLTypeInfo):
                svg_primitive_types = [
                    'SVGAngle', 'SVGLength', 'SVGMatrix', 'SVGNumber',
                    'SVGPoint', 'SVGRect', 'SVGTransform'
                ]
                conversion_cast = '%s::create($FUNCTION_CALL)'
                if self._interface.id.startswith('SVGAnimated'):
                    conversion_cast = 'static_cast<%s*>($FUNCTION_CALL)'
                elif return_type_info.idl_type() == 'SVGStringList':
                    conversion_cast = '%s::create(receiver, $FUNCTION_CALL)'
                elif self._interface.id.endswith('List'):
                    conversion_cast = 'static_cast<%s*>($FUNCTION_CALL.get())'
                elif return_type_info.idl_type() in svg_primitive_types:
                    conversion_cast = '%s::create($FUNCTION_CALL)'
                else:
                    conversion_cast = 'static_cast<%s*>($FUNCTION_CALL)'
                conversion_cast = conversion_cast % return_type_info.native_type(
                )

            # Generate to Dart conversion of C++ value.
            conversion_arguments = [conversion_cast]
            if (return_type_info.idl_type() in ['DOMString', 'AtomicString']
                    and 'TreatReturnedNullStringAs' in attributes):
                conversion_arguments.append('ConvertDefaultToNull')

            invocation_template = emitter.Format(
                '        Dart_Handle returnValue = toDartValue($ARGUMENTS);\n'
                '        if (returnValue)\n'
                '            Dart_SetReturnValue(args, returnValue);\n',
                ARGUMENTS=', '.join(conversion_arguments))

        if raises_dom_exceptions:
            # Add 'ec' argument to WebCore invocation and convert DOM exception to Dart exception.
            arguments.append('ec')
            invocation_template = emitter.Format(
                '        ExceptionCode ec = 0;\n'
                '$INVOCATION'
                '        if (UNLIKELY(ec)) {\n'
                '            exception = DartDOMWrapper::exceptionCodeToDartException(ec);\n'
                '            goto fail;\n'
                '        }\n',
                INVOCATION=invocation_template)

        if 'ImplementedBy' in attributes:
            arguments.insert(0, 'receiver')
            self._cpp_impl_includes.add('"%s.h"' % attributes['ImplementedBy'])

        return emitter.Format(invocation_template,
                              FUNCTION_CALL='%s(%s)' %
                              (function_expression, ', '.join(arguments)))