summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/bindings/scripts/bind_gen/blink_v8_bridge.py
blob: 22438ad3c9f360ae4498caeefba0505eafa8dc50 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import web_idl

from . import name_style
from .code_node import CodeNode
from .code_node import SymbolDefinitionNode
from .code_node import SymbolNode
from .code_node import SymbolScopeNode
from .code_node import TextNode
from .code_node import UnlikelyExitNode
from .codegen_format import format_template as _format


def blink_class_name(idl_definition):
    """
    Returns the class name of Blink implementation.
    """
    try:
        class_name = idl_definition.extended_attributes.get(
            "ImplementedAs").value
    except:
        class_name = idl_definition.identifier

    if isinstance(idl_definition,
                  (web_idl.CallbackFunction, web_idl.CallbackInterface)):
        return name_style.class_("v8", class_name)
    else:
        return name_style.class_(class_name)


def blink_type_info(idl_type):
    """
    Returns the types of Blink implementation corresponding to the given IDL
    type.  The returned object has the following attributes.

      member_t: The type of a member variable.  E.g. T => Member<T>
      ref_t: The type of a local variable that references to an already-existing
          value.  E.g. String => String&
      value_t: The type of a variable that behaves as a value.  E.g. String =>
          String
      is_nullable: True if the Blink implementation type can represent IDL null
          value by itself.
    """
    assert isinstance(idl_type, web_idl.IdlType)

    class TypeInfo(object):
        def __init__(self,
                     typename,
                     member_fmt="{}",
                     ref_fmt="{}",
                     value_fmt="{}",
                     is_nullable=False):
            self.member_t = member_fmt.format(typename)
            self.ref_t = ref_fmt.format(typename)
            self.value_t = value_fmt.format(typename)
            # Whether Blink impl type can represent IDL null or not.
            self.is_nullable = is_nullable

    real_type = idl_type.unwrap(typedef=True)

    if real_type.is_boolean or real_type.is_numeric:
        cxx_type = {
            "boolean": "bool",
            "byte": "int8_t",
            "octet": "uint8_t",
            "short": "int16_t",
            "unsigned short": "uint16_t",
            "long": "int32_t",
            "unsigned long": "uint32_t",
            "long long": "int64_t",
            "unsigned long long": "uint64_t",
            "float": "float",
            "unrestricted float": "float",
            "double": "double",
            "unrestricted double": "double",
        }
        return TypeInfo(cxx_type[real_type.keyword_typename])

    if real_type.is_string:
        return TypeInfo("String", ref_fmt="{}&", is_nullable=True)

    if real_type.is_symbol:
        assert False, "Blink does not support/accept IDL symbol type."

    if real_type.is_any or real_type.is_object:
        return TypeInfo("ScriptValue", ref_fmt="{}&", is_nullable=True)

    if real_type.is_void:
        assert False, "Blink does not support/accept IDL void type."

    if real_type.type_definition_object is not None:
        type_def_obj = real_type.type_definition_object
        blink_impl_type = (
            type_def_obj.code_generator_info.receiver_implemented_as
            or name_style.class_(type_def_obj.identifier))
        return TypeInfo(
            blink_impl_type,
            member_fmt="Member<{}>",
            ref_fmt="{}*",
            value_fmt="{}*",
            is_nullable=True)

    if (real_type.is_sequence or real_type.is_frozen_array
            or real_type.is_variadic):
        element_type = blink_type_info(real_type.element_type)
        return TypeInfo(
            "VectorOf<{}>".format(element_type.value_t), ref_fmt="{}&")

    if real_type.is_record:
        key_type = blink_type_info(real_type.key_type)
        value_type = blink_type_info(real_type.value_type)
        return TypeInfo(
            "VectorOfPairs<{}, {}>".format(key_type.value_t,
                                           value_type.value_t),
            ref_fmt="{}&")

    if real_type.is_promise:
        return TypeInfo("ScriptPromise", ref_fmt="{}&")

    if real_type.is_union:
        return TypeInfo("ToBeImplementedUnion")

    if real_type.is_nullable:
        inner_type = blink_type_info(real_type.inner_type)
        if inner_type.is_nullable:
            return inner_type
        return TypeInfo(
            "base::Optional<{}>".format(inner_type.value_t), ref_fmt="{}&")


