File: codegen_utils.py

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (233 lines) | stat: -rw-r--r-- 8,955 bytes parent folder | download | duplicates (5)
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
229
230
231
232
233
# Copyright 2019 The Chromium Authors
# 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 . import style_format
from .blink_v8_bridge import blink_class_name
from .blink_v8_bridge import blink_type_info
from .code_node import CodeNode
from .code_node import EmptyNode
from .code_node import LiteralNode
from .code_node import SequenceNode
from .code_node import render_code_node
from .codegen_accumulator import IncludeDefinition
from .codegen_accumulator import CodeGenAccumulator
from .path_manager import PathManager


def make_copyright_header():
    return LiteralNode("""\
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// DO NOT EDIT: This file is auto-generated by
// //third_party/blink/renderer/bindings/scripts/generate_bindings.py
//
// Use the GN flag `blink_enable_generated_code_formatting=true` to enable
// formatting of the generated files.\
""")


def make_forward_declarations(accumulator):
    assert isinstance(accumulator, CodeGenAccumulator)

    class ForwardDeclarations(object):
        def __init__(self, accumulator):
            self._accumulator = accumulator

        def __str__(self):
            return "\n".join([
                "class {};".format(class_name)
                for class_name in sorted(self._accumulator.class_decls)
            ] + [
                "struct {};".format(struct_name)
                for struct_name in sorted(self._accumulator.struct_decls)
            ])

    return LiteralNode(ForwardDeclarations(accumulator))


def make_header_include_directives(accumulator):
    assert isinstance(accumulator, CodeGenAccumulator)

    class HeaderIncludeDirectives(object):
        def __init__(self, accumulator):
            self._accumulator = accumulator

        def __str__(self):
            lines = []

            def eol_comment(header: IncludeDefinition) -> str:
                return f"  // {header.annotation}" if header.annotation else ""

            if self._accumulator.stdcpp_include_headers:
                lines.extend(
                    sorted([
                        "#include <{}>{}".format(h.filename, eol_comment(h))
                        for h in self._accumulator.stdcpp_include_headers
                    ]))
                lines.append("")

            lines.extend(
                sorted([
                    '#include "{}"{}'.format(h.filename, eol_comment(h))
                    for h in self._accumulator.include_headers
                ]))

            return "\n".join(lines)

    return LiteralNode(HeaderIncludeDirectives(accumulator))


