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