blob: 5500f1c5dd75999b98b5d95d5c0ce9266df731f3 [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):
Marc Slemko5b126d62006-08-11 23:03:42 +000087 if isinstance(ttype, TypedefType):
Marc Slemko27340eb2006-08-10 20:45:55 +000088 return toCanonicalType(ttype.definitionType)
89 else:
90 return ttype
91
92def isComparableType(ttype):
93 ttype = toCanonicalType(ttype)
Marc Slemko5b126d62006-08-11 23:03:42 +000094 return isinstance(ttype, PrimitiveType) or isinstance(ttype, EnumType)
Marc Slemko27340eb2006-08-10 20:45:55 +000095
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
Marc Slemko5b126d62006-08-11 23:03:42 +0000106class TypedefType(Type):
Marc Slemkob2039e72006-08-09 01:00:17 +0000107
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")
Marc Slemkod8b10512006-08-14 23:30:37 +0000139DOUBLE_TYPE = PrimitiveType("double")
Marc Slemkob2039e72006-08-09 01:00:17 +0000140
141PRIMITIVE_MAP = {
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000142 "stop" : STOP_TYPE,
Marc Slemkob2039e72006-08-09 01:00:17 +0000143 "void" : VOID_TYPE,
144 "bool" : BOOL_TYPE,
145 "string": UTF7_TYPE,
146 "utf7": UTF7_TYPE,
147 "utf8": UTF8_TYPE,
148 "utf16": UTF16_TYPE,
149 "byte" : U08_TYPE,
150 "i08": I08_TYPE,
151 "i16": I16_TYPE,
152 "i32": I32_TYPE,
153 "i64": I64_TYPE,
154 "u08": U08_TYPE,
155 "u16": U16_TYPE,
156 "u32": U32_TYPE,
157 "u64": U64_TYPE,
Marc Slemkod8b10512006-08-14 23:30:37 +0000158 "float": FLOAT_TYPE,
159 "double": DOUBLE_TYPE
Marc Slemkob2039e72006-08-09 01:00:17 +0000160}
161
162""" Collection Types """
163
164class CollectionType(Type):
165
166 def __init__(self, symbols, name):
167 Type.__init__(self, symbols, name)
168
Marc Slemko27340eb2006-08-10 20:45:55 +0000169 def validate(self):
170 return True
171
Marc Slemko5b126d62006-08-11 23:03:42 +0000172class MapType(CollectionType):
Marc Slemkob2039e72006-08-09 01:00:17 +0000173
174 def __init__(self, symbols, keyType, valueType):
175 CollectionType.__init__(self, symbols, "map<"+keyType.name+","+valueType.name +">")
176 self.keyType = keyType
177 self.valueType = valueType
178
Marc Slemko27340eb2006-08-10 20:45:55 +0000179 def validate(self):
180 if not isComparableType(self.keyType):
181 raise ErrorException([SymanticsError(self, "key type \""+str(self.keyType)+"\" is not a comparable type.")])
182
Marc Slemko5b126d62006-08-11 23:03:42 +0000183class SetType(CollectionType):
Marc Slemkob2039e72006-08-09 01:00:17 +0000184
185 def __init__(self, symbols, valueType):
186 CollectionType.__init__(self, symbols, "set<"+valueType.name+">")
187 self.valueType = valueType
188
Marc Slemko27340eb2006-08-10 20:45:55 +0000189 def validate(self):
190 if not isComparableType(self.valueType):
191 raise ErrorException([SymanticsError(self, "value type \""+str(self.valueType)+"\" is not a comparable type.")])
192
Marc Slemko5b126d62006-08-11 23:03:42 +0000193class ListType(CollectionType):
Marc Slemkob2039e72006-08-09 01:00:17 +0000194
195 def __init__(self, symbols, valueType):
196 CollectionType.__init__(self, symbols, "list<"+valueType.name+">")
197 self.valueType = valueType
198
Marc Slemko5b126d62006-08-11 23:03:42 +0000199class EnumType(Definition):
Marc Slemkob2039e72006-08-09 01:00:17 +0000200
201 def __init__(self, symbols, name, enumDefs):
202 Definition.__init__(self, symbols, name)
203 self.enumDefs = enumDefs
204
205 def validate(self):
206 ids = {}
207 names = {}
208 errors = []
209
210 for enumDef in self.enumDefs:
211
212 if enumDef.name in names:
213 errors.append(SymanticsError(enumDef, self.name+"."+str(enumDef.name)+" already defined at line "+str(names[enumDef.name].start)))
214 else:
215 names[enumDef.name] = enumDef
216
217 if enumDef.id != None:
218 oldEnumDef = ids.get(enumDef.id)
219 if oldEnumDef:
220 errors.append(SymanticsError(enumDef, "enum "+self.name+" \""+str(enumDef.name)+"\" uses constant already assigned to \""+oldEnumDef.name+"\""))
221 else:
222 ids[enumDef.id] = enumDef
223
224 if len(errors):
225 raise ErrorException(errors)
226
227 def assignId(enumDef, currentId, ids):
228 'Finds the next available id number for an enum definition'
229
230 id= currentId + 1
231
232 while id in ids:
233 id += 1
234
235 enumDef.id = id
236
237 ids[enumDef.id] = enumDef
238
239 # assign ids for all enum defs with unspecified ids
240
241 currentId = 0
242
243 for enumDef in self.enumDefs:
244 if not enumDef.id:
245 assignId(enumDef, currentId, ids)
246 currentId = enumDef.id
247
248 def __repr__(self):
249 return str(self)
250
251 def __str__(self):
252 return self.name+"<"+string.join(map(lambda enumDef: str(enumDef), self.enumDefs), ", ")
253
254class EnumDef(Definition):
255
256 def __init__(self, symbols, name, id=None):
257 Definition.__init__(self, symbols, name, id)
258
259 def __repr__(self):
260 return str(self)
261
262 def __str__(self):
263 result = self.name
264 if self.id:
265 result+= ":"+str(self.id)
266 return result
267
268
269class Field(Definition):
270
271 def __init__(self, symbols, type, identifier):
272 Definition.__init__(self, symbols, identifier.name, identifier.id)
273 self.type = type
274 self.identifier = identifier
275
276 def __str__(self):
277 return "<"+str(self.type)+", "+str(self.identifier)+">"
278
279def validateFieldList(fieldList):
280
281 errors = []
282 names = {}
283 ids = {}
284
285 for field in fieldList:
286
287 if field.name in names:
288 oldField = names[field.name]
289 errors.append(SymanticsError(field, "field \""+field.name+"\" already defined at "+str(oldField.start)))
290 else:
291 names[field.name] = field
292
293 if field.id != None:
294 oldField = ids.get(field.id)
295 if oldField:
296 errors.append(SymanticsError(field, "field \""+field.name+"\" uses constant already assigned to \""+oldField.name+"\""))
297 else:
298 ids[field.id] = field
299
300 if len(errors):
301 raise ErrorException(errors)
302
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000303 def assignId(field, currentId, ids):
304 'Finds the next available id number for a field'
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000305 id = currentId - 1
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000306
307 while id in ids:
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000308 id-= 1
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000309
310 field.id = id
311
312 ids[field.id] = field
313
314 return id
315
316 # assign ids for all fields with unspecified ids
317
318 currentId = 0
319
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000320 for field in fieldList:
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000321 if not field.id:
322 currentId = assignId(field, currentId, ids)
323
Marc Slemko5b126d62006-08-11 23:03:42 +0000324class StructType(Type):
Marc Slemkob2039e72006-08-09 01:00:17 +0000325
326 def __init__(self, symbols, name, fieldList):
327 Type.__init__(self, symbols, name)
328 self.fieldList = fieldList
329
330 def validate(self):
331 validateFieldList(self.fieldList)
332
333 def __str__(self):
334 return self.name+"<"+string.join(map(lambda a: str(a), self.fieldList), ", ")+">"
335
Marc Slemkod8b10512006-08-14 23:30:37 +0000336class ExceptionType(StructType):
337
338 def __init__(self, symbols, name, fieldList):
339 StructType.__init__(self, symbols, name, fieldList)
340
Marc Slemkob2039e72006-08-09 01:00:17 +0000341class Function(Definition):
342
Marc Slemko5b126d62006-08-11 23:03:42 +0000343 def __init__(self, symbols, name, resultStruct, argsStruct, ):
Marc Slemkob2039e72006-08-09 01:00:17 +0000344 Definition.__init__(self, symbols, name)
Marc Slemko5b126d62006-08-11 23:03:42 +0000345 self.resultStruct = resultStruct
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000346 self.argsStruct = argsStruct
Marc Slemkob2039e72006-08-09 01:00:17 +0000347
348 def validate(self):
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000349 validateFieldList(self.argsStruct.fieldList)
Marc Slemkod8b10512006-08-14 23:30:37 +0000350 validateFieldList(self.resultStruct.fieldList)
Marc Slemko5b126d62006-08-11 23:03:42 +0000351
352 def args(self):
353 return self.argsStruct.fieldList
354
355 def returnType(self):
356 return self.resultStruct.fieldList[0].type
Marc Slemkod8b10512006-08-14 23:30:37 +0000357
358 def exceptions(self):
359 return self.resultStruct.fieldList[1:]
Marc Slemkob2039e72006-08-09 01:00:17 +0000360
361 def __str__(self):
Marc Slemkod8b10512006-08-14 23:30:37 +0000362 return self.name+"("+str(self.argsStruct)+") => "+str(self.resultStruct)
Marc Slemkob2039e72006-08-09 01:00:17 +0000363
364class Service(Definition):
365
366 def __init__(self, symbols, name, functionList):
367 Definition.__init__(self, symbols, name)
368 self.functionList = functionList
369
370 def validate(self):
371
372 errors = []
373 functionNames = {}
374 for function in self.functionList:
375 if function.name in functionNames:
376 oldFunction = functionName[function.name]
377 errors.append(SymanticsError(function, "function "+function.name+" already defined at "+str(oldFunction.start)))
378
379 if len(errors):
380 raise ErrorException(errors)
381
382 def __str__(self):
383 return self.name+"("+string.join(map(lambda a: str(a), self.functionList), ", ")+")"
384
385class Program(object):
386
387 def __init__(self, symbols=None, name="", definitions=None, serviceMap=None, typedefMap=None, enumMap=None, structMap=None, collectionMap=None,
388 primitiveMap=None):
389
390 self.name = name
391
392 if not definitions:
393 definitions = []
394 self.definitions = definitions
395
396 if not serviceMap:
397 serviceMap = {}
398 self.serviceMap = serviceMap
399
400 if not typedefMap:
401 typedefMap = {}
402 self.typedefMap = typedefMap
403
404 if not enumMap:
405 enumMap = {}
406 self.enumMap = enumMap
407
408 if not structMap:
409 structMap = {}
410 self.structMap = structMap
411
412 if not collectionMap:
413 collectionMap = {}
414 self.collectionMap = collectionMap
415
416 if not primitiveMap:
417 primitiveMap = PRIMITIVE_MAP
418 self.primitiveMap = primitiveMap
419
420 def addDefinition(self, definition, definitionMap, definitionTypeName):
421
422 oldDefinition = definitionMap.get(definition.name)
423 if oldDefinition:
424 raise ErrorException([SymanticsError(definition, definitionTypeName+" "+definition.name+" is already defined at "+str(oldDefinition.start))])
425 else:
426 definitionMap[definition.name] = definition
427
428 # keep an ordered list of definitions so that stub/skel generators can determine the original order
429
430 self.definitions.append(definition)
431
432 def addStruct(self, struct):
433 self.addDefinition(struct, self.structMap, "struct")
434
435 def addTypedef(self, typedef):
436 self.addDefinition(typedef, self.typedefMap, "typedef")
437
438 def addEnum(self, enum):
439 self.addDefinition(enum, self.enumMap, "enum")
440
441 def addService(self, service):
442 self.addDefinition(service, self.serviceMap, "service")
443
444 def addCollection(self, collection):
445 if collection.name in self.collectionMap:
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000446 return self.collectionMap[collection.name]
Marc Slemkob2039e72006-08-09 01:00:17 +0000447 else:
448 self.collectionMap[collection.name] = collection
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000449 return collection
Marc Slemkob2039e72006-08-09 01:00:17 +0000450
451 def getType(self, parent, symbol):
452 """ Get the type definition for a symbol"""
453
454 typeName = None
455
456 if isinstance(symbol, Type):
457 return symbol
458 elif isinstance(symbol, Field):
459 typeName = symbol.type.name
460 elif isinstance(symbol, Identifier):
461 typeName = symbol.name
462 else:
463 raise ErrorException([SymanticsError(parent, "unknown symbol \""+str(symbol)+"\"")])
464
465 for map in (self.primitiveMap, self.collectionMap, self.typedefMap, self.enumMap, self.structMap):
466 if typeName in map:
467 return map[typeName]
468
469 raise ErrorException([SymanticsError(parent, "\""+typeName+"\" is not defined.")])
470
471 def hasType(self, parent, symbol):
472 """ Determine if a type definition exists for the symbol"""
473
474 return self.getType(parent, symbol) == True
475
476 def validate(self):
477
478 errors = []
479
480 # Verify that struct fields types, collection key and element types, and typedef defined types exists and replaces
481 # type names with references to the type objects
482
483 for struct in self.structMap.values():
484 for field in struct.fieldList:
485 try:
486 field.type = self.getType(struct, field)
487 except ErrorException, e:
488 errors+= e.errors
489
490 for collection in self.collectionMap.values():
491 try:
Marc Slemko5b126d62006-08-11 23:03:42 +0000492 if isinstance(collection, MapType):
Marc Slemkob2039e72006-08-09 01:00:17 +0000493 collection.keyType = self.getType(collection, collection.keyType)
494
495 collection.valueType = self.getType(collection, collection.valueType)
Marc Slemko27340eb2006-08-10 20:45:55 +0000496
497 collection.validate()
Marc Slemkob2039e72006-08-09 01:00:17 +0000498
499 except ErrorException, e:
500 errors+= e.errors
501
502 for typedef in self.typedefMap.values():
503 try:
504 typedef.definitionType = self.getType(self, typedef.definitionType)
505
506 except ErrorException, e:
507 errors+= e.errors
508
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000509 # 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 +0000510
511 for service in self.serviceMap.values():
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000512
Marc Slemkob2039e72006-08-09 01:00:17 +0000513 for function in service.functionList:
Marc Slemko5b126d62006-08-11 23:03:42 +0000514
515 for field in function.resultStruct.fieldList:
516 try:
517 field.type = self.getType(function, field)
518 except ErrorException, e:
519 errors+= e.errors
Marc Slemkob2039e72006-08-09 01:00:17 +0000520
Marc Slemko0b4ffa92006-08-11 02:49:29 +0000521 for field in function.argsStruct.fieldList:
Marc Slemkob2039e72006-08-09 01:00:17 +0000522 try:
523 field.type = self.getType(function, field)
524 except ErrorException, e:
525 errors+= e.errors
526
527 if len(errors):
528 raise ErrorException(errors)
Marc Slemkob2039e72006-08-09 01:00:17 +0000529
530class Parser(object):
531
532 reserved = ("BYTE",
533 # "CONST",
534 "DOUBLE",
535 "ENUM",
Marc Slemkod8b10512006-08-14 23:30:37 +0000536 "EXCEPTION",
Marc Slemkob2039e72006-08-09 01:00:17 +0000537 # "EXTENDS",
538 "I08",
539 "I16",
540 "I32",
541 "I64",
542 "LIST",
543 "MAP",
544 "SERVICE",
545 "SET",
546 # "STATIC",
547 "STRING",
548 "STRUCT",
549 # "SYNCHRONIZED",
Marc Slemkod8b10512006-08-14 23:30:37 +0000550 "THROWS",
Marc Slemkob2039e72006-08-09 01:00:17 +0000551 "TYPEDEF",
552 "U08",
553 "U16",
554 "U32",
555 "U64",
556 "UTF16",
557 "UTF8",
558 "VOID"
559 )
560
561 tokens = reserved + (
562 # Literals (identifier, integer constant, float constant, string constant, char const)
563 'ID', 'ICONST', 'SCONST', 'FCONST',
564 # Operators default=, optional*, variable...
565 'ASSIGN', #'OPTIONAL', 'ELLIPSIS',
566 # Delimeters ( ) { } < > , . ; :
567 'LPAREN', 'RPAREN',
568 'LBRACE', 'RBRACE',
569 'LANGLE', 'RANGLE',
570 'COMMA' #, 'PERIOD', 'SEMI' , 'COLON'
571 )
572
573 precendence = ()
574
575 reserved_map = {}
576
577 for r in reserved:
578 reserved_map[r.lower()] = r
579
580 def t_ID(self, t):
581 r'[A-Za-z_][\w_]*'
582 t.type = self.reserved_map.get(t.value,"ID")
583 return t
584
585 # Completely ignored characters
586 t_ignore = ' \t\x0c'
587
588# t_OPTIONAL = r'\*'
589 t_ASSIGN = r'='
590
591 # Delimeters
592 t_LPAREN = r'\('
593 t_RPAREN = r'\)'
594 t_LANGLE = r'\<'
595 t_RANGLE = r'\>'
596 t_LBRACE = r'\{'
597 t_RBRACE = r'\}'
598 t_COMMA = r','
599# t_PERIOD = r'\.'
600# t_SEMI = r';'
601# t_COLON = r':'
602# t_ELLIPSIS = r'\.\.\.'
603
604 # Integer literal
605 t_ICONST = r'\d+([uU]|[lL]|[uU][lL]|[lL][uU])?'
606
607 # Floating literal
608 t_FCONST = r'((\d+)(\.\d+)(e(\+|-)?(\d+))? | (\d+)e(\+|-)?(\d+))([lL]|[fF])?'
609
610 # String literal
611 t_SCONST = r'\"([^\\\n]|(\\.))*?\"'
612
613 # Comments
614 def t_comment(self, t):
615 r'(?:/\*(.|\n)*?\*/)|(?://[^\n]*\n)'
616 t.lineno += t.value.count('\n')
617
618 def t_error(self, t):
619 print "Illegal character %s" % repr(t.value[0])
620 t.skip(1)
621
622 # Newlines
623 def t_newline(self, t):
624 r'\n+'
625 t.lineno += t.value.count("\n")
626
627 def p_program(self, p):
628 'program : definitionlist'
629 pass
630
631 def p_definitionlist_1(self, p):
632 'definitionlist : definitionlist definition'
633 pass
634
635 def p_definitionlist_2(self, p):
636 'definitionlist :'
637 pass
638
639 def p_definition_1(self, p):
640 'definition : typedef'
641 self.pdebug("p_definition_1", p)
642 p[0] = p[1]
643 try:
644 self.program.addTypedef(p[0])
645 except ErrorException, e:
646 self.errors+= e.errors
647
648 def p_definition_2(self, p):
649 'definition : enum'
650 self.pdebug("p_definition_2", p)
651 p[0] = p[1]
652 try:
653 self.program.addEnum(p[0])
654 except ErrorException, e:
655 self.errors+= e.errors
656
657 def p_definition_3(self, p):
658 'definition : struct'
659 self.pdebug("p_definition_3", p)
660 p[0] = p[1]
661 try:
662 self.program.addStruct(p[0])
663 except ErrorException, e:
664 self.errors+= e.errors
665
666 def p_definition_4(self, p):
667 'definition : service'
668 self.pdebug("p_definition_4", p)
669 p[0] = p[1]
670 try:
671 self.program.addService(p[0])
672 except ErrorException, e:
673 self.errors+= e.errors
674
Marc Slemkod8b10512006-08-14 23:30:37 +0000675 def p_definition_5(self, p):
676 'definition : exception'
677 self.pdebug("p_definition_5", p)
678 p[0] = p[1]
679 try:
680 self.program.addStruct(p[0])
681 except ErrorException, e:
682 self.errors+= e.errors
683
Marc Slemkob2039e72006-08-09 01:00:17 +0000684 def p_typedef(self, p):
685 'typedef : TYPEDEF definitiontype ID'
686 self.pdebug("p_typedef", p)
Marc Slemko5b126d62006-08-11 23:03:42 +0000687 p[0] = TypedefType(p, p[3], p[2])
Marc Slemkob2039e72006-08-09 01:00:17 +0000688 try:
689 p[0].validate()
690
691 except ErrorException, e:
692 self.errors+= e.errors
693
Marc Slemkob2039e72006-08-09 01:00:17 +0000694 def p_enum(self, p):
695 'enum : ENUM ID LBRACE enumdeflist RBRACE'
696 self.pdebug("p_enum", p)
Marc Slemko5b126d62006-08-11 23:03:42 +0000697 p[0] = EnumType(p, p[2], p[4])
Marc Slemkob2039e72006-08-09 01:00:17 +0000698
699 try:
700 p[0].validate()
701 except ErrorException, e:
702 self.errors+= e.errors
703
704 def p_enumdeflist_1(self, p):
705 'enumdeflist : enumdeflist COMMA enumdef'
706 self.pdebug("p_enumdeflist_1", p)
707 p[0] = p[1] + (p[3],)
708
709 def p_enumdeflist_2(self, p):
710 'enumdeflist : enumdef'
711 self.pdebug("p_enumdeflist_2", p)
712 p[0] = (p[1],)
713
714 def p_enumdef_0(self, p):
715 'enumdef : ID ASSIGN ICONST'
716 self.pdebug("p_enumdef_0", p)
717 p[0] = EnumDef(p, p[1], int(p[3]))
718
719 def p_enumdef_1(self, p):
720 'enumdef : ID'
721 self.pdebug("p_enumdef_1", p)
722 p[0] = EnumDef(p, p[1])
723
724 def p_struct(self, p):
725 'struct : STRUCT ID LBRACE fieldlist RBRACE'
726 self.pdebug("p_struct", p)
Marc Slemko5b126d62006-08-11 23:03:42 +0000727 p[0] = StructType(p, p[2], p[4])
Marc Slemkob2039e72006-08-09 01:00:17 +0000728
729 try:
730 p[0].validate()
731 except ErrorException, e:
732 self.errors+= e.errors
733
Marc Slemkod8b10512006-08-14 23:30:37 +0000734 def p_exception(self, p):
735 'exception : EXCEPTION ID LBRACE fieldlist RBRACE'
736 self.pdebug("p_struct", p)
737 p[0] = ExceptionType(p, p[2], p[4])
738
739 try:
740 p[0].validate()
741 except ErrorException, e:
742 self.errors+= e.errors
743
Marc Slemkob2039e72006-08-09 01:00:17 +0000744 def p_service(self, p):
745 'service : SERVICE ID LBRACE functionlist RBRACE'
746 self.pdebug("p_service", p)
747 p[0] = Service(p, p[2], p[4])
748 try:
749 p[0].validate()
750 except ErrorException, e:
751 self.errors+= e.errors
752
753 def p_functionlist_1(self, p):
Marc Slemkod8b10512006-08-14 23:30:37 +0000754 'functionlist : function COMMA functionlist'
Marc Slemkob2039e72006-08-09 01:00:17 +0000755 self.pdebug("p_functionlist_1", p)
Marc Slemkod8b10512006-08-14 23:30:37 +0000756 p[0] = (p[1],) + p[3]
Marc Slemkob2039e72006-08-09 01:00:17 +0000757
758 def p_functionlist_2(self, p):
Marc Slemkod8b10512006-08-14 23:30:37 +0000759 'functionlist : function'
Marc Slemkob2039e72006-08-09 01:00:17 +0000760 self.pdebug("p_functionlist_2", p)
Marc Slemkod8b10512006-08-14 23:30:37 +0000761 p[0] = (p[1],)
762
763 def p_functionlist_3(self, p):
764 'functionlist : '
765 self.pdebug("p_functionlist_3", p)
Marc Slemkob2039e72006-08-09 01:00:17 +0000766 p[0] = ()
767
768 def p_function(self, p):
Marc Slemkod8b10512006-08-14 23:30:37 +0000769 'function : functiontype functionmodifiers ID LPAREN fieldlist RPAREN exceptionspecifier'
Marc Slemkob2039e72006-08-09 01:00:17 +0000770 self.pdebug("p_function", p)
Marc Slemko5b126d62006-08-11 23:03:42 +0000771
Marc Slemkod8b10512006-08-14 23:30:37 +0000772 resultStruct = StructType(p, p[3]+"_result", (Field(p, p[1], Identifier(None, "success", 0)),)+p[7])
Marc Slemko5b126d62006-08-11 23:03:42 +0000773
774 p[0] = Function(p, p[3], resultStruct, StructType(p, p[3]+"_args", p[5]))
Marc Slemkob2039e72006-08-09 01:00:17 +0000775 try:
776 p[0].validate()
777 except ErrorException, e:
778 self.errors+= e.errors
779
780 def p_functionmodifiers(self, p):
781 'functionmodifiers :'
782 self.pdebug("p_functionmodifiers", p)
783 p[0] = ()
784
785 def p_fieldlist_1(self, p):
Marc Slemkod8b10512006-08-14 23:30:37 +0000786 'fieldlist : field COMMA fieldlist'
Marc Slemkob2039e72006-08-09 01:00:17 +0000787 self.pdebug("p_fieldlist_1", p)
Marc Slemkod8b10512006-08-14 23:30:37 +0000788 p[0] = (p[1],) + p[3]
Marc Slemkob2039e72006-08-09 01:00:17 +0000789
790 def p_fieldlist_2(self, p):
791 'fieldlist : field'
792 self.pdebug("p_fieldlist_2", p)
793 p[0] = (p[1],)
794
795 def p_fieldlist_3(self, p):
796 'fieldlist :'
797 self.pdebug("p_fieldlist_3", p)
798 p[0] = ()
799
800 def p_field_1(self, p):
801 'field : fieldtype ID ASSIGN ICONST'
802 self.pdebug("p_field_1", p)
803 p[0] = Field(p, p[1], Identifier(None, p[2], int(p[4])))
804
805 def p_field_2(self, p):
806 'field : fieldtype ID'
807 self.pdebug("p_field_2", p)
808 p[0] = Field(p, p[1], Identifier(None, p[2]))
809
Marc Slemkod8b10512006-08-14 23:30:37 +0000810 def p_exceptionSpecifier_1(self, p):
811 'exceptionspecifier : THROWS LPAREN fieldlist RPAREN'
812 self.pdebug("p_exceptionspecifier", p)
813 p[0] = p[3]
814
815 def p_exceptionSpecifier_2(self, p):
816 'exceptionspecifier : empty'
817 self.pdebug("p_exceptionspecifier", p)
818 p[0] = ()
819
Marc Slemkob2039e72006-08-09 01:00:17 +0000820 def p_definitiontype_1(self, p):
821 'definitiontype : basetype'
822 self.pdebug("p_definitiontype_1", p)
823 p[0] = p[1]
824
825 def p_definitiontype_2(self, p):
826 'definitiontype : collectiontype'
827 self.pdebug("p_definitiontype_2", p)
828 p[0] = p[1]
829
830 def p_functiontype_1(self, p):
831 'functiontype : fieldtype'
832 self.pdebug("p_functiontype_1", p)
833 p[0] = p[1]
834
835 def p_functiontype_2(self, p):
836 'functiontype : VOID'
837 self.pdebug("p_functiontype_2", p)
838 p[0] = self.program.primitiveMap[p[1].lower()]
839
840 def p_fieldtype_1(self, p):
841 'fieldtype : ID'
842 self.pdebug("p_fieldtype_1", p)
843 p[0] = Identifier(p, p[1])
844
845 def p_fieldtype_2(self, p):
846 'fieldtype : basetype'
847 self.pdebug("p_fieldtype_2", p)
848 p[0] = p[1]
849
850 def p_fieldtype_3(self, p):
851 'fieldtype : collectiontype'
852 self.pdebug("p_fieldtype_3", p)
853 p[0] = p[1]
854
855 def p_basetype_1(self, p):
856 'basetype : STRING'
857 self.pdebug("p_basetype_1", p)
858 p[0] = self.program.primitiveMap[p[1].lower()]
859
860 def p_basetype_2(self, p):
861 'basetype : BYTE'
862 self.pdebug("p_basetype_2", p)
863 p[0] = self.program.primitiveMap[p[1].lower()]
864
865 def p_basetype_3(self, p):
866 'basetype : I08'
867 self.pdebug("p_basetype_3", p)
868 p[0] = self.program.primitiveMap[p[1].lower()]
869
870 def p_basetype_4(self, p):
871 'basetype : U08'
872 self.pdebug("p_basetype_4", p)
873 p[0] = self.program.primitiveMap[p[1].lower()]
874
875 def p_basetype_5(self, p):
876 'basetype : I16'
877 self.pdebug("p_basetype_5", p)
878 p[0] = self.program.primitiveMap[p[1].lower()]
879
880 def p_basetype_6(self, p):
881 'basetype : U16'
882 self.pdebug("p_basetype_6", p)
883 p[0] = self.program.primitiveMap[p[1].lower()]
884
885 def p_basetype_7(self, p):
886 'basetype : I32'
887 self.pdebug("p_basetype_7", p)
888 p[0] = self.program.primitiveMap[p[1].lower()]
889
890 def p_basetype_8(self, p):
891 'basetype : U32'
892 self.pdebug("p_basetype_8", p)
893 p[0] = self.program.primitiveMap[p[1].lower()]
894
895 def p_basetype_9(self, p):
896 'basetype : I64'
897 self.pdebug("p_basetype_9", p)
898 p[0] = self.program.primitiveMap[p[1].lower()]
899
900 def p_basetype_10(self, p):
901 'basetype : U64'
902 self.pdebug("p_basetype_10", p)
903 p[0] = self.program.primitiveMap[p[1].lower()]
904
905 def p_basetype_11(self, p):
906 'basetype : UTF8'
907 self.pdebug("p_basetype_11", p)
908 p[0] = self.program.primitiveMap[p[1].lower()]
909
910 def p_basetype_12(self, p):
911 'basetype : UTF16'
912 self.pdebug("p_basetype_12", p)
913 p[0] = self.program.primitiveMap[p[1].lower()]
914
915 def p_basetype_13(self, p):
916 'basetype : DOUBLE'
917 self.pdebug("p_basetype_13", p)
918 p[0] = self.program.primitiveMap[p[1].lower()]
919
920 def p_collectiontype_1(self, p):
921 'collectiontype : maptype'
922 self.pdebug("p_collectiontype_1", p)
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000923 p[0] = self.program.addCollection(p[1])
Marc Slemkob2039e72006-08-09 01:00:17 +0000924
925 def p_collectiontype_2(self, p):
926 'collectiontype : settype'
927 self.pdebug("p_collectiontype_2", p)
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000928 p[0] = self.program.addCollection(p[1])
Marc Slemkob2039e72006-08-09 01:00:17 +0000929
930 def p_collectiontype_3(self, p):
931 'collectiontype : listtype'
932 self.pdebug("p_collectiontype_3", p)
Marc Slemkoc0e07a22006-08-09 23:34:57 +0000933 p[0] = self.program.addCollection(p[1])
Marc Slemkob2039e72006-08-09 01:00:17 +0000934
935 def p_maptype(self, p):
936 'maptype : MAP LANGLE fieldtype COMMA fieldtype RANGLE'
937 self.pdebug("p_maptype", p)
Marc Slemko5b126d62006-08-11 23:03:42 +0000938 p[0] = MapType(p, p[3], p[5])
Marc Slemkob2039e72006-08-09 01:00:17 +0000939
940 def p_settype(self, p):
941 'settype : SET LANGLE fieldtype RANGLE'
942 self.pdebug("p_settype", p)
Marc Slemko5b126d62006-08-11 23:03:42 +0000943 p[0] = SetType(p, p[3])
Marc Slemkob2039e72006-08-09 01:00:17 +0000944
945 def p_listtype(self, p):
946 'listtype : LIST LANGLE fieldtype RANGLE'
947 self.pdebug("p_listtype", p)
Marc Slemko5b126d62006-08-11 23:03:42 +0000948 p[0] = ListType(p, p[3])
Marc Slemkob2039e72006-08-09 01:00:17 +0000949
Marc Slemkod8b10512006-08-14 23:30:37 +0000950 def p_empty(self, p):
951 "empty : "
952 pass
953
Marc Slemkob2039e72006-08-09 01:00:17 +0000954 def p_error(self, p):
Marc Slemko27340eb2006-08-10 20:45:55 +0000955 # p_error is called with an empty token if eof was encountered unexpectedly.
956 if not p:
957 self.errors.append(SyntaxError("Unexpected end of file"))
958 else:
959 self.errors.append(SyntaxError(p))
Marc Slemkob2039e72006-08-09 01:00:17 +0000960
961 def pdebug(self, name, p):
962 if self.debug:
Marc Slemkod8b10512006-08-14 23:30:37 +0000963 print(name+"("+string.join(["P["+str(ix)+"]<<"+str(p[ix])+">>" for ix in range(len(p))], ", ")+")")
Marc Slemkob2039e72006-08-09 01:00:17 +0000964
965 def __init__(self, **kw):
966 self.debug = kw.get('debug', 0)
967 self.names = { }
968 self.program = Program()
969 self.errors = []
970
971 try:
972 modname = os.path.split(os.path.splitext(__file__)[0])[1] + "_" + self.__class__.__name__
973 except:
974 modname = "parser"+"_"+self.__class__.__name__
975 self.debugfile = modname + ".dbg"
976 self.tabmodule = modname + "_" + "parsetab"
977 #print self.debugfile, self.tabmodule
978
979 # Build the lexer and parser
980 lex.lex(module=self, debug=self.debug)
981 yacc.yacc(module=self,
982 debug=self.debug,
983 debugfile=self.debugfile,
984 tabmodule=self.tabmodule)
985
986 def parsestring(self, s, filename=""):
987 yacc.parse(s)
988
989 if len(self.errors) == 0:
990 try:
991 self.program.validate()
992 except ErrorException, e:
993 self.errors+= e.errors
994
995 if len(self.errors):
996 for error in self.errors:
997 print(filename+":"+str(error))
998
999 def parse(self, filename, doPickle=True):
1000
1001 f = file(filename, "r")
1002
1003 self.parsestring(f.read(), filename)
1004
1005 if len(self.errors) == 0 and doPickle:
1006
1007 outf = file(os.path.splitext(filename)[0]+".thyc", "w")
1008
1009 pickle.dump(self.program, outf)