File: ts_definition_generator.py

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (355 lines) | stat: -rw-r--r-- 13,184 bytes parent folder | download
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# Copyright 2023 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Generator that produces a definition file for typescript.

Note: This is a work in progress, and generated definitions may need tweaking.
      See bug: crbug.com/1203307
This script is currently run manually.
"""

import datetime
import os
import subprocess
import tempfile

from code_util import Code
from js_util import JsUtil
from model import *
from schema_util import *


class TsDefinitionGenerator(object):

  def Generate(self, namespace):
    return _Generator(namespace).Generate()


class _Generator(object):

  def __init__(self, namespace: Namespace):
    self._namespace = namespace
    self._events_required = False
    self._js_util = JsUtil()

  def Generate(self):
    main_code = Code()
    body_code = Code()
    # Generate the definition first to determine if an import is required.
    self._AppendDefinitionBody(body_code)
    # Create copyright header.
    self._AppendChromiumHeader(main_code)
    # Create file overview.
    self._AppendFileOverview(main_code)
    # Create import area.
    self._AppendImportArea(main_code)
    # Create namespaces.
    namespaces_to_close = self._OpenNamespaces(main_code)
    # Append definitions.
    main_code.Concat(body_code)
    # Close namespaces.
    self._CloseNamespaces(main_code, namespaces_to_close)
    # Cleanup a little.
    main_code.TrimTrailingNewlines()
    # If events are needed, add the import.
    if self._events_required:
      main_code.Substitute(
          {"imports": "import {ChromeEvent} from './chrome_event.js';"}
      )
    else:
      main_code.Substitute({"imports": ""})
    main_code = self._ClangFormat(main_code)
    # Final new line.
    main_code.Append()
    return main_code

  def _AppendChromiumHeader(self, c: Code):
    c.Append(f"""// Copyright {datetime.date.today().year} The Chromium Authors
    // Use of this source code is governed by a BSD-style license that can be
    // found in the LICENSE file.""")
    c.Append()

  def _AppendFileOverview(self, c: Code):
    c.Append("""/**
     * @fileoverview Definitions for chrome.{name} API
     * Generated from: {file}
     * run `tools/json_schema_compiler/compiler.py {file} -g ts_definitions` to
     * regenerate.
     */""".format(name=self._namespace.name, file=self._namespace.source_file))
    c.Append()

  def _AppendImportArea(self, c: Code):
    # Assume these declarations will be placed in tools/typescript/definitions.
    c.Append("%(imports)s")
    c.Append()

  def _OpenNamespaces(self, c: Code):
    namespaces_opened = 2
    declare_or_export = "declare"
    # If adding an import the definition file becomes a module.
    # If that happens we must declare something global specifically.
    # Otherwise the definition file is considered global by default.
    if self._events_required:
      c.Sblock("declare global {")
      namespaces_opened += 1
      c.Append()
      declare_or_export = "export"
    c.Sblock(f"{declare_or_export} namespace chrome {{")
    c.Append()
    c.Sblock(f"export namespace {self._namespace.name} {{")
    c.Append()
    return namespaces_opened

  def _AppendDefinitionBody(self, c: Code):
    # Add namespace level properties.
    for prop in self._namespace.properties.values():
      type_name = self._ExtractType(prop.type_)
      # If the ref type has additional properties, do a namespace merge.
      prop_type: Type = prop.type_
      if (
          len(prop_type.properties) > 0
          and prop_type.property_type == PropertyType.REF
      ):
        type_name = self._AppendInterfaceForProperty(c, prop, type_name)
      c.Append(f"export const {prop.name}: {type_name};")
      c.Append()
    # Add types.
    for type in self._namespace.types.values():
      self._AppendType(c, type)
    # Add namespace level functions.
    for func in self._namespace.functions.values():
      self._AppendFunction(c, func)
    # Add Events.
    for event in self._namespace.events.values():
      event_type = self._ExtractFunctionType(event)
      c.Append(f"export const {event.name}: ChromeEvent<{event_type}>;")
      c.Append()
      self._events_required = True

  def _CloseNamespaces(self, c: Code, to_close: int):
    for i in range(to_close):
      c.Eblock("}")

  def _AppendFunction(self, c: Code, func):
    params = self._ExtractFunctionParams(func.params)
    ret_type = self._ExtractFunctionReturnType(func)
    c.Append(f"export function {func.name}({params}): {ret_type};")
    c.Append()

  # This appends an local only interface to allow for additional
  # properties on an already defined type.
  def _AppendInterfaceForProperty(
      self, c: Code, prop: Property, prop_type_name
  ):
    if prop.deprecated:
      return
    prop_type = prop.type_
    interface_name = f"{prop.name}_{prop_type_name}"
    # The names of these interfaces are not in pascal case.
    # They are unexported though which results in the correct behavior.
    c.Append("// eslint-disable-next-line @typescript-eslint/naming-convention")
    c.Sblock(f"interface {interface_name} extends {prop_type_name}{{")
    for prop in prop_type.properties.values():
      type_name = self._ExtractType(prop.type_)
      c.Append(f"readonly {prop.name}: {type_name};")
    # Add interface functions.
    for func in prop_type.functions.values():
      self._AppendFunction(c, func)
    # Add Events.
    for event in prop_type.events.values():
      event_type = self._ExtractFunctionType(event)
      c.Append(f"readonly {event.name}: ChromeEvent<{event_type}>;")
      self._events_required = True
    c.Eblock("}")
    return interface_name

  def _AppendType(self, c: Code, type: Type):
    if type.property_type is PropertyType.ENUM:
      self._AppendEnum(c, type)
    elif type.property_type is PropertyType.OBJECT:
      self._AppendInterface(c, type)
    elif type.property_type.is_fundamental:
      # Type alias
      c.Append(f"export type {type.name} = {type.property_type.name};")
      c.Append()
    else:
      # Adding this for things we may not have accounted for here.
      c.Append(
          f"// TODO({os.getlogin()}) -- {type.name}: {type.property_type.name}"
      )

  def _AppendInterface(self, c: Code, interface: Type):
    c.Sblock(f"export interface {interface.name} {{")
    # Add interface properties.
    for property in interface.properties.values():
      c.Append(self._ExtractPropertyDefinition(property))
    # Add interface functions.
    func: Function
    for func in interface.functions.values():
      c.Append(f"{func.name}{self._ExtractFunctionType(func, ':')};")
    # Add interface events.
    for evnt in interface.events.values():
      event_type = self._ExtractFunctionType(evnt)
      c.Append(f"{evnt.name}: ChromeEvent<{event_type}>;")
      self._events_required = True
    c.Eblock("}")
    c.Append()

  def _AppendEnum(self, c: Code, enum):
    c.Sblock(f"export enum {enum.name} {{")
    for v in enum.enum_values:
      c.Append(f"{self._js_util.GetPropertyName(v.name)} = '{v.name}',")
    c.Eblock("}")
    c.Append()

  def _AppendClass(self, c: Code, class_type: Type):
    c.Sblock(f"export class {class_type.name} {{")
    for property in class_type.properties.values():
      c.Append(self._ExtractPropertyDefinition(property))
    # Add class functions.
    func: Function
    for func in class_type.functions.values():
      c.Append(f"{func.name}{self._ExtractFunctionType(func, ':')};")
    # Add class events.
    for evnt in class_type.events.values():
      event_type = self._ExtractFunctionType(evnt)
      c.Append(f"{evnt.name}: ChromeEvent<{event_type}>;")
      self._events_required = True
    c.Eblock("}")

  def _ExtractFunctionReturnType(self, func: Function):
    ret_type = "void"
    if func.returns is not None:
      ret_type = self._ExtractType(func.returns)
    elif func.returns_async is not None:
      ret_type = f"Promise<{self._ExtractPromiseType(func.returns_async)}>"
    return ret_type

  # Extracts the code required to define a type.
  # Uses recursion to get types within types.
  def _ExtractType(self, type: Type):
    if type is None:
      return "void"
    if type.property_type in (PropertyType.INTEGER, PropertyType.DOUBLE):
      return "number"
    elif type.property_type is PropertyType.OBJECT:
      return self._ExtractObjectDefinition(type)
    elif type.property_type is PropertyType.REF:
      return type.ref_type
    elif type.property_type is PropertyType.CHOICES:
      type_list = ""
      for i, choice in enumerate(type.choices):
        if i != 0:
          type_list += "|"
        type_list += self._ExtractType(choice)
      return type_list
    elif type.property_type is PropertyType.ARRAY:
      if type.item_type.property_type is PropertyType.OBJECT:
        return f"Array<{self._ExtractType(type.item_type)}>"
      elif type.item_type.property_type is PropertyType.CHOICES:
        return f"({self._ExtractType(type.item_type)})[]"
      else:
        return f"{self._ExtractType(type.item_type)}[]"
    elif type.property_type.is_fundamental:
      return type.property_type.name
    elif type.property_type is PropertyType.FUNCTION:
      return self._ExtractFunctionType(type.function)
    elif type.property_type is PropertyType.ANY:
      return "any"
    elif type.property_type is PropertyType.BINARY:
      return "ArrayBuffer"
    else:
      # Added for accounting for unknown objects.
      return f"unknown /*TODO({os.getlogin()})*/"

  def _ExtractPropertyDefinition(self, prop: Property, terminator=";"):
    q_mark = "?" if prop.optional else ""
    type_name = self._ExtractType(prop.type_)
    return f"{prop.name}{q_mark}: {type_name}{terminator}"

  # Extracts the function type as an arrow function.
  # The delimiter can be changed so this can be used for interface / object
  # members.
  def _ExtractFunctionType(self, func: Function, return_delim=" =>"):
    params = self._ExtractFunctionParams(func.params)
    ret_type = self._ExtractFunctionReturnType(func)
    return f"({params}){return_delim} {ret_type}"

  # Extracts an object definition.
  def _ExtractObjectDefinition(self, obj: Type):
    # If there are no specific properties on the object then we should expect
    # and object of random keys with specific values.
    if len(obj.properties) == 0:
      return "{[key:string]: %s}" % self._ExtractType(obj.additional_properties)

    ## Otherwise we will build a definition similar to an interface
    obj_code = Code()
    obj_code.Append("{")
    for property in obj.properties.values():
      obj_code.Append(self._ExtractPropertyDefinition(property, ","))
    func: Function
    for func in obj.functions.values():
      obj_code.Append(f"{func.name}{self._ExtractFunctionType(func, ':')};")
    obj_code.Append("}")
    for evnt in obj.events.values():
      event_type = self._ExtractFunctionType(evnt)
      obj_code.Append(f"{evnt.name}: ChromeEvent<{event_type}>;")
      self._events_required = True
    return obj_code.Render()

  # Extracts parameters from a function as a string representation.
  # Example = "p1: string, p2: number, p3: any".
  def _ExtractFunctionParams(self, params: list):
    param_str = ""
    required_index = -1
    for i, param in reversed(list(enumerate(params))):
      if not param.optional:
        required_index = i
        break
    for i, param in enumerate(params):
      q_mark = "?" if param.optional and not i < required_index else ""
      type_name = self._ExtractType(param.type_)
      # Typescript doesn't allow an optional before a required param.
      # In this case append | undefined to the parameter.
      if i < required_index and param.optional:
        type_name += "|undefined"
      param_str += f"{param.name}{q_mark}: {type_name}"
      if i < len(params) - 1:
        param_str += ", "
    return param_str

  # Extracts the type from a promise.
  def _ExtractPromiseType(self, async_return: ReturnsAsync):
    retval = "void"
    # Assume that there is at most only one param since functions can only
    # return one thing. This includes those that are async and use a promise to
    # return a value. It could also be 0 for void return type.
    assert len(async_return.params) <= 1
    for ret in async_return.params:
      retval = self._ExtractType(ret.type_)
    return retval

  def _ClangFormat(self, c: Code, level=0):
    # temp = tempfile.NamedTemporaryFile("w", encoding="utf-8", suffix=".js")
    # f_name = temp.name
    with tempfile.NamedTemporaryFile(
        "w", encoding="utf-8", suffix=".js", delete=False
    ) as f:
      f.write(c.Render())
      f_name = f.name
    path = self._GetChromiumClangFormatPath()
    cmd = f'clang-format --fallback-style=none --style=file:{path} "{f_name}"'
    p = subprocess.Popen(
        cmd, encoding="utf-8", shell=True, stdout=subprocess.PIPE
    )
    out = p.communicate()[0]
    out_code = Code()
    out_code.Append(out)
    os.remove(f_name)
    return out_code

  def _GetChromiumClangFormatPath(self):
    return os.path.abspath(
        os.path.join(os.path.dirname(__file__), "../../.clang-format")
    )