2 # Copyright (c) 2013 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """ Parser for PPAPI IDL """
11 # The parser is uses the PLY yacc library to build a set of parsing rules based
14 # WebIDL, and WebIDL grammar can be found at:
15 # http://heycam.github.io/webidl/
16 # PLY can be found at:
17 # http://www.dabeaz.com/ply/
19 # The parser generates a tree by recursively matching sets of items against
20 # defined patterns. When a match is made, that set of items is reduced
21 # to a new item. The new item can provide a match for parent patterns.
22 # In this way an AST is built (reduced) depth first.
26 # Disable check for line length and Member as Function due to how grammar rules
27 # are defined with PLY
29 # pylint: disable=R0201
30 # pylint: disable=C0301
36 from idl_lexer
import IDLLexer
37 from idl_node
import IDLAttribute
, IDLNode
40 # Try to load the ply module, if not, then assume it is in the third_party
44 # Disable lint check which fails to find the ply module.
45 # pylint: disable=F0401
49 module_path
, module_name
= os
.path
.split(__file__
)
50 third_party
= os
.path
.join(module_path
, os
.par
, os
.par
, 'third_party')
51 sys
.path
.append(third_party
)
52 # pylint: disable=F0401
59 # Maps the standard error formula into a more friendly error message.
62 'Unexpected ")" after "(".' : 'Empty argument list.',
63 'Unexpected ")" after ",".' : 'Missing argument.',
64 'Unexpected "}" after ",".' : 'Trailing comma in block.',
65 'Unexpected "}" after "{".' : 'Unexpected empty block.',
66 'Unexpected comment after "}".' : 'Unexpected trailing comment.',
67 'Unexpected "{" after keyword "enum".' : 'Enum missing name.',
68 'Unexpected "{" after keyword "struct".' : 'Struct missing name.',
69 'Unexpected "{" after keyword "interface".' : 'Interface missing name.',
74 """Convert to strict boolean type."""
80 def ListFromConcat(*items
):
81 """Generate list by concatenating inputs"""
86 if type(item
) is not type([]):
93 def ExpandProduction(p
):
95 return '[' + ', '.join([ExpandProduction(x
) for x
in p
]) + ']'
96 if type(p
) == IDLNode
:
97 return 'Node:' + str(p
)
98 if type(p
) == IDLAttribute
:
99 return 'Attr:' + str(p
)
102 return '%s:%s' % (p
.__class
__.__name
__, str(p
))
106 # Generate a string which has the type and value of the token.
108 def TokenTypeName(t
):
109 if t
.type == 'SYMBOL':
110 return 'symbol %s' % t
.value
111 if t
.type in ['HEX', 'INT', 'OCT', 'FLOAT']:
112 return 'value %s' % t
.value
113 if t
.type == 'string' :
114 return 'string "%s"' % t
.value
115 if t
.type == 'COMMENT' :
117 if t
.type == t
.value
:
118 return '"%s"' % t
.value
121 if t
.type == 'identifier':
122 return 'identifier "%s"' % t
.value
123 return 'keyword "%s"' % t
.value
129 # The Parser inherits the from the Lexer to provide PLY with the tokenizing
130 # definitions. Parsing patterns are encoded as functions where p_<name> is
131 # is called any time a patern matching the function documentation is found.
132 # Paterns are expressed in the form of:
133 # """ <new item> : <item> ....
136 # Where new item is the result of a match against one or more sets of items
137 # separated by the "|".
139 # The function is called with an object 'p' where p[0] is the output object
140 # and p[n] is the set of inputs for positive values of 'n'. Len(p) can be
141 # used to distinguish between multiple item sets in the pattern.
143 # For more details on parsing refer to the PLY documentation at
144 # http://www.dabeaz.com/ply/
146 # The parser is based on the WebIDL standard. See:
147 # http://heycam.github.io/webidl/#idl-grammar
149 # The various productions are annotated so that the WHOLE number greater than
150 # zero in the comment denotes the matching WebIDL grammar definition.
152 # Productions with a fractional component in the comment denote additions to
153 # the WebIDL spec, such as comments.
157 class IDLParser(object):
159 # We force all input files to start with two comments. The first comment is a
160 # Copyright notice followed by a file comment and finally by file level
163 # [0] Insert a TOP definition for Copyright and Comments
165 """Top : COMMENT COMMENT Definitions"""
166 Copyright
= self
.BuildComment('Copyright', p
, 1)
167 Filedoc
= self
.BuildComment('Comment', p
, 2)
168 p
[0] = ListFromConcat(Copyright
, Filedoc
, p
[3])
170 # [0.1] Add support for Multiple COMMENTS
171 def p_Comments(self
, p
):
172 """Comments : CommentsRest"""
176 # [0.2] Produce a COMMENT and aggregate sibling comments
177 def p_CommentsRest(self
, p
):
178 """CommentsRest : COMMENT CommentsRest
181 p
[0] = ListFromConcat(self
.BuildComment('Comment', p
, 1), p
[2])
185 #The parser is based on the WebIDL standard. See:
186 # http://heycam.github.io/webidl/#idl-grammar
189 def p_Definitions(self
, p
):
190 """Definitions : ExtendedAttributeList Definition Definitions
193 p
[2].AddChildren(p
[1])
194 p
[0] = ListFromConcat(p
[2], p
[3])
197 def p_Definition(self
, p
):
198 """Definition : CallbackOrInterface
204 | ImplementsStatement"""
207 # [2.1] Error recovery for definition
208 def p_DefinitionError(self
, p
):
209 """Definition : error ';'"""
210 p
[0] = self
.BuildError(p
, 'Definition')
213 def p_CallbackOrInterface(self
, p
):
214 """CallbackOrInterface : CALLBACK CallbackRestOrInterface
222 def p_CallbackRestOrInterface(self
, p
):
223 """CallbackRestOrInterface : CallbackRest
228 def p_Interface(self
, p
):
229 """Interface : INTERFACE identifier Inheritance '{' InterfaceMembers '}' ';'"""
230 p
[0] = self
.BuildNamed('Interface', p
, 2, ListFromConcat(p
[3], p
[5]))
233 def p_Partial(self
, p
):
234 """Partial : PARTIAL PartialDefinition"""
235 p
[2].AddChildren(self
.BuildTrue('Partial'))
238 # [6.1] Error recovery for Partial
239 def p_PartialError(self
, p
):
240 """Partial : PARTIAL error"""
241 p
[0] = self
.BuildError(p
, 'Partial')
244 def p_PartialDefinition(self
, p
):
245 """PartialDefinition : PartialDictionary
246 | PartialInterface"""
250 def p_PartialInterface(self
, p
):
251 """PartialInterface : INTERFACE identifier '{' InterfaceMembers '}' ';'"""
252 p
[0] = self
.BuildNamed('Interface', p
, 2, p
[4])
255 def p_InterfaceMembers(self
, p
):
256 """InterfaceMembers : ExtendedAttributeList InterfaceMember InterfaceMembers
259 p
[2].AddChildren(p
[1])
260 p
[0] = ListFromConcat(p
[2], p
[3])
263 def p_InterfaceMember(self
, p
):
264 """InterfaceMember : Const
265 | AttributeOrOperationOrIterator"""
269 def p_Dictionary(self
, p
):
270 """Dictionary : DICTIONARY identifier Inheritance '{' DictionaryMembers '}' ';'"""
271 p
[0] = self
.BuildNamed('Dictionary', p
, 2, ListFromConcat(p
[3], p
[5]))
273 # [11.1] Error recovery for regular Dictionary
274 def p_DictionaryError(self
, p
):
275 """Dictionary : DICTIONARY error ';'"""
276 p
[0] = self
.BuildError(p
, 'Dictionary')
279 def p_DictionaryMembers(self
, p
):
280 """DictionaryMembers : ExtendedAttributeList DictionaryMember DictionaryMembers
283 p
[2].AddChildren(p
[1])
284 p
[0] = ListFromConcat(p
[2], p
[3])
287 def p_DictionaryMember(self
, p
):
288 """DictionaryMember : Type identifier Default ';'"""
289 p
[0] = self
.BuildNamed('Key', p
, 2, ListFromConcat(p
[1], p
[3]))
292 def p_PartialDictionary(self
, p
):
293 """PartialDictionary : DICTIONARY identifier '{' DictionaryMembers '}' ';'"""
294 partial
= self
.BuildTrue('Partial')
295 p
[0] = self
.BuildNamed('Dictionary', p
, 2, ListFromConcat(p
[4], partial
))
297 # [14.1] Error recovery for Partial Dictionary
298 def p_PartialDictionaryError(self
, p
):
299 """PartialDictionary : DICTIONARY error ';'"""
300 p
[0] = self
.BuildError(p
, 'PartialDictionary')
303 def p_Default(self
, p
):
304 """Default : '=' DefaultValue
307 p
[0] = self
.BuildProduction('Default', p
, 2, p
[2])
310 def p_DefaultValue(self
, p
):
311 """DefaultValue : ConstValue
313 if type(p
[1]) == str:
314 p
[0] = ListFromConcat(self
.BuildAttribute('TYPE', 'DOMString'),
315 self
.BuildAttribute('NAME', p
[1]))
320 def p_Exception(self
, p
):
321 """Exception : EXCEPTION identifier Inheritance '{' ExceptionMembers '}' ';'"""
322 p
[0] = self
.BuildNamed('Exception', p
, 2, ListFromConcat(p
[3], p
[5]))
325 def p_ExceptionMembers(self
, p
):
326 """ExceptionMembers : ExtendedAttributeList ExceptionMember ExceptionMembers
329 p
[2].AddChildren(p
[1])
330 p
[0] = ListFromConcat(p
[2], p
[3])
332 # [18.1] Error recovery for ExceptionMembers
333 def p_ExceptionMembersError(self
, p
):
334 """ExceptionMembers : error"""
335 p
[0] = self
.BuildError(p
, 'ExceptionMembers')
338 def p_Inheritance(self
, p
):
339 """Inheritance : ':' identifier
342 p
[0] = self
.BuildNamed('Inherit', p
, 2)
346 """Enum : ENUM identifier '{' EnumValueList '}' ';'"""
347 p
[0] = self
.BuildNamed('Enum', p
, 2, p
[4])
349 # [20.1] Error recovery for Enums
350 def p_EnumError(self
, p
):
351 """Enum : ENUM error ';'"""
352 p
[0] = self
.BuildError(p
, 'Enum')
355 def p_EnumValueList(self
, p
):
356 """EnumValueList : ExtendedAttributeList string EnumValueListComma"""
357 enum
= self
.BuildNamed('EnumItem', p
, 2, p
[1])
358 p
[0] = ListFromConcat(enum
, p
[3])
361 def p_EnumValueListComma(self
, p
):
362 """EnumValueListComma : ',' EnumValueListString
368 def p_EnumValueListString(self
, p
):
369 """EnumValueListString : ExtendedAttributeList string EnumValueListComma
372 enum
= self
.BuildNamed('EnumItem', p
, 2, p
[1])
373 p
[0] = ListFromConcat(enum
, p
[3])
376 def p_CallbackRest(self
, p
):
377 """CallbackRest : identifier '=' ReturnType '(' ArgumentList ')' ';'"""
378 arguments
= self
.BuildProduction('Arguments', p
, 4, p
[5])
379 p
[0] = self
.BuildNamed('Callback', p
, 1, ListFromConcat(p
[3], arguments
))
382 def p_Typedef(self
, p
):
383 """Typedef : TYPEDEF ExtendedAttributeListNoComments Type identifier ';'"""
384 p
[0] = self
.BuildNamed('Typedef', p
, 4, ListFromConcat(p
[2], p
[3]))
386 # [25.1] Error recovery for Typedefs
387 def p_TypedefError(self
, p
):
388 """Typedef : TYPEDEF error ';'"""
389 p
[0] = self
.BuildError(p
, 'Typedef')
392 def p_ImplementsStatement(self
, p
):
393 """ImplementsStatement : identifier IMPLEMENTS identifier ';'"""
394 name
= self
.BuildAttribute('REFERENCE', p
[3])
395 p
[0] = self
.BuildNamed('Implements', p
, 1, name
)
398 def p_Const(self
, p
):
399 """Const : CONST ConstType identifier '=' ConstValue ';'"""
400 value
= self
.BuildProduction('Value', p
, 5, p
[5])
401 p
[0] = self
.BuildNamed('Const', p
, 3, ListFromConcat(p
[2], value
))
404 def p_ConstValue(self
, p
):
405 """ConstValue : BooleanLiteral
409 if type(p
[1]) == str:
410 p
[0] = ListFromConcat(self
.BuildAttribute('TYPE', 'integer'),
411 self
.BuildAttribute('NAME', p
[1]))
415 # [28.1] Add definition for NULL
418 p
[0] = ListFromConcat(self
.BuildAttribute('TYPE', 'NULL'),
419 self
.BuildAttribute('NAME', 'NULL'))
422 def p_BooleanLiteral(self
, p
):
423 """BooleanLiteral : TRUE
425 value
= self
.BuildAttribute('VALUE', Boolean(p
[1] == 'true'))
426 p
[0] = ListFromConcat(self
.BuildAttribute('TYPE', 'boolean'), value
)
429 def p_FloatLiteral(self
, p
):
430 """FloatLiteral : float
438 p
[0] = ListFromConcat(self
.BuildAttribute('TYPE', 'float'),
439 self
.BuildAttribute('VALUE', val
))
441 # [31] Removed unsupported: Serializer
442 def p_AttributeOrOperationOrIterator(self
, p
):
443 """AttributeOrOperationOrIterator : Stringifier
446 | OperationOrIterator"""
449 # [32-37] NOT IMPLEMENTED (Serializer)
452 def p_Stringifier(self
, p
):
453 """Stringifier : STRINGIFIER StringifierRest"""
454 p
[0] = self
.BuildProduction('Stringifier', p
, 1, p
[2])
457 def p_StringifierRest(self
, p
):
458 """StringifierRest : AttributeRest
459 | ReturnType OperationRest
462 p
[2].AddChildren(p
[1])
468 def p_StaticMember(self
, p
):
469 """StaticMember : STATIC StaticMemberRest"""
470 p
[2].AddChildren(self
.BuildTrue('STATIC'))
474 def p_StaticMemberRest(self
, p
):
475 """StaticMemberRest : AttributeRest
476 | ReturnType OperationRest"""
480 p
[2].AddChildren(p
[1])
484 def p_Attribute(self
, p
):
485 """Attribute : Inherit AttributeRest"""
486 p
[2].AddChildren(ListFromConcat(p
[1]))
490 def p_AttributeRest(self
, p
):
491 """AttributeRest : ReadOnly ATTRIBUTE Type identifier ';'"""
492 p
[0] = self
.BuildNamed('Attribute', p
, 4,
493 ListFromConcat(p
[1], p
[3]))
496 def p_Inherit(self
, p
):
500 p
[0] = self
.BuildTrue('INHERIT')
503 def p_ReadOnly(self
, p
):
504 """ReadOnly : READONLY
507 p
[0] = self
.BuildTrue('READONLY')
510 def p_OperationOrIterator(self
, p
):
511 """OperationOrIterator : ReturnType OperationOrIteratorRest
512 | SpecialOperation"""
514 p
[2].AddChildren(p
[1])
520 def p_SpecialOperation(self
, p
):
521 """SpecialOperation : Special Specials ReturnType OperationRest"""
522 p
[4].AddChildren(ListFromConcat(p
[1], p
[2], p
[3]))
526 def p_Specials(self
, p
):
527 """Specials : Special Specials
530 p
[0] = ListFromConcat(p
[1], p
[2])
533 def p_Special(self
, p
):
539 p
[0] = self
.BuildTrue(p
[1].upper())
541 # [50] Removed unsupported: IteratorRest
542 def p_OperationOrIteratorRest(self
, p
):
543 """OperationOrIteratorRest : OperationRest"""
546 # [51-53] NOT IMPLEMENTED (IteratorRest)
549 def p_OperationRest(self
, p
):
550 """OperationRest : OptionalIdentifier '(' ArgumentList ')' ';'"""
551 arguments
= self
.BuildProduction('Arguments', p
, 2, p
[3])
552 p
[0] = self
.BuildNamed('Operation', p
, 1, arguments
)
555 def p_OptionalIdentifier(self
, p
):
556 """OptionalIdentifier : identifier
564 def p_ArgumentList(self
, p
):
565 """ArgumentList : Argument Arguments
568 p
[0] = ListFromConcat(p
[1], p
[2])
570 # [56.1] ArgumentList error recovery
571 def p_ArgumentListError(self
, p
):
572 """ArgumentList : error """
573 p
[0] = self
.BuildError(p
, 'ArgumentList')
576 def p_Arguments(self
, p
):
577 """Arguments : ',' Argument Arguments
580 p
[0] = ListFromConcat(p
[2], p
[3])
583 def p_Argument(self
, p
):
584 """Argument : ExtendedAttributeList OptionalOrRequiredArgument"""
585 p
[2].AddChildren(p
[1])
589 def p_OptionalOrRequiredArgument(self
, p
):
590 """OptionalOrRequiredArgument : OPTIONAL Type ArgumentName Default
591 | Type Ellipsis ArgumentName"""
593 arg
= self
.BuildNamed('Argument', p
, 3, ListFromConcat(p
[2], p
[4]))
594 arg
.AddChildren(self
.BuildTrue('OPTIONAL'))
596 arg
= self
.BuildNamed('Argument', p
, 3, ListFromConcat(p
[1], p
[2]))
600 def p_ArgumentName(self
, p
):
601 """ArgumentName : ArgumentNameKeyword
606 def p_Ellipsis(self
, p
):
607 """Ellipsis : ELLIPSIS
610 p
[0] = self
.BuildNamed('Argument', p
, 1)
611 p
[0].AddChildren(self
.BuildTrue('ELLIPSIS'))
614 def p_ExceptionMember(self
, p
):
615 """ExceptionMember : Const
620 def p_ExceptionField(self
, p
):
621 """ExceptionField : Type identifier ';'"""
622 p
[0] = self
.BuildNamed('ExceptionField', p
, 2, p
[1])
624 # [63.1] Error recovery for ExceptionMembers
625 def p_ExceptionFieldError(self
, p
):
626 """ExceptionField : error"""
627 p
[0] = self
.BuildError(p
, 'ExceptionField')
629 # [64] No comment version for mid statement attributes.
630 def p_ExtendedAttributeListNoComments(self
, p
):
631 """ExtendedAttributeListNoComments : '[' ExtendedAttribute ExtendedAttributes ']'
634 items
= ListFromConcat(p
[2], p
[3])
635 p
[0] = self
.BuildProduction('ExtAttributes', p
, 1, items
)
637 # [64.1] Add optional comment field for start of statements.
638 def p_ExtendedAttributeList(self
, p
):
639 """ExtendedAttributeList : Comments '[' ExtendedAttribute ExtendedAttributes ']'
642 items
= ListFromConcat(p
[3], p
[4])
643 attribs
= self
.BuildProduction('ExtAttributes', p
, 2, items
)
644 p
[0] = ListFromConcat(p
[1], attribs
)
649 def p_ExtendedAttributes(self
, p
):
650 """ExtendedAttributes : ',' ExtendedAttribute ExtendedAttributes
653 p
[0] = ListFromConcat(p
[2], p
[3])
657 # [ identifier = identifier ]
658 # [ identifier ( ArgumentList )]
659 # [ identifier = identifier ( ArgumentList )]
660 # [66] map directly to [91-93, 95]
661 # [67-69, 71] are unsupported
662 def p_ExtendedAttribute(self
, p
):
663 """ExtendedAttribute : ExtendedAttributeNoArgs
664 | ExtendedAttributeArgList
665 | ExtendedAttributeIdent
666 | ExtendedAttributeNamedArgList"""
670 def p_ArgumentNameKeyword(self
, p
):
671 """ArgumentNameKeyword : ATTRIBUTE
695 | UnionType TypeSuffix"""
697 p
[0] = self
.BuildProduction('Type', p
, 1, p
[1])
699 p
[0] = self
.BuildProduction('Type', p
, 1, ListFromConcat(p
[1], p
[2]))
702 def p_SingleType(self
, p
):
703 """SingleType : NonAnyType
704 | ANY TypeSuffixStartingWithArray"""
708 p
[0] = ListFromConcat(self
.BuildProduction('Any', p
, 1), p
[2])
711 def p_UnionType(self
, p
):
712 """UnionType : '(' UnionMemberType OR UnionMemberType UnionMemberTypes ')'"""
715 def p_UnionMemberType(self
, p
):
716 """UnionMemberType : NonAnyType
717 | UnionType TypeSuffix
718 | ANY '[' ']' TypeSuffix"""
720 def p_UnionMemberTypes(self
, p
):
721 """UnionMemberTypes : OR UnionMemberType UnionMemberTypes
724 # [77] Moved BYTESTRING, DOMSTRING, OBJECT, DATE, REGEXP to PrimitiveType
725 # Moving all built-in types into PrimitiveType makes it easier to
726 # differentiate between them and 'identifier', since p[1] would be a string in
728 def p_NonAnyType(self
, p
):
729 """NonAnyType : PrimitiveType TypeSuffix
730 | identifier TypeSuffix
731 | SEQUENCE '<' Type '>' Null"""
733 if type(p
[1]) == str:
734 typeref
= self
.BuildNamed('Typeref', p
, 1)
737 p
[0] = ListFromConcat(typeref
, p
[2])
740 p
[0] = self
.BuildProduction('Sequence', p
, 1, ListFromConcat(p
[3], p
[5]))
744 def p_ConstType(self
, p
):
745 """ConstType : PrimitiveType Null
747 if type(p
[1]) == str:
748 p
[0] = self
.BuildNamed('Typeref', p
, 1, p
[2])
750 p
[1].AddChildren(p
[2])
754 # [79] Added BYTESTRING, DOMSTRING, OBJECT, DATE, REGEXP
755 def p_PrimitiveType(self
, p
):
756 """PrimitiveType : UnsignedIntegerType
757 | UnrestrictedFloatType
766 if type(p
[1]) == str:
767 p
[0] = self
.BuildNamed('PrimitiveType', p
, 1)
773 def p_UnrestrictedFloatType(self
, p
):
774 """UnrestrictedFloatType : UNRESTRICTED FloatType
777 typeref
= self
.BuildNamed('PrimitiveType', p
, 1)
779 typeref
= self
.BuildNamed('PrimitiveType', p
, 2)
780 typeref
.AddChildren(self
.BuildTrue('UNRESTRICTED'))
785 def p_FloatType(self
, p
):
791 def p_UnsignedIntegerType(self
, p
):
792 """UnsignedIntegerType : UNSIGNED IntegerType
797 p
[0] = 'unsigned ' + p
[2]
800 def p_IntegerType(self
, p
):
801 """IntegerType : SHORT
802 | LONG OptionalLong"""
809 def p_OptionalLong(self
, p
):
810 """OptionalLong : LONG
818 # [85] Add support for sized array
819 def p_TypeSuffix(self
, p
):
820 """TypeSuffix : '[' integer ']' TypeSuffix
822 | '?' TypeSuffixStartingWithArray
825 p
[0] = self
.BuildNamed('Array', p
, 2, p
[4])
828 p
[0] = self
.BuildProduction('Array', p
, 1, p
[3])
831 p
[0] = ListFromConcat(self
.BuildTrue('NULLABLE'), p
[2])
835 def p_TypeSuffixStartingWithArray(self
, p
):
836 """TypeSuffixStartingWithArray : '[' ']' TypeSuffix
839 p
[0] = self
.BuildProduction('Array', p
, 0, p
[3])
846 p
[0] = self
.BuildTrue('NULLABLE')
849 def p_ReturnType(self
, p
):
853 p
[0] = self
.BuildProduction('Type', p
, 1)
854 p
[0].AddChildren(self
.BuildNamed('PrimitiveType', p
, 1))
858 # [89-90] NOT IMPLEMENTED (IdentifierList)
861 def p_ExtendedAttributeNoArgs(self
, p
):
862 """ExtendedAttributeNoArgs : identifier"""
863 p
[0] = self
.BuildNamed('ExtAttribute', p
, 1)
866 def p_ExtendedAttributeArgList(self
, p
):
867 """ExtendedAttributeArgList : identifier '(' ArgumentList ')'"""
868 arguments
= self
.BuildProduction('Arguments', p
, 2, p
[3])
869 p
[0] = self
.BuildNamed('ExtAttribute', p
, 1, arguments
)
872 def p_ExtendedAttributeIdent(self
, p
):
873 """ExtendedAttributeIdent : identifier '=' identifier"""
874 value
= self
.BuildAttribute('VALUE', p
[3])
875 p
[0] = self
.BuildNamed('ExtAttribute', p
, 1, value
)
877 # [94] NOT IMPLEMENTED (ExtendedAttributeIdentList)
880 def p_ExtendedAttributeNamedArgList(self
, p
):
881 """ExtendedAttributeNamedArgList : identifier '=' identifier '(' ArgumentList ')'"""
882 args
= self
.BuildProduction('Arguments', p
, 4, p
[5])
883 value
= self
.BuildNamed('Call', p
, 3, args
)
884 p
[0] = self
.BuildNamed('ExtAttribute', p
, 1, value
)
886 # [96] NOT IMPLEMENTED (ExtendedAttributeTypePair)
891 # p_error is called whenever the parser can not find a pattern match for
892 # a set of items from the current state. The p_error function defined here
893 # is triggered logging an error, and parsing recovery happens as the
894 # p_<type>_error functions defined above are called. This allows the parser
895 # to continue so as to capture more than one error per file.
897 def p_error(self
, t
):
901 prev
= self
.yaccobj
.symstack
[-1]
902 if type(prev
) == lex
.LexToken
:
903 msg
= "Unexpected %s after %s." % (
904 TokenTypeName(t
), TokenTypeName(prev
))
906 msg
= "Unexpected %s." % (t
.value
)
908 last
= self
.LastToken()
911 msg
= "Unexpected end of file after %s." % TokenTypeName(last
)
912 self
.yaccobj
.restart()
914 # Attempt to remap the error to a friendlier form
915 if msg
in ERROR_REMAP
:
916 msg
= ERROR_REMAP
[msg
]
918 self
._last
_error
_msg
= msg
919 self
._last
_error
_lineno
= lineno
920 self
._last
_error
_pos
= pos
922 def Warn(self
, node
, msg
):
923 sys
.stdout
.write(node
.GetLogLine(msg
))
924 self
.parse_warnings
+= 1
927 return self
.lexer
.last
929 def __init__(self
, lexer
, verbose
=False, debug
=False, mute_error
=False):
931 self
.tokens
= lexer
.KnownTokens()
932 self
.yaccobj
= yacc
.yacc(module
=self
, tabmodule
=None, debug
=debug
,
933 optimize
=0, write_tables
=0)
934 self
.parse_debug
= debug
935 self
.verbose
= verbose
936 self
.mute_error
= mute_error
937 self
._parse
_errors
= 0
938 self
._parse
_warnings
= 0
939 self
._last
_error
_msg
= None
940 self
._last
_error
_lineno
= 0
941 self
._last
_error
_pos
= 0
947 # Production is the set of items sent to a grammar rule resulting in a new
948 # item being returned.
950 # p - Is the Yacc production object containing the stack of items
951 # index - Index into the production of the name for the item being produced.
952 # cls - The type of item being producted
953 # childlist - The children of the new item
954 def BuildProduction(self
, cls
, p
, index
, childlist
=None):
959 filename
= self
.lexer
.Lexer().filename
960 lineno
= p
.lineno(index
)
961 pos
= p
.lexpos(index
)
962 out
= IDLNode(cls
, filename
, lineno
, pos
, childlist
)
965 print 'Exception while parsing:'
966 for num
, item
in enumerate(p
):
967 print ' [%d] %s' % (num
, ExpandProduction(item
))
969 print 'Last token: %s' % str(self
.LastToken())
972 def BuildNamed(self
, cls
, p
, index
, childlist
=None):
973 childlist
= ListFromConcat(childlist
)
974 childlist
.append(self
.BuildAttribute('NAME', p
[index
]))
975 return self
.BuildProduction(cls
, p
, index
, childlist
)
977 def BuildComment(self
, cls
, p
, index
):
980 # Remove comment markers
983 # For C++ style, remove any leading whitespace and the '//' marker from
986 for line
in name
.split('\n'):
987 start
= line
.find('//')
988 lines
.append(line
[start
+2:])
990 # For C style, remove ending '*/''
992 for line
in name
[:-2].split('\n'):
993 # Remove characters until start marker for this line '*' if found
994 # otherwise it should be blank.
995 offs
= line
.find('*')
997 line
= line
[offs
+ 1:].rstrip()
1001 name
= '\n'.join(lines
)
1002 childlist
= [self
.BuildAttribute('NAME', name
),
1003 self
.BuildAttribute('FORM', form
)]
1004 return self
.BuildProduction(cls
, p
, index
, childlist
)
1009 # Build and Errror node as part of the recovery process.
1012 def BuildError(self
, p
, prod
):
1013 self
._parse
_errors
+= 1
1014 name
= self
.BuildAttribute('NAME', self
._last
_error
_msg
)
1015 line
= self
.BuildAttribute('LINE', self
._last
_error
_lineno
)
1016 pos
= self
.BuildAttribute('POS', self
._last
_error
_pos
)
1017 prod
= self
.BuildAttribute('PROD', prod
)
1019 node
= self
.BuildProduction('Error', p
, 1,
1020 ListFromConcat(name
, line
, pos
, prod
))
1021 if not self
.mute_error
:
1022 node
.Error(self
._last
_error
_msg
)
1029 # An ExtendedAttribute is a special production that results in a property
1030 # which is applied to the adjacent item. Attributes have no children and
1031 # instead represent key/value pairs.
1033 def BuildAttribute(self
, key
, val
):
1034 return IDLAttribute(key
, val
)
1036 def BuildFalse(self
, key
):
1037 return IDLAttribute(key
, Boolean(False))
1039 def BuildTrue(self
, key
):
1040 return IDLAttribute(key
, Boolean(True))
1042 def GetErrors(self
):
1043 # Access lexer errors, despite being private
1044 # pylint: disable=W0212
1045 return self
._parse
_errors
+ self
.lexer
._lex
_errors
1050 # Attempts to parse the current data loaded in the lexer.
1052 def ParseText(self
, filename
, data
):
1053 self
._parse
_errors
= 0
1054 self
._parse
_warnings
= 0
1055 self
._last
_error
_msg
= None
1056 self
._last
_error
_lineno
= 0
1057 self
._last
_error
_pos
= 0
1060 self
.lexer
.Tokenize(data
, filename
)
1061 nodes
= self
.yaccobj
.parse(lexer
=self
.lexer
) or []
1062 name
= self
.BuildAttribute('NAME', filename
)
1063 return IDLNode('File', filename
, 0, 0, nodes
+ [name
])
1065 except lex
.LexError
as lexError
:
1066 sys
.stderr
.write('Error in token: %s\n' % str(lexError
))
1071 def ParseFile(parser
, filename
):
1072 """Parse a file and return a File type of node."""
1073 with
open(filename
) as fileobject
:
1075 out
= parser
.ParseText(filename
, fileobject
.read())
1076 out
.SetProperty('DATETIME', time
.ctime(os
.path
.getmtime(filename
)))
1077 out
.SetProperty('ERRORS', parser
.GetErrors())
1080 except Exception as e
:
1081 last
= parser
.LastToken()
1082 sys
.stderr
.write('%s(%d) : Internal parsing error\n\t%s.\n' % (
1083 filename
, last
.lineno
, str(e
)))
1088 parser
= IDLParser(IDLLexer())
1090 for filename
in argv
:
1091 filenode
= ParseFile(parser
, filename
)
1093 errors
+= filenode
.GetProperty('ERRORS')
1094 nodes
.append(filenode
)
1096 ast
= IDLNode('AST', '__AST__', 0, 0, nodes
)
1098 print '\n'.join(ast
.Tree(accept_props
=['PROD']))
1100 print '\nFound %d errors.\n' % errors
1105 if __name__
== '__main__':
1106 sys
.exit(main(sys
.argv
[1:]))