def collect_forward_decls_and_include_headers(idl_types):
    assert isinstance(idl_types, (list, tuple))
    assert all(isinstance(idl_type, web_idl.IdlType) for idl_type in idl_types)

    header_forward_decls = set()
    header_include_headers = set()
    header_stdcpp_include_headers = set()
    source_forward_decls = set()
    source_include_headers = set()

    def collect(idl_type):
        if idl_type.is_any or idl_type.is_object:
            header_include_headers.add(
                "third_party/blink/renderer/bindings/core/v8/script_value.h")
        elif idl_type.is_boolean or idl_type.is_numeric:
            pass
        elif idl_type.is_bigint:
            header_include_headers.add(
                "third_party/blink/renderer/platform/bindings/bigint.h")
        elif idl_type.is_data_view:
            header_include_headers.update([
                "third_party/blink/renderer/core/typed_arrays/array_buffer_view_helpers.h",
                "third_party/blink/renderer/core/typed_arrays/dom_data_view.h",
                "third_party/blink/renderer/platform/heap/member.h",
            ])
        elif idl_type.is_buffer_source_type:
            header_include_headers.update([
                "third_party/blink/renderer/core/typed_arrays/array_buffer_view_helpers.h",
                "third_party/blink/renderer/core/typed_arrays/dom_typed_array.h",
                "third_party/blink/renderer/platform/heap/member.h",
            ])
        elif idl_type.is_nullable:
            if not blink_type_info(idl_type.inner_type).has_null_value:
                header_stdcpp_include_headers.add("optional")
        elif idl_type.is_promise:
            header_include_headers.add(
                "third_party/blink/renderer/bindings/core/v8/script_promise.h")
        elif (idl_type.is_sequence or idl_type.is_frozen_array
              or idl_type.is_record or idl_type.is_variadic):
            header_include_headers.add(
                "third_party/blink/renderer/platform/heap/collection_support/heap_vector.h"
            )
        elif idl_type.is_string:
            header_include_headers.add(
                "third_party/blink/renderer/platform/wtf/text/wtf_string.h")
        elif idl_type.is_typedef:
            pass
        elif idl_type.is_undefined:
            header_include_headers.add(
                "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
            )
        elif idl_type.type_definition_object:
            type_def_obj = idl_type.type_definition_object
            if type_def_obj.is_enumeration:
                header_include_headers.add(
                    PathManager(type_def_obj).api_path(ext="h"))
            elif type_def_obj.is_interface:
                header_forward_decls.add(blink_class_name(type_def_obj))
                header_include_headers.add(
                    "third_party/blink/renderer/platform/heap/member.h")
                source_include_headers.add(
                    PathManager(type_def_obj).blink_path(ext="h"))
            else:
                header_forward_decls.add(blink_class_name(type_def_obj))
                header_include_headers.add(
                    "third_party/blink/renderer/platform/heap/member.h")
                source_include_headers.add(
                    PathManager(type_def_obj).api_path(ext="h"))
        elif idl_type.union_definition_object:
            union_def_obj = idl_type.union_definition_object
            header_forward_decls.add(blink_class_name(union_def_obj))
            header_include_headers.add(
                "third_party/blink/renderer/platform/heap/member.h")
            source_include_headers.add(
                PathManager(union_def_obj).api_path(ext="h"))
        else:
            assert False, "Unknown type: {}".format(idl_type.syntactic_form)

    for idl_type in idl_types:
        idl_type.apply_to_all_composing_elements(collect)

    return (
        header_forward_decls,
        header_include_headers,
        header_stdcpp_include_headers,
        source_forward_decls,
        source_include_headers,
    )


def component_export(component, for_testing):
    assert isinstance(component, web_idl.Component)
    assert isinstance(for_testing, bool)

    if for_testing:
        return ""
    return name_style.macro(component, "EXPORT")


def component_export_header(component, for_testing):
    assert isinstance(component, web_idl.Component)
    assert isinstance(for_testing, bool)

    if for_testing:
        return None
    if component == "core":
        return "third_party/blink/renderer/core/core_export.h"
    elif component == "modules":
        return "third_party/blink/renderer/modules/modules_export.h"
    elif component == "extensions_chromeos":
        return "third_party/blink/renderer/extensions/chromeos/extensions_chromeos_export.h"
    elif component == "extensions_webview":
        return "third_party/blink/renderer/extensions/webview/extensions_webview_export.h"
    else:
        assert False


def enclose_with_header_guard(code_node, header_guard):
    assert isinstance(code_node, CodeNode)
    assert isinstance(header_guard, str)

    return SequenceNode([
        LiteralNode("#ifndef {}".format(header_guard)),
        LiteralNode("#define {}".format(header_guard)),
        EmptyNode(),
        code_node,
        EmptyNode(),
        LiteralNode("#endif  // {}".format(header_guard)),
    ])


def write_code_node_to_file(code_node, filepath):
    """Renders |code_node| and then write the result to |filepath|."""
    assert isinstance(code_node, CodeNode)
    assert isinstance(filepath, str)

    rendered_text = render_code_node(code_node)

    format_result = style_format.auto_format(rendered_text, filename=filepath)
    if not format_result.did_succeed:
        raise RuntimeError("Style-formatting failed: filename = {filename}\n"
                           "---- stderr ----\n"
                           "{stderr}:".format(
                               filename=format_result.filename,
                               stderr=format_result.error_message))

    web_idl.file_io.write_to_file_if_changed(
        filepath, format_result.contents.encode('utf-8'))