/
idlparser.py
441 lines (344 loc) · 11.7 KB
/
idlparser.py
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
#!/usr/bin/python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import re
import subprocess
import tempfile
from pegparser import *
# IDL grammar variants.
WEBIDL_SYNTAX = 0
WEBKIT_SYNTAX = 1
FREMONTCUT_SYNTAX = 2
class IDLParser(object):
"""IDLParser is a PEG based IDL files parser."""
def __init__(self, syntax=WEBIDL_SYNTAX):
"""Constructor.
Initializes the IDLParser by defining the grammar and initializing
a PEGParserinstance.
Args:
syntax -- supports either WEBIDL_SYNTAX (0) or WEBKIT_SYNTAX (1)
"""
self._syntax = syntax
self._pegparser = PegParser(self._idl_grammar(),
self._whitespace_grammar(),
strings_are_tokens=True)
def _idl_grammar(self):
"""Returns the PEG grammar for IDL parsing."""
# utilities:
def syntax_switch(w3c_syntax, webkit_syntax, fremontcut_syntax=None):
"""Returns w3c_syntax or web_syntax, depending on the current
configuration.
"""
if self._syntax == WEBIDL_SYNTAX:
return w3c_syntax
elif self._syntax == WEBKIT_SYNTAX:
return webkit_syntax
elif self._syntax == FREMONTCUT_SYNTAX:
if fremontcut_syntax is not None:
return fremontcut_syntax
return w3c_syntax
else:
raise RuntimeError('unsupported IDL syntax %s' % syntax)
# The following grammar is based on the Web IDL's LL(1) grammar
# (specified in: http://dev.w3.org/2006/webapi/WebIDL/#idl-grammar).
# It is adjusted to PEG grammar, as well as to also support
# WebKit IDL and FremontCut grammar.
###################### BEGIN GRAMMAR #####################
def Id():
return re.compile(r'[\w\_]+')
def _Definitions():
return MAYBE(MANY(_Definition))
def _Definition():
return syntax_switch(
# Web IDL:
OR(Module, Interface, ExceptionDef, TypeDef, ImplStmt,
ValueTypeDef, Const),
# WebKit:
OR(Module, Interface))
def Module():
return syntax_switch(
# Web IDL:
[MAYBE(ExtAttrs), 'module', Id, '{', _Definitions, '}',
MAYBE(';')],
# WebKit:
['module', MAYBE(ExtAttrs), Id, '{', _Definitions, '}',
MAYBE(';')],
# FremontCut:
[MAYBE(_Annotations), MAYBE(ExtAttrs), 'module', Id,
'{', _Definitions, '}', MAYBE(';')])
def Interface():
return syntax_switch(
# Web IDL:
[MAYBE(ExtAttrs), 'interface', Id, MAYBE(_ParentInterfaces),
MAYBE(['{', MAYBE(MANY(_Member)), '}']), ';'],
# WebKit:
[MAYBE(ExtAttrs), OR('interface', 'exception'), MAYBE(ExtAttrs), Id, MAYBE(_ParentInterfaces),
MAYBE(['{', MAYBE(MANY(_Member)), '}']), MAYBE(';')],
# FremontCut:
[MAYBE(_Annotations), MAYBE(ExtAttrs), 'interface',
Id, MAYBE(_ParentInterfaces), MAYBE(['{', MAYBE(MANY(_Member)),
'}']), ';'])
def _Member():
return syntax_switch(
# Web IDL:
OR(Const, Attribute, Operation, ExtAttrs),
# WebKit:
OR(Const, Attribute, Operation),
# FremontCut:
OR(Const, Attribute, Operation))
# Interface inheritance:
def _ParentInterfaces():
return [':', MANY(ParentInterface, separator=',')]
def ParentInterface():
return syntax_switch(
# Web IDL:
[InterfaceType],
# WebKit:
[InterfaceType],
# FremontCut:
[MAYBE(_Annotations), InterfaceType])
# TypeDef (Web IDL):
def TypeDef():
return ['typedef', Type, Id, ';']
# TypeDef (Old-school W3C IDLs)
def ValueTypeDef():
return ['valuetype', Id, Type, ';']
# Implements Statement (Web IDL):
def ImplStmt():
return [ImplStmtImplementor, 'implements', ImplStmtImplemented,
';']
def ImplStmtImplementor():
return ScopedName
def ImplStmtImplemented():
return ScopedName
# Constants:
def Const():
return syntax_switch(
# Web IDL:
[MAYBE(ExtAttrs), 'const', Type, Id, '=', ConstExpr, ';'],
# WebKit:
[MAYBE(ExtAttrs), 'const', Type, Id, '=', ConstExpr, ';'],
# FremontCut:
[MAYBE(_Annotations), MAYBE(ExtAttrs), 'const', Type, Id, '=',
ConstExpr, ';'])
def ConstExpr():
return OR(_BooleanLiteral,
_IntegerLiteral,
_FloatLiteral)
def _BooleanLiteral():
return re.compile(r'true|false')
def _IntegerLiteral():
return OR(re.compile(r'(0x)?[0-9ABCDEF]+'),
re.compile(r'[0-9]+'))
def _FloatLiteral():
return re.compile(r'[0-9]+\.[0-9]*')
# Attributes:
def Attribute():
return syntax_switch(
# Web IDL:
[MAYBE(ExtAttrs), MAYBE(Stringifier), MAYBE(ReadOnly),
'attribute', Type, Id, MAYBE(_AttrRaises), ';'],
# WebKit:
[
MAYBE(Stringifier),
MAYBE(ExtAttrs), MAYBE(Static), MAYBE(ReadOnly), 'attribute', MAYBE(ExtAttrs),
Type, Id, MAYBE(_AttrRaises), ';'],
# FremontCut:
[MAYBE(_Annotations), MAYBE(ExtAttrs),
MAYBE(_AttrGetterSetter), MAYBE(Stringifier), MAYBE(ReadOnly),
'attribute', Type, Id, MAYBE(_AttrRaises), ';'])
def _AttrRaises():
return syntax_switch(
# Web IDL:
MANY(OR(GetRaises, SetRaises)),
# WebKit:
MANY(OR(GetRaises, SetRaises, Raises), separator=','))
# Special fremontcut feature:
def _AttrGetterSetter():
return OR(AttrGetter, AttrSetter)
def AttrGetter():
return 'getter'
def AttrSetter():
return 'setter'
def ReadOnly():
return 'readonly'
def GetRaises():
return syntax_switch(
# Web IDL:
['getraises', '(', _ScopedNames, ')'],
# WebKit:
['getter', 'raises', '(', _ScopedNames, ')'])
def SetRaises():
return syntax_switch(
# Web IDL:
['setraises', '(', _ScopedNames, ')'],
# WebKit:
['setter', 'raises', '(', _ScopedNames, ')'])
# Operation:
def Operation():
return syntax_switch(
# Web IDL:
[MAYBE(ExtAttrs), MAYBE(Static), MAYBE(Stringifier), MAYBE(_Specials),
ReturnType, MAYBE(Id), '(', _Arguments, ')', MAYBE(Raises),
';'],
# WebKit:
[MAYBE(ExtAttrs), MAYBE(Static),
ReturnType, MAYBE(Id), '(', _Arguments, ')',
MAYBE(Raises), ';'],
# FremontCut:
[MAYBE(_Annotations), MAYBE(ExtAttrs), MAYBE(Static), MAYBE(Stringifier),
MAYBE(_Specials), ReturnType, MAYBE(Id), '(', _Arguments, ')',
MAYBE(Raises), ';'])
def Static():
return 'static'
def _Specials():
return MANY(Special)
def Special():
return re.compile(r'getter|setter|creator|deleter|caller')
def Stringifier():
return 'stringifier'
def Raises():
return ['raises', '(', _ScopedNames, ')']
# Operation arguments:
def _Arguments():
return MAYBE(MANY(Argument, ','))
def Argument():
return syntax_switch(
# Web IDL:
[MAYBE(ExtAttrs), MAYBE(Optional), MAYBE('in'),
MAYBE(Optional), Type, MAYBE(AnEllipsis), Id],
# WebKit:
[MAYBE(Optional), MAYBE('in'), MAYBE(Optional),
MAYBE(ExtAttrs), Type, Id])
def Optional():
return 'optional'
def AnEllipsis():
return '...'
# Exceptions (Web IDL).
def ExceptionDef():
return ['exception', Id, '{', MAYBE(MANY(_ExceptionMember)), '}',
';']
def _ExceptionMember():
return OR(Const, ExceptionField, ExtAttrs)
def ExceptionField():
return [Type, Id, ';']
# Types:
def Type():
return _Type
def ReturnType():
return OR(VoidType, _Type)
def InterfaceType():
return ScopedName
def ArrayModifiers():
return re.compile(r'(\[\])+')
def _Type():
return OR(
[OR(AnyType, ObjectType), MAYBE([ArrayModifiers, MAYBE(Nullable)])],
[_NullableNonArrayType(), MAYBE(ArrayModifiers), MAYBE(Nullable)])
def _NullableNonArrayType():
return [OR(_IntegerType, BooleanType, OctetType, FloatType,
DoubleType, SequenceType, ScopedName)]
def Nullable():
return '?'
def SequenceType():
return ['sequence', '<', Type, '>']
def AnyType():
return 'any'
def ObjectType():
return re.compile(r'(object|Object)\b') # both spellings.
def VoidType():
return 'void'
def _IntegerType():
return [MAYBE(Unsigned), OR(ByteType, IntType, LongLongType,
LongType, OctetType, ShortType)]
def Unsigned():
return 'unsigned'
def ShortType():
return 'short'
def LongLongType():
return ['long', 'long']
def LongType():
return 'long'
def IntType():
return 'int'
def ByteType():
return 'byte'
def OctetType():
return 'octet'
def BooleanType():
return 'boolean'
def FloatType():
return 'float'
def DoubleType():
return 'double'
def _ScopedNames():
return MANY(ScopedName, separator=',')
def ScopedName():
return re.compile(r'[\w\_\:\.\<\>]+')
# Extended Attributes:
def ExtAttrs():
return ['[', MAYBE(MANY(ExtAttr, ',')), ']']
def ExtAttr():
return [Id, MAYBE(OR(['=', ExtAttrValue], ExtAttrArgList))]
def ExtAttrValue():
return OR(ExtAttrFunctionValue, re.compile(r'[\w&0-9:\-\| ]+'))
def ExtAttrFunctionValue():
return [Id, ExtAttrArgList]
def ExtAttrArgList():
return ['(', MAYBE(MANY(Argument, ',')), ')']
# Annotations - used in the FremontCut IDL grammar:
def _Annotations():
return MANY(Annotation)
def Annotation():
return ['@', Id, MAYBE(_AnnotationBody)]
def _AnnotationBody():
return ['(', MAYBE(MANY(AnnotationArg, ',')), ')']
def AnnotationArg():
return [Id, MAYBE(['=', AnnotationArgValue])]
def AnnotationArgValue():
return re.compile(r'[\w&0-9:/\-\.]+')
###################### END GRAMMAR #####################
# Return the grammar's root rule:
return MANY(_Definition)
def _whitespace_grammar(self):
return OR(re.compile(r'\s+'),
re.compile(r'//.*'),
re.compile(r'#.*'),
re.compile(r'/\*.*?\*/', re.S))
def _pre_process(self, content, defines, includePaths):
"""Pre-processes the content using gcc.
WebKit IDLs require pre-processing by gcc. This is done by invoking
gcc in a sub-process and capturing the results.
Returns:
The result of running gcc on the content.
Args:
content -- text to process.
defines -- an array of pre-processor defines.
includePaths -- an array of path strings.
"""
# FIXME: Handle gcc not found, or any other processing errors
gcc = 'gcc'
cmd = [gcc, '-E', '-P', '-C', '-x', 'c++']
for define in defines:
cmd.append('-D%s' % define)
cmd.append('-')
pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(content, stderr) = pipe.communicate(content)
return content
def parse(self, content, defines=[], includePaths=[]):
"""Parse the give content string.
The WebKit IDL syntax also allows gcc pre-processing instructions.
Lists of defined variables and include paths can be provided.
Returns:
An abstract syntax tree (AST).
Args:
content -- text to parse.
defines -- an array of pre-processor defines.
includePaths -- an array of path strings used by the
gcc pre-processor.
"""
if self._syntax == WEBKIT_SYNTAX:
content = self._pre_process(content, defines, includePaths)
return self._pegparser.parse(content)