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
|
# Copyright 2015 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.
"""
Generator that produces an externs file for the Closure Compiler.
Note: This is a work in progress, and generated externs may require tweaking.
See https://developers.google.com/closure/compiler/docs/api-tutorial3#externs
"""
from code import Code
from model import *
from schema_util import *
import os
from datetime import datetime
LICENSE = ("""// Copyright %s 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.
""" % datetime.now().year)
class JsExternsGenerator(object):
def Generate(self, namespace):
return _Generator(namespace).Generate()
class _Generator(object):
def __init__(self, namespace):
self._namespace = namespace
def Generate(self):
"""Generates a Code object with the schema for the entire namespace.
"""
c = Code()
(c.Append(LICENSE)
.Append()
.Append('/** @fileoverview Externs generated from namespace: %s */' %
self._namespace.name)
.Append())
c.Cblock(self._GenerateNamespaceObject())
for js_type in self._namespace.types.values():
c.Cblock(self._GenerateType(js_type))
for function in self._namespace.functions.values():
c.Cblock(self._GenerateFunction(function))
for event in self._namespace.events.values():
c.Cblock(self._GenerateEvent(event))
return c
def _GenerateType(self, js_type):
"""Given a Type object, returns the Code for this type's definition.
"""
c = Code()
if js_type.property_type is PropertyType.ENUM:
c.Concat(self._GenerateEnumJsDoc(js_type))
else:
c.Concat(self._GenerateTypeJsDoc(js_type))
return c
def _GenerateEnumJsDoc(self, js_type):
""" Given an Enum Type object, returns the Code for the enum's definition.
"""
c = Code()
c.Append('/**').Append(' * @enum {string}').Append(' */')
c.Append('chrome.%s.%s = {' % (self._namespace.name, js_type.name))
c.Append('\n'.join(
[" %s: '%s'," % (v.name, v.name) for v in js_type.enum_values]))
c.Append('};')
return c
def _IsTypeConstructor(self, js_type):
"""Returns true if the given type should be a @constructor. If this returns
false, the type is a typedef.
"""
return any(prop.type_.property_type is PropertyType.FUNCTION
for prop in js_type.properties.values())
def _GenerateTypeJsDoc(self, js_type):
"""Generates the documentation for a type as a Code.
Returns an empty code object if the object has no documentation.
"""
c = Code()
c.Append('/**')
if js_type.description:
for line in js_type.description.splitlines():
c.Comment(line, comment_prefix = ' * ')
is_constructor = self._IsTypeConstructor(js_type)
if is_constructor:
c.Comment('@constructor', comment_prefix = ' * ', wrap_indent=4)
else:
c.Concat(self._GenerateTypedef(js_type.properties))
c.Append(' */')
var = 'var ' + js_type.simple_name
if is_constructor: var += ' = function() {}'
var += ';'
c.Append(var)
return c
def _GenerateTypedef(self, properties):
"""Given an OrderedDict of properties, returns a Code containing a @typedef.
"""
if not properties: return Code()
lines = []
lines.append('@typedef {{')
for field, prop in properties.items():
js_type = self._TypeToJsType(prop.type_)
if prop.optional:
js_type = '(%s|undefined)' % js_type
lines.append(' %s: %s,' % (field, js_type))
# Remove last trailing comma.
# TODO(devlin): This will be unneeded, if when
# https://github.com/google/closure-compiler/issues/796 is fixed.
lines[-1] = lines[-1][:-1]
lines.append('}}')
# TODO(tbreisacher): Add '@see <link to documentation>'.
c = Code()
c.Append('\n'.join([' * ' + line for line in lines]))
return c
def _GenerateFunctionJsDoc(self, function):
"""Generates the documentation for a function as a Code.
Returns an empty code object if the object has no documentation.
"""
c = Code()
c.Append('/**')
lines = []
if function.description:
for line in function.description.splitlines():
c.Comment(line, comment_prefix=' * ')
for param in function.params:
js_type = self._TypeToJsType(param.type_)
if param.optional:
js_type += '='
lines.append('@param {%s} %s %s' % (js_type,
param.name,
param.description or ''))
if function.callback:
lines.append('@param {%s} %s %s' % (
self._FunctionToJsFunction(function.callback),
function.callback.name,
function.callback.description or ''))
if function.returns:
lines.append('@return {%s} %s' % (self._TypeToJsType(function.returns),
function.returns.description or ''))
if function.deprecated:
lines.append('@deprecated %s' % function.deprecated)
for line in lines:
c.Comment(line, comment_prefix=' * ', wrap_indent=4);
c.Append(' */')
return c
def _FunctionToJsFunction(self, function):
"""Converts a model.Function to a JS type (i.e., function([params])...)"""
params = ', '.join(
[self._TypeToJsType(param.type_) for param in function.params])
return_type = (
self._TypeToJsType(function.returns) if function.returns else 'void')
optional = '=' if function.optional else ''
return 'function(%s):%s%s' % (params, return_type, optional)
def _TypeToJsType(self, js_type):
"""Converts a model.Type to a JS type (number, Array, etc.)"""
if js_type.property_type in (PropertyType.INTEGER, PropertyType.DOUBLE):
return 'number'
elif js_type.property_type is PropertyType.OBJECT:
return 'Object'
elif js_type.property_type is PropertyType.ARRAY:
return '!Array<%s>' % self._TypeToJsType(js_type.item_type)
elif js_type.property_type is PropertyType.REF:
ref_type = js_type.ref_type
# Enums are defined as chrome.fooAPI.MyEnum, but types are defined simply
# as MyType.
if self._namespace.types[ref_type].property_type is PropertyType.ENUM:
ref_type = '!chrome.%s.%s' % (self._namespace.name, ref_type)
return ref_type
elif js_type.property_type is PropertyType.CHOICES:
return '(%s)' % '|'.join(
[self._TypeToJsType(choice) for choice in js_type.choices])
elif js_type.property_type is PropertyType.FUNCTION:
return self._FunctionToJsFunction(js_type.function)
elif js_type.property_type is PropertyType.ANY:
return '*'
elif js_type.property_type.is_fundamental:
return js_type.property_type.name
else:
return '?' # TODO(tbreisacher): Make this more specific.
def _GenerateFunction(self, function):
"""Generates the code representing a function, including its documentation.
For example:
/**
* @param {string} title The new title.
*/
chrome.window.setTitle = function(title) {};
"""
c = Code()
params = self._GenerateFunctionParams(function)
(c.Concat(self._GenerateFunctionJsDoc(function))
.Append('chrome.%s.%s = function(%s) {};' % (self._namespace.name,
function.name,
params))
)
return c
def _GenerateEvent(self, event):
"""Generates the code representing an event.
For example:
/** @type {!ChromeEvent} */
chrome.bookmarks.onChildrenReordered;
"""
c = Code()
(c.Append('/** @type {!ChromeEvent} */')
.Append('chrome.%s.%s;' % (self._namespace.name, event.name)))
return c
def _GenerateNamespaceObject(self):
"""Generates the code creating namespace object.
For example:
/**
* @const
*/
chrome.bookmarks = {};
"""
c = Code()
(c.Append("""/**
* @const
*/""")
.Append('chrome.%s = {};' % self._namespace.name))
return c
def _GenerateFunctionParams(self, function):
params = function.params[:]
if function.callback:
params.append(function.callback)
return ', '.join(param.name for param in params)
|