blob: d2fb0fd44efa8af490b03ebaa60d30d277a65b68 [file] [log] [blame]
Marc Slemkoc0e07a22006-08-09 23:34:57 +00001#!python
Marc Slemkob2039e72006-08-09 01:00:17 +00002""" Thrift IDL parser/compiler
3
4 This parser uses the Python PLY LALR parser generator to build a parser for the Thrift IDL grammar.
5
6 If a compiles \"thyc\" file exists for a given source \"thrift\" file it computes a hash of the file and determines
7 if if it is the source of the \"thyc\" file. If so, it simply returns the parse tree previously computed, otherwise it
8 parses the source and generates a new \"thyc\" file (assuming of course the source file contains no errors.)
9
10 When the parser encounters import statements it searches for corresponding \"thrift\" or \"thyc\" files in paths corresponding to
11 the specified namespace.
12
13 Author(s): Mark Slee(mclee@facebook.com), Marc Kwiatkowski (marc@facebook.com)
14
15 $Id:
16"""
17
18import lex
19import os
20import pickle
21import string
Marc Slemkob2039e72006-08-09 01:00:17 +000022import yacc
23
24class Error(object):
25
26 def __init__(self, start=0, end=0, message=""):
27 if len(message) == 0:
28 raise Exception, "NO MESSAGE"
29 self.message = message
30 self.start = start
31 self.end = end
32
33 def __str__(self):
34 return str(self.start)+": error: "+self.message
35
36class SyntaxError(Error):
Marc Slemko27340eb2006-08-10 20:45:55 +000037 def __init__(self, yaccSymbol):
38 if isinstance(yaccSymbol, yacc.YaccSymbol):
39 Error.__init__(self, yaccSymbol.lineno, yaccSymbol.lineno, "syntax error "+str(yaccSymbol.value))
40 else:
41 Error.__init__(self, 1, 1, "syntax error "+str(yaccSymbol))
Marc Slemkob2039e72006-08-09 01:00:17 +000042
43class SymanticsError(Error):
44
45 def __init__(self, definition, message):
46 Error.__init__(self, definition.start, definition.end, message)
47 self.definition = definition
48
49 def __str__(self):
50 return str(self.start)+": error: "+self.message
51
52class ErrorException(Exception):
53
54 def __init__(self, errors=None):
55 self.errors = errors
56
57class Definition(object):
58 """ Abstract thrift IDL definition unit """
59
60 def __init__(self, symbols=None, name="", id=None):
61 if symbols:
62 self.lines(symbols)
63 self.name = name
64 self.id = id
65
66 def validate(self):
67 pass
68
69 def lines(self, symbols):
70 self.start = symbols.lineno(1)
71 self.end = symbols.lineno(len(symbols) - 1)
72
73class Identifier(Definition):
74 """ An Identifier - name and optional integer id """
75
76 def __init__(self, symbols, name, id=None):
77 Definition.__init__(self, symbols, name, id)
78
79 def __str__(self):
80 result = self.name
81 if self.id != 0:
82 result+="="+str(self.id)
83 return result
84
Marc Slemko27340eb2006-08-10 20:45:55 +000085
86def toCanonicalType(ttype):
87 if isinstance(ttype, TypeDef):
88 return toCanonicalType(ttype.definitionType)
89 else:
90 return ttype
91
92def isComparableType(ttype):
93 ttype = toCanonicalType(ttype)
94 return isinstance(ttype, PrimitiveType) or isinstance(ttype, Enum)
95
Marc Slemkob2039e72006-08-09 01:00:17 +000096class Type(Definition):
97 """ Abstract Type definition """
98
99 def __init__(self, symbols, name):
100 Definition.__init__(self, symbols, name)
101 self.name = name
102
103 def __str__(self):
104 return self.name
105
106class TypeDef(Type):
107
108 def __init__(self, symbols, name, definitionType):
109 Type.__init__(self, symbols, name)
110 self.definitionType = definitionType
111
112 def __str__(self):
113 return self.name+"<"+str(self.name)+", "+str(self.definitionType)+">"
114
115""" Primitive Types """
116
117class PrimitiveType(Type):
118
119 def __init__(self, name):
120 Type.__init__(self, None, name)
121
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000122STOP_TYPE = PrimitiveType("stop")
Marc Slemkob2039e72006-08-09 01:00:17 +0000123VOID_TYPE = PrimitiveType("void")
124BOOL_TYPE = PrimitiveType("bool")
125STRING_TYPE =PrimitiveType("utf7")
126UTF7_TYPE = PrimitiveType("utf7")
127UTF8_TYPE = PrimitiveType("utf8")
128UTF16_TYPE = PrimitiveType("utf16")
129BYTE_TYPE = PrimitiveType("u08")
130I08_TYPE = PrimitiveType("i08")
131I16_TYPE = PrimitiveType("i16")
132I32_TYPE = PrimitiveType("i32")
133I64_TYPE = PrimitiveType("i64")
134U08_TYPE = PrimitiveType("u08")
135U16_TYPE = PrimitiveType("u16")
136U32_TYPE = PrimitiveType("u32")
137U64_TYPE = PrimitiveType("u64")
138FLOAT_TYPE = PrimitiveType("float")
139
140PRIMITIVE_MAP = {
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000141 "stop" : STOP_TYPE,
Marc Slemkob2039e72006-08-09 01:00:17 +0000142 "void" : VOID_TYPE,
143 "bool" : BOOL_TYPE,
144 "string": UTF7_TYPE,
145 "utf7": UTF7_TYPE,
146 "utf8": UTF8_TYPE,
147 "utf16": UTF16_TYPE,
148 "byte" : U08_TYPE,
149 "i08": I08_TYPE,
150 "i16": I16_TYPE,
151 "i32": I32_TYPE,
152 "i64": I64_TYPE,
153 "u08": U08_TYPE,
154 "u16": U16_TYPE,
155 "u32": U32_TYPE,
156 "u64": U64_TYPE,
157 "float": FLOAT_TYPE
158}
159
160""" Collection Types """
161
162class CollectionType(Type):
163
164 def __init__(self, symbols, name):
165 Type.__init__(self, symbols, name)
166
Marc Slemko27340eb2006-08-10 20:45:55 +0000167 def validate(self):
168 return True
169
Marc Slemkob2039e72006-08-09 01:00:17 +0000170class Map(CollectionType):
171
172 def __init__(self, symbols, keyType, valueType):
173 CollectionType.__init__(self, symbols, "map<"+keyType.name+","+valueType.name +">")
174 self.keyType = keyType
175 self.valueType = valueType
176
Marc Slemko27340eb2006-08-10 20:45:55 +0000177 def validate(self):
178 if not isComparableType(self.keyType):
179 raise ErrorException([SymanticsError(self, "key type \""+str(self.keyType)+"\" is not a comparable type.")])
180
Marc Slemkob2039e72006-08-09 01:00:17 +0000181class Set(CollectionType):
182
183 def __init__(self, symbols, valueType):
184 CollectionType.__init__(self, symbols, "set<"+valueType.name+">")
185 self.valueType = valueType
186
Marc Slemko27340eb2006-08-10 20:45:55 +0000187 def validate(self):
188 if not isComparableType(self.valueType):
189 raise ErrorException([SymanticsError(self, "value type \""+str(self.valueType)+"\" is not a comparable type.")])
190
Marc Slemkob2039e72006-08-09 01:00:17 +0000191class List(CollectionType):
192
193 def __init__(self, symbols, valueType):
194 CollectionType.__init__(self, symbols, "list<"+valueType.name+">")
195 self.valueType = valueType
196
197class Enum(Definition):
198
199 def __init__(self, symbols, name, enumDefs):
200 Definition.__init__(self, symbols, name)
201 self.enumDefs = enumDefs
202
203 def validate(self):
204 ids = {}
205 names = {}
206 errors = []
207
208 for enumDef in self.enumDefs:
209
210 if enumDef.name in names:
211 errors.append(SymanticsError(enumDef, self.name+"."+str(enumDef.name)+" already defined at line "+str(names[enumDef.name].start)))
212 else:
213 names[enumDef.name] = enumDef
214
215 if enumDef.id != None:
216 oldEnumDef = ids.get(enumDef.id)
217 if oldEnumDef:
218 errors.append(SymanticsError(enumDef, "enum "+self.name+" \""+str(enumDef.name)+"\" uses constant already assigned to \""+oldEnumDef.name+"\""))
219 else:
220 ids[enumDef.id] = enumDef
221
222 if len(errors):
223 raise ErrorException(errors)
224
225 def assignId(enumDef, currentId, ids):
226 'Finds the next available id number for an enum definition'
227
228 id= currentId + 1
229
230 while id in ids:
231 id += 1
232
233 enumDef.id = id
234
235 ids[enumDef.id] = enumDef
236
237 # assign ids for all enum defs with unspecified ids
238
239 currentId = 0
240
241 for enumDef in self.enumDefs:
242 if not enumDef.id:
243 assignId(enumDef, currentId, ids)
244 currentId = enumDef.id
245
246 def __repr__(self):
247 return str(self)
248
249 def __str__(self):
250 return self.name+"<"+string.join(map(lambda enumDef: str(enumDef), self.enumDefs), ", ")
251
252class EnumDef(Definition):
253
254 def __init__(self, symbols, name, id=None):
255 Definition.__init__(self, symbols, name, id)
256
257 def __repr__(self):
258 return str(self)
259
260 def __str__(self):
261 result = self.name
262 if self.id:
263 result+= ":"+str(self.id)
264 return result
265
266
267class Field(Definition):
268
269 def __init__(self, symbols, type, identifier):
270 Definition.__init__(self, symbols, identifier.name, identifier.id)
271 self.type = type
272 self.identifier = identifier
273
274 def __str__(self):
275 return "<"+str(self.type)+", "+str(self.identifier)+">"
276
277def validateFieldList(fieldList):
278
279 errors = []
280 names = {}
281 ids = {}
282
283 for field in fieldList:
284
285 if field.name in names:
286 oldField = names[field.name]
287 errors.append(SymanticsError(field, "field \""+field.name+"\" already defined at "+str(oldField.start)))
288 else:
289 names[field.name] = field
290
291 if field.id != None:
292 oldField = ids.get(field.id)
293 if oldField:
294 errors.append(SymanticsError(field, "field \""+field.name+"\" uses constant already assigned to \""+oldField.name+"\""))
295 else:
296 ids[field.id] = field
297
298 if len(errors):
299 raise ErrorException(errors)
300
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000301 def assignId(field, currentId, ids):
302 'Finds the next available id number for a field'
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000303 id = currentId - 1
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000304
305 while id in ids:
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000306 id-= 1
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000307
308 field.id = id
309
310 ids[field.id] = field
311
312 return id
313
314 # assign ids for all fields with unspecified ids
315
316 currentId = 0
317
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000318 for field in fieldList:
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000319 if not field.id:
320 currentId = assignId(field, currentId, ids)
321
Marc Slemkob2039e72006-08-09 01:00:17 +0000322class Struct(Type):
323
324 def __init__(self, symbols, name, fieldList):
325 Type.__init__(self, symbols, name)
326 self.fieldList = fieldList
327
328 def validate(self):
329 validateFieldList(self.fieldList)
330
331 def __str__(self):
332 return self.name+"<"+string.join(map(lambda a: str(a), self.fieldList), ", ")+">"
333
334class Function(Definition):
335
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000336 def __init__(self, symbols, name, resultType, argsStruct):
Marc Slemkob2039e72006-08-09 01:00:17 +0000337 Definition.__init__(self, symbols, name)
338 self.resultType = resultType
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000339 self.argsStruct = argsStruct
Marc Slemkob2039e72006-08-09 01:00:17 +0000340
341 def validate(self):
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000342 validateFieldList(self.argsStruct.fieldList)
Marc Slemkob2039e72006-08-09 01:00:17 +0000343
344 def __str__(self):
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000345 return self.name+"("+string.join(map(lambda a: str(a), self.argsStruct), ", ")+") => "+str(self.resultType)
Marc Slemkob2039e72006-08-09 01:00:17 +0000346
347class Service(Definition):
348
349 def __init__(self, symbols, name, functionList):
350 Definition.__init__(self, symbols, name)
351 self.functionList = functionList
352
353 def validate(self):
354
355 errors = []
356 functionNames = {}
357 for function in self.functionList:
358 if function.name in functionNames:
359 oldFunction = functionName[function.name]
360 errors.append(SymanticsError(function, "function "+function.name+" already defined at "+str(oldFunction.start)))
361
362 if len(errors):
363 raise ErrorException(errors)
364
365 def __str__(self):
366 return self.name+"("+string.join(map(lambda a: str(a), self.functionList), ", ")+")"
367
368class Program(object):
369
370 def __init__(self, symbols=None, name="", definitions=None, serviceMap=None, typedefMap=None, enumMap=None, structMap=None, collectionMap=None,
371 primitiveMap=None):
372
373 self.name = name
374
375 if not definitions:
376 definitions = []
377 self.definitions = definitions
378
379 if not serviceMap:
380 serviceMap = {}
381 self.serviceMap = serviceMap
382
383 if not typedefMap:
384 typedefMap = {}
385 self.typedefMap = typedefMap
386
387 if not enumMap:
388 enumMap = {}
389 self.enumMap = enumMap
390
391 if not structMap:
392 structMap = {}
393 self.structMap = structMap
394
395 if not collectionMap:
396 collectionMap = {}
397 self.collectionMap = collectionMap
398
399 if not primitiveMap:
400 primitiveMap = PRIMITIVE_MAP
401 self.primitiveMap = primitiveMap
402
403 def addDefinition(self, definition, definitionMap, definitionTypeName):
404
405 oldDefinition = definitionMap.get(definition.name)
406 if oldDefinition:
407 raise ErrorException([SymanticsError(definition, definitionTypeName+" "+definition.name+" is already defined at "+str(oldDefinition.start))])
408 else:
409 definitionMap[definition.name] = definition
410
411 # keep an ordered list of definitions so that stub/skel generators can determine the original order
412
413 self.definitions.append(definition)
414
415 def addStruct(self, struct):
416 self.addDefinition(struct, self.structMap, "struct")
417
418 def addTypedef(self, typedef):
419 self.addDefinition(typedef, self.typedefMap, "typedef")
420
421 def addEnum(self, enum):
422 self.addDefinition(enum, self.enumMap, "enum")
423
424 def addService(self, service):
425 self.addDefinition(service, self.serviceMap, "service")
426
427 def addCollection(self, collection):
428 if collection.name in self.collectionMap:
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000429 return self.collectionMap[collection.name]
Marc Slemkob2039e72006-08-09 01:00:17 +0000430 else:
431 self.collectionMap[collection.name] = collection
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000432 return collection
Marc Slemkob2039e72006-08-09 01:00:17 +0000433
434 def getType(self, parent, symbol):
435 """ Get the type definition for a symbol"""
436
437 typeName = None
438
439 if isinstance(symbol, Type):
440 return symbol
441 elif isinstance(symbol, Field):
442 typeName = symbol.type.name
443 elif isinstance(symbol, Identifier):
444 typeName = symbol.name
445 else:
446 raise ErrorException([SymanticsError(parent, "unknown symbol \""+str(symbol)+"\"")])
447
448 for map in (self.primitiveMap, self.collectionMap, self.typedefMap, self.enumMap, self.structMap):
449 if typeName in map:
450 return map[typeName]
451
452 raise ErrorException([SymanticsError(parent, "\""+typeName+"\" is not defined.")])
453
454 def hasType(self, parent, symbol):
455 """ Determine if a type definition exists for the symbol"""
456
457 return self.getType(parent, symbol) == True
458
459 def validate(self):
460
461 errors = []
462
463 # Verify that struct fields types, collection key and element types, and typedef defined types exists and replaces
464 # type names with references to the type objects
465
466 for struct in self.structMap.values():
467 for field in struct.fieldList:
468 try:
469 field.type = self.getType(struct, field)
470 except ErrorException, e:
471 errors+= e.errors
472
473 for collection in self.collectionMap.values():
474 try:
475 if isinstance(collection, Map):
476 collection.keyType = self.getType(collection, collection.keyType)
477
478 collection.valueType = self.getType(collection, collection.valueType)
Marc Slemko27340eb2006-08-10 20:45:55 +0000479
480 collection.validate()
Marc Slemkob2039e72006-08-09 01:00:17 +0000481
482 except ErrorException, e:
483 errors+= e.errors
484
485 for typedef in self.typedefMap.values():
486 try:
487 typedef.definitionType = self.getType(self, typedef.definitionType)
488
489 except ErrorException, e:
490 errors+= e.errors
491
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000492 # Verify that service function result and arg list types exist and replace type name with reference to definition
Marc Slemkob2039e72006-08-09 01:00:17 +0000493
494 for service in self.serviceMap.values():
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000495
Marc Slemkob2039e72006-08-09 01:00:17 +0000496 for function in service.functionList:
497 try:
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000498 function.resultType = self.getType(service, function.resultType)
Marc Slemkob2039e72006-08-09 01:00:17 +0000499 except ErrorException, e:
500 errors+= e.errors
501
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000502 for field in function.argsStruct.fieldList:
Marc Slemkob2039e72006-08-09 01:00:17 +0000503 try:
504 field.type = self.getType(function, field)
505 except ErrorException, e:
506 errors+= e.errors
507
508 if len(errors):
509 raise ErrorException(errors)
Marc Slemkob2039e72006-08-09 01:00:17 +0000510
511class Parser(object):
512
513 reserved = ("BYTE",
514 # "CONST",
515 "DOUBLE",
516 "ENUM",
517 # "EXCEPTION",
518 # "EXTENDS",
519 "I08",
520 "I16",
521 "I32",
522 "I64",
523 "LIST",
524 "MAP",
525 "SERVICE",
526 "SET",
527 # "STATIC",
528 "STRING",
529 "STRUCT",
530 # "SYNCHRONIZED",
531 "TYPEDEF",
532 "U08",
533 "U16",
534 "U32",
535 "U64",
536 "UTF16",
537 "UTF8",
538 "VOID"
539 )
540
541 tokens = reserved + (
542 # Literals (identifier, integer constant, float constant, string constant, char const)
543 'ID', 'ICONST', 'SCONST', 'FCONST',
544 # Operators default=, optional*, variable...
545 'ASSIGN', #'OPTIONAL', 'ELLIPSIS',
546 # Delimeters ( ) { } < > , . ; :
547 'LPAREN', 'RPAREN',
548 'LBRACE', 'RBRACE',
549 'LANGLE', 'RANGLE',
550 'COMMA' #, 'PERIOD', 'SEMI' , 'COLON'
551 )
552
553 precendence = ()
554
555 reserved_map = {}
556
557 for r in reserved:
558 reserved_map[r.lower()] = r
559
560 def t_ID(self, t):
561 r'[A-Za-z_][\w_]*'
562 t.type = self.reserved_map.get(t.value,"ID")
563 return t
564
565 # Completely ignored characters
566 t_ignore = ' \t\x0c'
567
568# t_OPTIONAL = r'\*'
569 t_ASSIGN = r'='
570
571 # Delimeters
572 t_LPAREN = r'\('
573 t_RPAREN = r'\)'
574 t_LANGLE = r'\<'
575 t_RANGLE = r'\>'
576 t_LBRACE = r'\{'
577 t_RBRACE = r'\}'
578 t_COMMA = r','
579# t_PERIOD = r'\.'
580# t_SEMI = r';'
581# t_COLON = r':'
582# t_ELLIPSIS = r'\.\.\.'
583
584 # Integer literal
585 t_ICONST = r'\d+([uU]|[lL]|[uU][lL]|[lL][uU])?'
586
587 # Floating literal
588 t_FCONST = r'((\d+)(\.\d+)(e(\+|-)?(\d+))? | (\d+)e(\+|-)?(\d+))([lL]|[fF])?'
589
590 # String literal
591 t_SCONST = r'\"([^\\\n]|(\\.))*?\"'
592
593 # Comments
594 def t_comment(self, t):
595 r'(?:/\*(.|\n)*?\*/)|(?://[^\n]*\n)'
596 t.lineno += t.value.count('\n')
597
598 def t_error(self, t):
599 print "Illegal character %s" % repr(t.value[0])
600 t.skip(1)
601
602 # Newlines
603 def t_newline(self, t):
604 r'\n+'
605 t.lineno += t.value.count("\n")
606
607 def p_program(self, p):
608 'program : definitionlist'
609 pass
610
611 def p_definitionlist_1(self, p):
612 'definitionlist : definitionlist definition'
613 pass
614
615 def p_definitionlist_2(self, p):
616 'definitionlist :'
617 pass
618
619 def p_definition_1(self, p):
620 'definition : typedef'
621 self.pdebug("p_definition_1", p)
622 p[0] = p[1]
623 try:
624 self.program.addTypedef(p[0])
625 except ErrorException, e:
626 self.errors+= e.errors
627
628 def p_definition_2(self, p):
629 'definition : enum'
630 self.pdebug("p_definition_2", p)
631 p[0] = p[1]
632 try:
633 self.program.addEnum(p[0])
634 except ErrorException, e:
635 self.errors+= e.errors
636
637 def p_definition_3(self, p):
638 'definition : struct'
639 self.pdebug("p_definition_3", p)
640 p[0] = p[1]
641 try:
642 self.program.addStruct(p[0])
643 except ErrorException, e:
644 self.errors+= e.errors
645
646 def p_definition_4(self, p):
647 'definition : service'
648 self.pdebug("p_definition_4", p)
649 p[0] = p[1]
650 try:
651 self.program.addService(p[0])
652 except ErrorException, e:
653 self.errors+= e.errors
654
655 def p_typedef(self, p):
656 'typedef : TYPEDEF definitiontype ID'
657 self.pdebug("p_typedef", p)
658 p[0] = TypeDef(p, p[3], p[2])
659 try:
660 p[0].validate()
661
662 except ErrorException, e:
663 self.errors+= e.errors
664
Marc Slemkob2039e72006-08-09 01:00:17 +0000665 def p_enum(self, p):
666 'enum : ENUM ID LBRACE enumdeflist RBRACE'
667 self.pdebug("p_enum", p)
668 p[0] = Enum(p, p[2], p[4])
669
670 try:
671 p[0].validate()
672 except ErrorException, e:
673 self.errors+= e.errors
674
675 def p_enumdeflist_1(self, p):
676 'enumdeflist : enumdeflist COMMA enumdef'
677 self.pdebug("p_enumdeflist_1", p)
678 p[0] = p[1] + (p[3],)
679
680 def p_enumdeflist_2(self, p):
681 'enumdeflist : enumdef'
682 self.pdebug("p_enumdeflist_2", p)
683 p[0] = (p[1],)
684
685 def p_enumdef_0(self, p):
686 'enumdef : ID ASSIGN ICONST'
687 self.pdebug("p_enumdef_0", p)
688 p[0] = EnumDef(p, p[1], int(p[3]))
689
690 def p_enumdef_1(self, p):
691 'enumdef : ID'
692 self.pdebug("p_enumdef_1", p)
693 p[0] = EnumDef(p, p[1])
694
695 def p_struct(self, p):
696 'struct : STRUCT ID LBRACE fieldlist RBRACE'
697 self.pdebug("p_struct", p)
698 p[0] = Struct(p, p[2], p[4])
699
700 try:
701 p[0].validate()
702 except ErrorException, e:
703 self.errors+= e.errors
704
705 def p_service(self, p):
706 'service : SERVICE ID LBRACE functionlist RBRACE'
707 self.pdebug("p_service", p)
708 p[0] = Service(p, p[2], p[4])
709 try:
710 p[0].validate()
711 except ErrorException, e:
712 self.errors+= e.errors
713
714 def p_functionlist_1(self, p):
715 'functionlist : functionlist function'
716 self.pdebug("p_functionlist_1", p)
717 p[0] = p[1] + (p[2],)
718
719 def p_functionlist_2(self, p):
720 'functionlist :'
721 self.pdebug("p_functionlist_2", p)
722 p[0] = ()
723
724 def p_function(self, p):
725 'function : functiontype functionmodifiers ID LPAREN fieldlist RPAREN'
726 self.pdebug("p_function", p)
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000727 p[0] = Function(p, p[3], p[1], Struct(p, p[3]+"_args", p[5]))
Marc Slemkob2039e72006-08-09 01:00:17 +0000728 try:
729 p[0].validate()
730 except ErrorException, e:
731 self.errors+= e.errors
732
733 def p_functionmodifiers(self, p):
734 'functionmodifiers :'
735 self.pdebug("p_functionmodifiers", p)
736 p[0] = ()
737
738 def p_fieldlist_1(self, p):
739 'fieldlist : fieldlist COMMA field'
740 self.pdebug("p_fieldlist_1", p)
741 p[0] = p[1] + (p[3],)
742
743 def p_fieldlist_2(self, p):
744 'fieldlist : field'
745 self.pdebug("p_fieldlist_2", p)
746 p[0] = (p[1],)
747
748 def p_fieldlist_3(self, p):
749 'fieldlist :'
750 self.pdebug("p_fieldlist_3", p)
751 p[0] = ()
752
753 def p_field_1(self, p):
754 'field : fieldtype ID ASSIGN ICONST'
755 self.pdebug("p_field_1", p)
756 p[0] = Field(p, p[1], Identifier(None, p[2], int(p[4])))
757
758 def p_field_2(self, p):
759 'field : fieldtype ID'
760 self.pdebug("p_field_2", p)
761 p[0] = Field(p, p[1], Identifier(None, p[2]))
762
763 def p_definitiontype_1(self, p):
764 'definitiontype : basetype'
765 self.pdebug("p_definitiontype_1", p)
766 p[0] = p[1]
767
768 def p_definitiontype_2(self, p):
769 'definitiontype : collectiontype'
770 self.pdebug("p_definitiontype_2", p)
771 p[0] = p[1]
772
773 def p_functiontype_1(self, p):
774 'functiontype : fieldtype'
775 self.pdebug("p_functiontype_1", p)
776 p[0] = p[1]
777
778 def p_functiontype_2(self, p):
779 'functiontype : VOID'
780 self.pdebug("p_functiontype_2", p)
781 p[0] = self.program.primitiveMap[p[1].lower()]
782
783 def p_fieldtype_1(self, p):
784 'fieldtype : ID'
785 self.pdebug("p_fieldtype_1", p)
786 p[0] = Identifier(p, p[1])
787
788 def p_fieldtype_2(self, p):
789 'fieldtype : basetype'
790 self.pdebug("p_fieldtype_2", p)
791 p[0] = p[1]
792
793 def p_fieldtype_3(self, p):
794 'fieldtype : collectiontype'
795 self.pdebug("p_fieldtype_3", p)
796 p[0] = p[1]
797
798 def p_basetype_1(self, p):
799 'basetype : STRING'
800 self.pdebug("p_basetype_1", p)
801 p[0] = self.program.primitiveMap[p[1].lower()]
802
803 def p_basetype_2(self, p):
804 'basetype : BYTE'
805 self.pdebug("p_basetype_2", p)
806 p[0] = self.program.primitiveMap[p[1].lower()]
807
808 def p_basetype_3(self, p):
809 'basetype : I08'
810 self.pdebug("p_basetype_3", p)
811 p[0] = self.program.primitiveMap[p[1].lower()]
812
813 def p_basetype_4(self, p):
814 'basetype : U08'
815 self.pdebug("p_basetype_4", p)
816 p[0] = self.program.primitiveMap[p[1].lower()]
817
818 def p_basetype_5(self, p):
819 'basetype : I16'
820 self.pdebug("p_basetype_5", p)
821 p[0] = self.program.primitiveMap[p[1].lower()]
822
823 def p_basetype_6(self, p):
824 'basetype : U16'
825 self.pdebug("p_basetype_6", p)
826 p[0] = self.program.primitiveMap[p[1].lower()]
827
828 def p_basetype_7(self, p):
829 'basetype : I32'
830 self.pdebug("p_basetype_7", p)
831 p[0] = self.program.primitiveMap[p[1].lower()]
832
833 def p_basetype_8(self, p):
834 'basetype : U32'
835 self.pdebug("p_basetype_8", p)
836 p[0] = self.program.primitiveMap[p[1].lower()]
837
838 def p_basetype_9(self, p):
839 'basetype : I64'
840 self.pdebug("p_basetype_9", p)
841 p[0] = self.program.primitiveMap[p[1].lower()]
842
843 def p_basetype_10(self, p):
844 'basetype : U64'
845 self.pdebug("p_basetype_10", p)
846 p[0] = self.program.primitiveMap[p[1].lower()]
847
848 def p_basetype_11(self, p):
849 'basetype : UTF8'
850 self.pdebug("p_basetype_11", p)
851 p[0] = self.program.primitiveMap[p[1].lower()]
852
853 def p_basetype_12(self, p):
854 'basetype : UTF16'
855 self.pdebug("p_basetype_12", p)
856 p[0] = self.program.primitiveMap[p[1].lower()]
857
858 def p_basetype_13(self, p):
859 'basetype : DOUBLE'
860 self.pdebug("p_basetype_13", p)
861 p[0] = self.program.primitiveMap[p[1].lower()]
862
863 def p_collectiontype_1(self, p):
864 'collectiontype : maptype'
865 self.pdebug("p_collectiontype_1", p)
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000866 p[0] = self.program.addCollection(p[1])
Marc Slemkob2039e72006-08-09 01:00:17 +0000867
868 def p_collectiontype_2(self, p):
869 'collectiontype : settype'
870 self.pdebug("p_collectiontype_2", p)
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000871 p[0] = self.program.addCollection(p[1])
Marc Slemkob2039e72006-08-09 01:00:17 +0000872
873 def p_collectiontype_3(self, p):
874 'collectiontype : listtype'
875 self.pdebug("p_collectiontype_3", p)
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000876 p[0] = self.program.addCollection(p[1])
Marc Slemkob2039e72006-08-09 01:00:17 +0000877
878 def p_maptype(self, p):
879 'maptype : MAP LANGLE fieldtype COMMA fieldtype RANGLE'
880 self.pdebug("p_maptype", p)
881 p[0] = Map(p, p[3], p[5])
882
883 def p_settype(self, p):
884 'settype : SET LANGLE fieldtype RANGLE'
885 self.pdebug("p_settype", p)
886 p[0] = Set(p, p[3])
887
888 def p_listtype(self, p):
889 'listtype : LIST LANGLE fieldtype RANGLE'
890 self.pdebug("p_listtype", p)
Marc Slemkoc4eb9e82006-08-10 03:29:29 +0000891 p[0] = List(p, p[3])
Marc Slemkob2039e72006-08-09 01:00:17 +0000892
893 def p_error(self, p):
Marc Slemko27340eb2006-08-10 20:45:55 +0000894 # p_error is called with an empty token if eof was encountered unexpectedly.
895 if not p:
896 self.errors.append(SyntaxError("Unexpected end of file"))
897 else:
898 self.errors.append(SyntaxError(p))
Marc Slemkob2039e72006-08-09 01:00:17 +0000899
900 def pdebug(self, name, p):
901 if self.debug:
902 print(name+"("+string.join(map(lambda t: "<<"+str(t)+">>", p), ", ")+")")
903
904 def __init__(self, **kw):
905 self.debug = kw.get('debug', 0)
906 self.names = { }
907 self.program = Program()
908 self.errors = []
909
910 try:
911 modname = os.path.split(os.path.splitext(__file__)[0])[1] + "_" + self.__class__.__name__
912 except:
913 modname = "parser"+"_"+self.__class__.__name__
914 self.debugfile = modname + ".dbg"
915 self.tabmodule = modname + "_" + "parsetab"
916 #print self.debugfile, self.tabmodule
917
918 # Build the lexer and parser
919 lex.lex(module=self, debug=self.debug)
920 yacc.yacc(module=self,
921 debug=self.debug,
922 debugfile=self.debugfile,
923 tabmodule=self.tabmodule)
924
925 def parsestring(self, s, filename=""):
926 yacc.parse(s)
927
928 if len(self.errors) == 0:
929 try:
930 self.program.validate()
931 except ErrorException, e:
932 self.errors+= e.errors
933
934 if len(self.errors):
935 for error in self.errors:
936 print(filename+":"+str(error))
937
938 def parse(self, filename, doPickle=True):
939
940 f = file(filename, "r")
941
942 self.parsestring(f.read(), filename)
943
944 if len(self.errors) == 0 and doPickle:
945
946 outf = file(os.path.splitext(filename)[0]+".thyc", "w")
947
948 pickle.dump(self.program, outf)