def native_value_tag(idl_type):
    """Returns the tag type of NativeValueTraits."""
    assert isinstance(idl_type, web_idl.IdlType)

    real_type = idl_type.unwrap(typedef=True)

    if (real_type.is_boolean or real_type.is_numeric or real_type.is_string
            or real_type.is_any or real_type.is_object):
        return "IDL{}".format(real_type.type_name)

    if real_type.is_symbol:
        assert False, "Blink does not support/accept IDL symbol type."

    if real_type.is_void:
        assert False, "Blink does not support/accept IDL void type."

    if real_type.type_definition_object is not None:
        return blink_type_info(real_type).value_t

    if real_type.is_sequence:
        return "IDLSequence<{}>".format(
            native_value_tag(real_type.element_type))

    if real_type.is_record:
        return "IDLRecord<{}, {}>".format(
            native_value_tag(real_type.key_type),
            native_value_tag(real_type.value_type))

    if real_type.is_promise:
        return "IDLPromise"

    if real_type.is_union:
        return blink_type_info(real_type).value_t

    if real_type.is_nullable:
        return "IDLNullable<{}>".format(native_value_tag(real_type.inner_type))


def make_v8_to_blink_value(blink_var_name,
                           v8_value_expr,
                           idl_type,
                           default_value=None):
    """
    Returns a SymbolNode whose definition converts a v8::Value to a Blink value.
    """
    assert isinstance(blink_var_name, str)
    assert isinstance(v8_value_expr, str)
    assert isinstance(idl_type, web_idl.IdlType)
    assert (default_value is None
            or isinstance(default_value, web_idl.LiteralConstant))

    pattern = (
        "const auto& ${{{_1}}} = NativeValueTraits<{_2}>::NativeValue({_3});")
    _1 = blink_var_name
    _2 = native_value_tag(idl_type)
    _3 = ["${isolate}", v8_value_expr, "${exception_state}"]
    text = _format(pattern, _1=_1, _2=_2, _3=", ".join(_3))

    def create_definition(symbol_node):
        return SymbolDefinitionNode(symbol_node, [
            TextNode(text),
            UnlikelyExitNode(
                cond=TextNode("${exception_state}.HadException()"),
                body=SymbolScopeNode([TextNode("return;")])),
        ])

    return SymbolNode(blink_var_name, definition_constructor=create_definition)


def make_v8_to_blink_value_variadic(blink_var_name, v8_array,
                                    v8_array_start_index, idl_type):
    """
    Returns a SymbolNode whose definition converts an array of v8::Value
    (variadic arguments) to a Blink value.
    """
    assert isinstance(blink_var_name, str)
    assert isinstance(v8_array, str)
    assert isinstance(v8_array_start_index, (int, long))
    assert isinstance(idl_type, web_idl.IdlType)

    pattern = "const auto& ${{{_1}}} = ToImplArguments<{_2}>({_3});"
    _1 = blink_var_name
    _2 = native_value_tag(idl_type.element_type)
    _3 = [v8_array, str(v8_array_start_index), "${exception_state}"]
    text = _format(pattern, _1=_1, _2=_2, _3=", ".join(_3))

    def create_definition(symbol_node):
        return SymbolDefinitionNode(symbol_node, [
            TextNode(text),
            UnlikelyExitNode(
                cond=TextNode("${exception_state}.HadException()"),
                body=SymbolScopeNode([TextNode("return;")])),
        ])

    return SymbolNode(blink_var_name, definition_constructor=create_definition)