Fix protoc plugin path
[apps/agl-service-can-low-level.git] / generator / nanopb_generator.py
1 #!/usr/bin/python
2
3 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 nanopb_version = "nanopb-0.2.5-dev"
5
6 try:
7     import google, distutils.util # bbfreeze seems to need these
8     import google.protobuf.text_format as text_format
9 except:
10     print
11     print "*************************************************************"
12     print "*** Could not import the Google protobuf Python libraries ***"
13     print "*** Try installing package 'python-protobuf' or similar.  ***"
14     print "*************************************************************"
15     print
16     raise
17
18 try:
19     import proto.nanopb_pb2 as nanopb_pb2
20     import proto.descriptor_pb2 as descriptor
21 except:
22     print
23     print "********************************************************************"
24     print "*** Failed to import the protocol definitions for generator.     ***"
25     print "*** You have to run 'make' in the nanopb/generator/proto folder. ***"
26     print "********************************************************************"
27     print
28     raise
29
30
31 # ---------------------------------------------------------------------------
32 #                     Generation of single fields
33 # ---------------------------------------------------------------------------
34
35 import time
36 import os.path
37
38 # Values are tuple (c type, pb type, encoded size)
39 FieldD = descriptor.FieldDescriptorProto
40 datatypes = {
41     FieldD.TYPE_BOOL:       ('bool',     'BOOL',        1),
42     FieldD.TYPE_DOUBLE:     ('double',   'DOUBLE',      8),
43     FieldD.TYPE_FIXED32:    ('uint32_t', 'FIXED32',     4),
44     FieldD.TYPE_FIXED64:    ('uint64_t', 'FIXED64',     8),
45     FieldD.TYPE_FLOAT:      ('float',    'FLOAT',       4),
46     FieldD.TYPE_INT32:      ('int32_t',  'INT32',      10),
47     FieldD.TYPE_INT64:      ('int64_t',  'INT64',      10),
48     FieldD.TYPE_SFIXED32:   ('int32_t',  'SFIXED32',    4),
49     FieldD.TYPE_SFIXED64:   ('int64_t',  'SFIXED64',    8),
50     FieldD.TYPE_SINT32:     ('int32_t',  'SINT32',      5),
51     FieldD.TYPE_SINT64:     ('int64_t',  'SINT64',     10),
52     FieldD.TYPE_UINT32:     ('uint32_t', 'UINT32',      5),
53     FieldD.TYPE_UINT64:     ('uint64_t', 'UINT64',     10)
54 }
55
56 class Names:
57     '''Keeps a set of nested names and formats them to C identifier.'''
58     def __init__(self, parts = ()):
59         if isinstance(parts, Names):
60             parts = parts.parts
61         self.parts = tuple(parts)
62     
63     def __str__(self):
64         return '_'.join(self.parts)
65
66     def __add__(self, other):
67         if isinstance(other, (str, unicode)):
68             return Names(self.parts + (other,))
69         elif isinstance(other, tuple):
70             return Names(self.parts + other)
71         else:
72             raise ValueError("Name parts should be of type str")
73     
74     def __eq__(self, other):
75         return isinstance(other, Names) and self.parts == other.parts
76     
77 def names_from_type_name(type_name):
78     '''Parse Names() from FieldDescriptorProto type_name'''
79     if type_name[0] != '.':
80         raise NotImplementedError("Lookup of non-absolute type names is not supported")
81     return Names(type_name[1:].split('.'))
82
83 def varint_max_size(max_value):
84     '''Returns the maximum number of bytes a varint can take when encoded.'''
85     for i in range(1, 11):
86         if (max_value >> (i * 7)) == 0:
87             return i
88     raise ValueError("Value too large for varint: " + str(max_value))
89
90 assert varint_max_size(0) == 1
91 assert varint_max_size(127) == 1
92 assert varint_max_size(128) == 2
93
94 class EncodedSize:
95     '''Class used to represent the encoded size of a field or a message.
96     Consists of a combination of symbolic sizes and integer sizes.'''
97     def __init__(self, value = 0, symbols = []):
98         if isinstance(value, (str, Names)):
99             symbols = [str(value)]
100             value = 0
101         self.value = value
102         self.symbols = symbols
103     
104     def __add__(self, other):
105         if isinstance(other, (int, long)):
106             return EncodedSize(self.value + other, self.symbols)
107         elif isinstance(other, (str, Names)):
108             return EncodedSize(self.value, self.symbols + [str(other)])
109         elif isinstance(other, EncodedSize):
110             return EncodedSize(self.value + other.value, self.symbols + other.symbols)
111         else:
112             raise ValueError("Cannot add size: " + repr(other))
113
114     def __mul__(self, other):
115         if isinstance(other, (int, long)):
116             return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
117         else:
118             raise ValueError("Cannot multiply size: " + repr(other))
119
120     def __str__(self):
121         if not self.symbols:
122             return str(self.value)
123         else:
124             return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
125
126     def upperlimit(self):
127         if not self.symbols:
128             return self.value
129         else:
130             return 2**32 - 1
131
132 class Enum:
133     def __init__(self, names, desc, enum_options):
134         '''desc is EnumDescriptorProto'''
135         
136         self.options = enum_options
137         self.names = names + desc.name
138         
139         if enum_options.long_names:
140             self.values = [(self.names + x.name, x.number) for x in desc.value]            
141         else:
142             self.values = [(names + x.name, x.number) for x in desc.value] 
143         
144         self.value_longnames = [self.names + x.name for x in desc.value]
145     
146     def __str__(self):
147         result = 'typedef enum _%s {\n' % self.names
148         result += ',\n'.join(["    %s = %d" % x for x in self.values])
149         result += '\n} %s;' % self.names
150         return result
151
152 class Field:
153     def __init__(self, struct_name, desc, field_options):
154         '''desc is FieldDescriptorProto'''
155         self.tag = desc.number
156         self.struct_name = struct_name
157         self.name = desc.name
158         self.default = None
159         self.max_size = None
160         self.max_count = None
161         self.array_decl = ""
162         self.enc_size = None
163         
164         # Parse field options
165         if field_options.HasField("max_size"):
166             self.max_size = field_options.max_size
167         
168         if field_options.HasField("max_count"):
169             self.max_count = field_options.max_count
170         
171         if desc.HasField('default_value'):
172             self.default = desc.default_value
173            
174         # Check field rules, i.e. required/optional/repeated.
175         can_be_static = True
176         if desc.label == FieldD.LABEL_REQUIRED:
177             self.rules = 'REQUIRED'
178         elif desc.label == FieldD.LABEL_OPTIONAL:
179             self.rules = 'OPTIONAL'
180         elif desc.label == FieldD.LABEL_REPEATED:
181             self.rules = 'REPEATED'
182             if self.max_count is None:
183                 can_be_static = False
184             else:
185                 self.array_decl = '[%d]' % self.max_count
186         else:
187             raise NotImplementedError(desc.label)
188         
189         # Check if the field can be implemented with static allocation
190         # i.e. whether the data size is known.
191         if desc.type == FieldD.TYPE_STRING and self.max_size is None:
192             can_be_static = False
193         
194         if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
195             can_be_static = False
196         
197         # Decide how the field data will be allocated
198         if field_options.type == nanopb_pb2.FT_DEFAULT:
199             if can_be_static:
200                 field_options.type = nanopb_pb2.FT_STATIC
201             else:
202                 field_options.type = nanopb_pb2.FT_CALLBACK
203         
204         if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
205             raise Exception("Field %s is defined as static, but max_size or "
206                             "max_count is not given." % self.name)
207         
208         if field_options.type == nanopb_pb2.FT_STATIC:
209             self.allocation = 'STATIC'
210         elif field_options.type == nanopb_pb2.FT_POINTER:
211             self.allocation = 'POINTER'
212         elif field_options.type == nanopb_pb2.FT_CALLBACK:
213             self.allocation = 'CALLBACK'
214         else:
215             raise NotImplementedError(field_options.type)
216         
217         # Decide the C data type to use in the struct.
218         if datatypes.has_key(desc.type):
219             self.ctype, self.pbtype, self.enc_size = datatypes[desc.type]
220         elif desc.type == FieldD.TYPE_ENUM:
221             self.pbtype = 'ENUM'
222             self.ctype = names_from_type_name(desc.type_name)
223             if self.default is not None:
224                 self.default = self.ctype + self.default
225             self.enc_size = 5 # protoc rejects enum values > 32 bits
226         elif desc.type == FieldD.TYPE_STRING:
227             self.pbtype = 'STRING'
228             self.ctype = 'char'
229             if self.allocation == 'STATIC':
230                 self.ctype = 'char'
231                 self.array_decl += '[%d]' % self.max_size
232                 self.enc_size = varint_max_size(self.max_size) + self.max_size
233         elif desc.type == FieldD.TYPE_BYTES:
234             self.pbtype = 'BYTES'
235             if self.allocation == 'STATIC':
236                 self.ctype = self.struct_name + self.name + 't'
237                 self.enc_size = varint_max_size(self.max_size) + self.max_size
238             elif self.allocation == 'POINTER':
239                 self.ctype = 'pb_bytes_ptr_t'
240         elif desc.type == FieldD.TYPE_MESSAGE:
241             self.pbtype = 'MESSAGE'
242             self.ctype = self.submsgname = names_from_type_name(desc.type_name)
243             self.enc_size = None # Needs to be filled in after the message type is available
244         else:
245             raise NotImplementedError(desc.type)
246         
247     def __cmp__(self, other):
248         return cmp(self.tag, other.tag)
249     
250     def __str__(self):
251         result = ''
252         if self.allocation == 'POINTER':
253             if self.rules == 'REPEATED':
254                 result += '    size_t ' + self.name + '_count;\n'
255             
256             if self.pbtype == 'MESSAGE':
257                 # Use struct definition, so recursive submessages are possible
258                 result += '    struct _%s *%s;' % (self.ctype, self.name)
259             elif self.rules == 'REPEATED' and self.pbtype == 'STRING':
260                 # String arrays need to be defined as pointers to pointers
261                 result += '    %s **%s;' % (self.ctype, self.name)
262             else:
263                 result += '    %s *%s;' % (self.ctype, self.name)
264         elif self.allocation == 'CALLBACK':
265             result += '    pb_callback_t %s;' % self.name
266         else:
267             if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
268                 result += '    bool has_' + self.name + ';\n'
269             elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
270                 result += '    size_t ' + self.name + '_count;\n'
271             result += '    %s %s%s;' % (self.ctype, self.name, self.array_decl)
272         return result
273     
274     def types(self):
275         '''Return definitions for any special types this field might need.'''
276         if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
277             result = 'typedef struct {\n'
278             result += '    size_t size;\n'
279             result += '    uint8_t bytes[%d];\n' % self.max_size
280             result += '} %s;\n' % self.ctype
281         else:
282             result = None
283         return result
284     
285     def default_decl(self, declaration_only = False):
286         '''Return definition for this field's default value.'''
287         if self.default is None:
288             return None
289
290         ctype, default = self.ctype, self.default
291         array_decl = ''
292         
293         if self.pbtype == 'STRING':
294             if self.allocation != 'STATIC':
295                 return None # Not implemented
296         
297             array_decl = '[%d]' % self.max_size
298             default = str(self.default).encode('string_escape')
299             default = default.replace('"', '\\"')
300             default = '"' + default + '"'
301         elif self.pbtype == 'BYTES':
302             if self.allocation != 'STATIC':
303                 return None # Not implemented
304
305             data = self.default.decode('string_escape')
306             data = ['0x%02x' % ord(c) for c in data]
307             default = '{%d, {%s}}' % (len(data), ','.join(data))
308         
309         if declaration_only:
310             return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
311         else:
312             return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
313     
314     def tags(self):
315         '''Return the #define for the tag number of this field.'''
316         identifier = '%s_%s_tag' % (self.struct_name, self.name)
317         return '#define %-40s %d\n' % (identifier, self.tag)
318     
319     def pb_field_t(self, prev_field_name):
320         '''Return the pb_field_t initializer to use in the constant array.
321         prev_field_name is the name of the previous field or None.
322         '''
323         result  = '    PB_FIELD2(%3d, ' % self.tag
324         result += '%-8s, ' % self.pbtype
325         result += '%s, ' % self.rules
326         result += '%-8s, ' % self.allocation
327         result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
328         result += '%s, ' % self.struct_name
329         result += '%s, ' % self.name
330         result += '%s, ' % (prev_field_name or self.name)
331         
332         if self.pbtype == 'MESSAGE':
333             result += '&%s_fields)' % self.submsgname
334         elif self.default is None:
335             result += '0)'
336         elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
337             result += '0)' # Arbitrary size default values not implemented
338         else:
339             result += '&%s_default)' % (self.struct_name + self.name)
340         
341         return result
342     
343     def largest_field_value(self):
344         '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
345         Returns numeric value or a C-expression for assert.'''
346         if self.pbtype == 'MESSAGE':
347             if self.rules == 'REPEATED' and self.allocation == 'STATIC':
348                 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
349             else:
350                 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
351
352         return max(self.tag, self.max_size, self.max_count)        
353
354     def encoded_size(self, allmsgs):
355         '''Return the maximum size that this field can take when encoded,
356         including the field tag. If the size cannot be determined, returns
357         None.'''
358         
359         if self.allocation != 'STATIC':
360             return None
361         
362         if self.pbtype == 'MESSAGE':
363             for msg in allmsgs:
364                 if msg.name == self.submsgname:
365                     encsize = msg.encoded_size(allmsgs)
366                     if encsize is None:
367                         return None # Submessage size is indeterminate
368                         
369                     # Include submessage length prefix
370                     encsize += varint_max_size(encsize.upperlimit())
371                     break
372             else:
373                 # Submessage cannot be found, this currently occurs when
374                 # the submessage type is defined in a different file.
375                 # Instead of direct numeric value, reference the size that
376                 # has been #defined in the other file.
377                 encsize = EncodedSize(self.submsgname + 'size')
378
379                 # We will have to make a conservative assumption on the length
380                 # prefix size, though.
381                 encsize += 5
382
383         elif self.enc_size is None:
384             raise RuntimeError("Could not determine encoded size for %s.%s"
385                                % (self.struct_name, self.name))
386         else:
387             encsize = EncodedSize(self.enc_size)
388         
389         encsize += varint_max_size(self.tag << 3) # Tag + wire type
390
391         if self.rules == 'REPEATED':
392             # Decoders must be always able to handle unpacked arrays.
393             # Therefore we have to reserve space for it, even though
394             # we emit packed arrays ourselves.
395             encsize *= self.max_count
396         
397         return encsize
398
399
400 class ExtensionRange(Field):
401     def __init__(self, struct_name, range_start, field_options):
402         '''Implements a special pb_extension_t* field in an extensible message
403         structure. The range_start signifies the index at which the extensions
404         start. Not necessarily all tags above this are extensions, it is merely
405         a speed optimization.
406         '''
407         self.tag = range_start
408         self.struct_name = struct_name
409         self.name = 'extensions'
410         self.pbtype = 'EXTENSION'
411         self.rules = 'OPTIONAL'
412         self.allocation = 'CALLBACK'
413         self.ctype = 'pb_extension_t'
414         self.array_decl = ''
415         self.default = None
416         self.max_size = 0
417         self.max_count = 0
418         
419     def __str__(self):
420         return '    pb_extension_t *extensions;'
421     
422     def types(self):
423         return None
424     
425     def tags(self):
426         return ''
427         
428     def encoded_size(self, allmsgs):
429         # We exclude extensions from the count, because they cannot be known
430         # until runtime. Other option would be to return None here, but this
431         # way the value remains useful if extensions are not used.
432         return EncodedSize(0)
433
434 class ExtensionField(Field):
435     def __init__(self, struct_name, desc, field_options):
436         self.fullname = struct_name + desc.name
437         self.extendee_name = names_from_type_name(desc.extendee)
438         Field.__init__(self, self.fullname + 'struct', desc, field_options)
439         
440         if self.rules != 'OPTIONAL':
441             self.skip = True
442         else:
443             self.skip = False
444             self.rules = 'OPTEXT'
445
446     def tags(self):
447         '''Return the #define for the tag number of this field.'''
448         identifier = '%s_tag' % self.fullname
449         return '#define %-40s %d\n' % (identifier, self.tag)
450
451     def extension_decl(self):
452         '''Declaration of the extension type in the .pb.h file'''
453         if self.skip:
454             msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
455             msg +='   type of extension fields is currently supported. */\n'
456             return msg
457         
458         return 'extern const pb_extension_type_t %s;\n' % self.fullname
459
460     def extension_def(self):
461         '''Definition of the extension type in the .pb.c file'''
462
463         if self.skip:
464             return ''
465
466         result  = 'typedef struct {\n'
467         result += str(self)
468         result += '\n} %s;\n\n' % self.struct_name
469         result += ('static const pb_field_t %s_field = \n  %s;\n\n' %
470                     (self.fullname, self.pb_field_t(None)))
471         result += 'const pb_extension_type_t %s = {\n' % self.fullname
472         result += '    NULL,\n'
473         result += '    NULL,\n'
474         result += '    &%s_field\n' % self.fullname
475         result += '};\n'
476         return result
477
478
479 # ---------------------------------------------------------------------------
480 #                   Generation of messages (structures)
481 # ---------------------------------------------------------------------------
482
483
484 class Message:
485     def __init__(self, names, desc, message_options):
486         self.name = names
487         self.fields = []
488         
489         for f in desc.field:
490             field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
491             if field_options.type != nanopb_pb2.FT_IGNORE:
492                 self.fields.append(Field(self.name, f, field_options))
493         
494         if len(desc.extension_range) > 0:
495             field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
496             range_start = min([r.start for r in desc.extension_range])
497             if field_options.type != nanopb_pb2.FT_IGNORE:
498                 self.fields.append(ExtensionRange(self.name, range_start, field_options))
499         
500         self.packed = message_options.packed_struct
501         self.ordered_fields = self.fields[:]
502         self.ordered_fields.sort()
503
504     def get_dependencies(self):
505         '''Get list of type names that this structure refers to.'''
506         return [str(field.ctype) for field in self.fields]
507     
508     def __str__(self):
509         result = 'typedef struct _%s {\n' % self.name
510
511         if not self.ordered_fields:
512             # Empty structs are not allowed in C standard.
513             # Therefore add a dummy field if an empty message occurs.
514             result += '    uint8_t dummy_field;'
515
516         result += '\n'.join([str(f) for f in self.ordered_fields])
517         result += '\n}'
518         
519         if self.packed:
520             result += ' pb_packed'
521         
522         result += ' %s;' % self.name
523         
524         if self.packed:
525             result = 'PB_PACKED_STRUCT_START\n' + result
526             result += '\nPB_PACKED_STRUCT_END'
527         
528         return result
529     
530     def types(self):
531         result = ""
532         for field in self.fields:
533             types = field.types()
534             if types is not None:
535                 result += types + '\n'
536         return result
537     
538     def default_decl(self, declaration_only = False):
539         result = ""
540         for field in self.fields:
541             default = field.default_decl(declaration_only)
542             if default is not None:
543                 result += default + '\n'
544         return result
545
546     def fields_declaration(self):
547         result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
548         return result
549
550     def fields_definition(self):
551         result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
552         
553         prev = None
554         for field in self.ordered_fields:
555             result += field.pb_field_t(prev)
556             result += ',\n'
557             prev = field.name
558         
559         result += '    PB_LAST_FIELD\n};'
560         return result
561
562     def encoded_size(self, allmsgs):
563         '''Return the maximum size that this message can take when encoded.
564         If the size cannot be determined, returns None.
565         '''
566         size = EncodedSize(0)
567         for field in self.fields:
568             fsize = field.encoded_size(allmsgs)
569             if fsize is None:
570                 return None
571             size += fsize
572         
573         return size
574
575
576 # ---------------------------------------------------------------------------
577 #                    Processing of entire .proto files
578 # ---------------------------------------------------------------------------
579
580
581 def iterate_messages(desc, names = Names()):
582     '''Recursively find all messages. For each, yield name, DescriptorProto.'''
583     if hasattr(desc, 'message_type'):
584         submsgs = desc.message_type
585     else:
586         submsgs = desc.nested_type
587     
588     for submsg in submsgs:
589         sub_names = names + submsg.name
590         yield sub_names, submsg
591         
592         for x in iterate_messages(submsg, sub_names):
593             yield x
594
595 def iterate_extensions(desc, names = Names()):
596     '''Recursively find all extensions.
597     For each, yield name, FieldDescriptorProto.
598     '''
599     for extension in desc.extension:
600         yield names, extension
601
602     for subname, subdesc in iterate_messages(desc, names):
603         for extension in subdesc.extension:
604             yield subname, extension
605
606 def parse_file(fdesc, file_options):
607     '''Takes a FileDescriptorProto and returns tuple (enums, messages, extensions).'''
608     
609     enums = []
610     messages = []
611     extensions = []
612     
613     if fdesc.package:
614         base_name = Names(fdesc.package.split('.'))
615     else:
616         base_name = Names()
617     
618     for enum in fdesc.enum_type:
619         enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
620         enums.append(Enum(base_name, enum, enum_options))
621     
622     for names, message in iterate_messages(fdesc, base_name):
623         message_options = get_nanopb_suboptions(message, file_options, names)
624         messages.append(Message(names, message, message_options))
625         for enum in message.enum_type:
626             enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
627             enums.append(Enum(names, enum, enum_options))
628     
629     for names, extension in iterate_extensions(fdesc, base_name):
630         field_options = get_nanopb_suboptions(extension, file_options, names)
631         if field_options.type != nanopb_pb2.FT_IGNORE:
632             extensions.append(ExtensionField(names, extension, field_options))
633     
634     # Fix field default values where enum short names are used.
635     for enum in enums:
636         if not enum.options.long_names:
637             for message in messages:
638                 for field in message.fields:
639                     if field.default in enum.value_longnames:
640                         idx = enum.value_longnames.index(field.default)
641                         field.default = enum.values[idx][0]
642     
643     return enums, messages, extensions
644
645 def toposort2(data):
646     '''Topological sort.
647     From http://code.activestate.com/recipes/577413-topological-sort/
648     This function is under the MIT license.
649     '''
650     for k, v in data.items():
651         v.discard(k) # Ignore self dependencies
652     extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
653     data.update(dict([(item, set()) for item in extra_items_in_deps]))
654     while True:
655         ordered = set(item for item,dep in data.items() if not dep)
656         if not ordered:
657             break
658         for item in sorted(ordered):
659             yield item
660         data = dict([(item, (dep - ordered)) for item,dep in data.items()
661                 if item not in ordered])
662     assert not data, "A cyclic dependency exists amongst %r" % data
663
664 def sort_dependencies(messages):
665     '''Sort a list of Messages based on dependencies.'''
666     dependencies = {}
667     message_by_name = {}
668     for message in messages:
669         dependencies[str(message.name)] = set(message.get_dependencies())
670         message_by_name[str(message.name)] = message
671     
672     for msgname in toposort2(dependencies):
673         if msgname in message_by_name:
674             yield message_by_name[msgname]
675
676 def make_identifier(headername):
677     '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
678     result = ""
679     for c in headername.upper():
680         if c.isalnum():
681             result += c
682         else:
683             result += '_'
684     return result
685
686 def generate_header(dependencies, headername, enums, messages, extensions, options):
687     '''Generate content for a header file.
688     Generates strings, which should be concatenated and stored to file.
689     '''
690     
691     yield '/* Automatically generated nanopb header */\n'
692     yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
693     
694     symbol = make_identifier(headername)
695     yield '#ifndef _PB_%s_\n' % symbol
696     yield '#define _PB_%s_\n' % symbol
697     try:
698         yield options.libformat % ('pb.h')
699     except TypeError:
700         # no %s specified - use whatever was passed in as options.libformat
701         yield options.libformat
702     yield '\n'
703     
704     for dependency in dependencies:
705         noext = os.path.splitext(dependency)[0]
706         yield options.genformat % (noext + '.' + options.extension + '.h')
707         yield '\n'
708
709     yield '#ifdef __cplusplus\n'
710     yield 'extern "C" {\n'
711     yield '#endif\n\n'
712     
713     yield '/* Enum definitions */\n'
714     for enum in enums:
715         yield str(enum) + '\n\n'
716     
717     yield '/* Struct definitions */\n'
718     for msg in sort_dependencies(messages):
719         yield msg.types()
720         yield str(msg) + '\n\n'
721     
722     if extensions:
723         yield '/* Extensions */\n'
724         for extension in extensions:
725             yield extension.extension_decl()
726         yield '\n'
727         
728     yield '/* Default values for struct fields */\n'
729     for msg in messages:
730         yield msg.default_decl(True)
731     yield '\n'
732     
733     yield '/* Field tags (for use in manual encoding/decoding) */\n'
734     for msg in sort_dependencies(messages):
735         for field in msg.fields:
736             yield field.tags()
737     for extension in extensions:
738         yield extension.tags()
739     yield '\n'
740     
741     yield '/* Struct field encoding specification for nanopb */\n'
742     for msg in messages:
743         yield msg.fields_declaration() + '\n'
744     yield '\n'
745     
746     yield '/* Maximum encoded size of messages (where known) */\n'
747     for msg in messages:
748         msize = msg.encoded_size(messages)
749         if msize is not None:
750             identifier = '%s_size' % msg.name
751             yield '#define %-40s %s\n' % (identifier, msize)
752     yield '\n'
753     
754     yield '#ifdef __cplusplus\n'
755     yield '} /* extern "C" */\n'
756     yield '#endif\n'
757     
758     # End of header
759     yield '\n#endif\n'
760
761 def generate_source(headername, enums, messages, extensions, options):
762     '''Generate content for a source file.'''
763     
764     yield '/* Automatically generated nanopb constant definitions */\n'
765     yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
766     yield options.genformat % (headername)
767     yield '\n'
768     
769     for msg in messages:
770         yield msg.default_decl(False)
771     
772     yield '\n\n'
773     
774     for msg in messages:
775         yield msg.fields_definition() + '\n\n'
776     
777     for ext in extensions:
778         yield ext.extension_def() + '\n'
779         
780     # Add checks for numeric limits
781     if messages:
782         count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
783         largest_msg = max(messages, key = count_required_fields)
784         largest_count = count_required_fields(largest_msg)
785         if largest_count > 64:
786             yield '\n/* Check that missing required fields will be properly detected */\n'
787             yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
788             yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
789             yield '       setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
790             yield '#endif\n'
791     
792     worst = 0
793     worst_field = ''
794     checks = []
795     checks_msgnames = []
796     for msg in messages:
797         checks_msgnames.append(msg.name)
798         for field in msg.fields:
799             status = field.largest_field_value()
800             if isinstance(status, (str, unicode)):
801                 checks.append(status)
802             elif status > worst:
803                 worst = status
804                 worst_field = str(field.struct_name) + '.' + str(field.name)
805
806     if worst > 255 or checks:
807         yield '\n/* Check that field information fits in pb_field_t */\n'
808         
809         if worst < 65536:
810             yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
811             if worst > 255:
812                 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
813             else:
814                 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
815                 msgs = '_'.join(str(n) for n in checks_msgnames)
816                 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
817             yield '#endif\n\n'
818         
819         if worst > 65535 or checks:
820             yield '#if !defined(PB_FIELD_32BIT)\n'
821             if worst > 65535:
822                 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
823             else:
824                 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
825                 msgs = '_'.join(str(n) for n in checks_msgnames)
826                 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
827             yield '#endif\n'
828     
829     # Add check for sizeof(double)
830     has_double = False
831     for msg in messages:
832         for field in msg.fields:
833             if field.ctype == 'double':
834                 has_double = True
835     
836     if has_double:
837         yield '\n'
838         yield '/* On some platforms (such as AVR), double is really float.\n'
839         yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
840         yield ' * To get rid of this error, remove any double fields from your .proto.\n'
841         yield ' */\n'
842         yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
843     
844     yield '\n'
845
846 # ---------------------------------------------------------------------------
847 #                    Options parsing for the .proto files
848 # ---------------------------------------------------------------------------
849
850 from fnmatch import fnmatch
851
852 def read_options_file(infile):
853     '''Parse a separate options file to list:
854         [(namemask, options), ...]
855     '''
856     results = []
857     for line in infile:
858         line = line.strip()
859         if not line or line.startswith('//') or line.startswith('#'):
860             continue
861         
862         parts = line.split(None, 1)
863         opts = nanopb_pb2.NanoPBOptions()
864         text_format.Merge(parts[1], opts)
865         results.append((parts[0], opts))
866
867     return results
868
869 class Globals:
870     '''Ugly global variables, should find a good way to pass these.'''
871     verbose_options = False
872     separate_options = []
873
874 def get_nanopb_suboptions(subdesc, options, name):
875     '''Get copy of options, and merge information from subdesc.'''
876     new_options = nanopb_pb2.NanoPBOptions()
877     new_options.CopyFrom(options)
878     
879     # Handle options defined in a separate file
880     dotname = '.'.join(name.parts)
881     for namemask, options in Globals.separate_options:
882         if fnmatch(dotname, namemask):
883             new_options.MergeFrom(options)
884     
885     # Handle options defined in .proto
886     if isinstance(subdesc.options, descriptor.FieldOptions):
887         ext_type = nanopb_pb2.nanopb
888     elif isinstance(subdesc.options, descriptor.FileOptions):
889         ext_type = nanopb_pb2.nanopb_fileopt
890     elif isinstance(subdesc.options, descriptor.MessageOptions):
891         ext_type = nanopb_pb2.nanopb_msgopt
892     elif isinstance(subdesc.options, descriptor.EnumOptions):
893         ext_type = nanopb_pb2.nanopb_enumopt
894     else:
895         raise Exception("Unknown options type")
896     
897     if subdesc.options.HasExtension(ext_type):
898         ext = subdesc.options.Extensions[ext_type]
899         new_options.MergeFrom(ext)
900     
901     if Globals.verbose_options:
902         print "Options for " + dotname + ":"
903         print text_format.MessageToString(new_options)
904     
905     return new_options
906
907
908 # ---------------------------------------------------------------------------
909 #                         Command line interface
910 # ---------------------------------------------------------------------------
911
912 import sys
913 import os.path    
914 from optparse import OptionParser
915
916 optparser = OptionParser(
917     usage = "Usage: nanopb_generator.py [options] file.pb ...",
918     epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
919              "Output will be written to file.pb.h and file.pb.c.")
920 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
921     help="Exclude file from generated #include list.")
922 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
923     help="Set extension to use instead of 'pb' for generated files. [default: %default]")
924 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
925     help="Set name of a separate generator options file.")
926 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
927     metavar="FORMAT", default='#include "%s"\n',
928     help="Set format string to use for including other .pb.h files. [default: %default]")
929 optparser.add_option("-L", "--library-include-format", dest="libformat",
930     metavar="FORMAT", default='#include <%s>\n',
931     help="Set format string to use for including the nanopb pb.h header. [default: %default]")
932 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
933     help="Don't print anything except errors.")
934 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
935     help="Print more information.")
936 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
937     help="Set generator option (max_size, max_count etc.).")
938
939 def process_file(filename, fdesc, options):
940     '''Process a single file.
941     filename: The full path to the .proto or .pb source file, as string.
942     fdesc: The loaded FileDescriptorSet, or None to read from the input file.
943     options: Command line options as they come from OptionsParser.
944     
945     Returns a dict:
946         {'headername': Name of header file,
947          'headerdata': Data for the .h header file,
948          'sourcename': Name of the source code file,
949          'sourcedata': Data for the .c source code file
950         }
951     '''
952     toplevel_options = nanopb_pb2.NanoPBOptions()
953     for s in options.settings:
954         text_format.Merge(s, toplevel_options)
955     
956     if not fdesc:
957         data = open(filename, 'rb').read()
958         fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
959     
960     # Check if there is a separate .options file
961     try:
962         optfilename = options.options_file % os.path.splitext(filename)[0]
963     except TypeError:
964         # No %s specified, use the filename as-is
965         optfilename = options.options_file
966     
967     if options.verbose:
968         print 'Reading options from ' + optfilename
969     
970     if os.path.isfile(optfilename):
971         Globals.separate_options = read_options_file(open(optfilename, "rU"))
972     else:
973         Globals.separate_options = []
974     
975     # Parse the file
976     file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
977     enums, messages, extensions = parse_file(fdesc, file_options)
978     
979     # Decide the file names
980     noext = os.path.splitext(filename)[0]
981     headername = noext + '.' + options.extension + '.h'
982     sourcename = noext + '.' + options.extension + '.c'
983     headerbasename = os.path.basename(headername)
984     
985     # List of .proto files that should not be included in the C header file
986     # even if they are mentioned in the source .proto.
987     excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
988     dependencies = [d for d in fdesc.dependency if d not in excludes]
989     
990     headerdata = ''.join(generate_header(dependencies, headerbasename, enums,
991                                          messages, extensions, options))
992
993     sourcedata = ''.join(generate_source(headerbasename, enums,
994                                          messages, extensions, options))
995
996     return {'headername': headername, 'headerdata': headerdata,
997             'sourcename': sourcename, 'sourcedata': sourcedata}
998     
999 def main_cli():
1000     '''Main function when invoked directly from the command line.'''
1001     
1002     options, filenames = optparser.parse_args()
1003     
1004     if not filenames:
1005         optparser.print_help()
1006         sys.exit(1)
1007     
1008     if options.quiet:
1009         options.verbose = False
1010
1011     Globals.verbose_options = options.verbose
1012     
1013     for filename in filenames:
1014         results = process_file(filename, None, options)
1015         
1016         if not options.quiet:
1017             print "Writing to " + results['headername'] + " and " + results['sourcename']
1018     
1019         open(results['headername'], 'w').write(results['headerdata'])
1020         open(results['sourcename'], 'w').write(results['sourcedata'])        
1021
1022 def main_plugin():
1023     '''Main function when invoked as a protoc plugin.'''
1024
1025     import sys
1026     if sys.platform == "win32":
1027         import os, msvcrt
1028         # Set stdin and stdout to binary mode
1029         msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1030         msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1031     
1032     import proto.plugin_pb2 as plugin_pb2
1033     data = sys.stdin.read()
1034     request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1035     
1036     import shlex
1037     args = shlex.split(request.parameter)
1038     options, dummy = optparser.parse_args(args)
1039     
1040     # We can't go printing stuff to stdout
1041     Globals.verbose_options = False
1042     options.verbose = False
1043     options.quiet = True
1044     
1045     response = plugin_pb2.CodeGeneratorResponse()
1046     
1047     for filename in request.file_to_generate:
1048         for fdesc in request.proto_file:
1049             if fdesc.name == filename:
1050                 results = process_file(filename, fdesc, options)
1051                 
1052                 f = response.file.add()
1053                 f.name = results['headername']
1054                 f.content = results['headerdata']
1055
1056                 f = response.file.add()
1057                 f.name = results['sourcename']
1058                 f.content = results['sourcedata']    
1059     
1060     sys.stdout.write(response.SerializeToString())
1061
1062 if __name__ == '__main__':
1063     # Check if we are running as a plugin under protoc
1064     if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv:
1065         main_plugin()
1066     else:
1067         main_cli()
1068