Publishing nanopb-0.3.1
[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.3.1"
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     import google.protobuf.descriptor_pb2 as descriptor
19 except:
20     sys.stderr.write('''
21          *************************************************************
22          *** Could not import the Google protobuf Python libraries ***
23          *** Try installing package 'python-protobuf' or similar.  ***
24          *************************************************************
25     ''' + '\n')
26     raise
27
28 try:
29     import proto.nanopb_pb2 as nanopb_pb2
30     import proto.plugin_pb2 as plugin_pb2
31 except:
32     sys.stderr.write('''
33          ********************************************************************
34          *** Failed to import the protocol definitions for generator.     ***
35          *** You have to run 'make' in the nanopb/generator/proto folder. ***
36          ********************************************************************
37     ''' + '\n')
38     raise
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_array_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 += '    pb_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 in ['STRING', 'BYTES']:
270                 # String/bytes 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 += '    pb_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 PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype)
288         else:
289             result = None
290         return result
291     
292     def get_initializer(self, null_init):
293         '''Return literal expression for this field's default value.'''
294         
295         if self.pbtype == 'MESSAGE':
296             if null_init:
297                 return '%s_init_zero' % self.ctype
298             else:
299                 return '%s_init_default' % self.ctype
300         
301         if self.default is None or null_init:
302             if self.pbtype == 'STRING':
303                 return '""'
304             elif self.pbtype == 'BYTES':
305                 return '{0, {0}}'
306             elif self.pbtype == 'ENUM':
307                 return '(%s)0' % self.ctype
308             else:
309                 return '0'
310         
311         default = str(self.default)
312         
313         if self.pbtype == 'STRING':
314             default = default.encode('utf-8').encode('string_escape')
315             default = default.replace('"', '\\"')
316             default = '"' + default + '"'
317         elif self.pbtype == 'BYTES':
318             data = default.decode('string_escape')
319             data = ['0x%02x' % ord(c) for c in data]
320             if len(data) == 0:
321                 default = '{0, {0}}'
322             else:
323                 default = '{%d, {%s}}' % (len(data), ','.join(data))
324         elif self.pbtype in ['FIXED32', 'UINT32']:
325             default += 'u'
326         elif self.pbtype in ['FIXED64', 'UINT64']:
327             default += 'ull'
328         elif self.pbtype in ['SFIXED64', 'INT64']:
329             default += 'll'
330         
331         return default
332     
333     def default_decl(self, declaration_only = False):
334         '''Return definition for this field's default value.'''
335         if self.default is None:
336             return None
337
338         ctype = self.ctype
339         default = self.get_initializer(False)
340         array_decl = ''
341         
342         if self.pbtype == 'STRING':
343             if self.allocation != 'STATIC':
344                 return None # Not implemented
345             array_decl = '[%d]' % self.max_size
346         elif self.pbtype == 'BYTES':
347             if self.allocation != 'STATIC':
348                 return None # Not implemented
349         
350         if declaration_only:
351             return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
352         else:
353             return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
354     
355     def tags(self):
356         '''Return the #define for the tag number of this field.'''
357         identifier = '%s_%s_tag' % (self.struct_name, self.name)
358         return '#define %-40s %d\n' % (identifier, self.tag)
359     
360     def pb_field_t(self, prev_field_name):
361         '''Return the pb_field_t initializer to use in the constant array.
362         prev_field_name is the name of the previous field or None.
363         '''
364         result  = '    PB_FIELD(%3d, ' % self.tag
365         result += '%-8s, ' % self.pbtype
366         result += '%s, ' % self.rules
367         result += '%-8s, ' % self.allocation
368         result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
369         result += '%s, ' % self.struct_name
370         result += '%s, ' % self.name
371         result += '%s, ' % (prev_field_name or self.name)
372         
373         if self.pbtype == 'MESSAGE':
374             result += '&%s_fields)' % self.submsgname
375         elif self.default is None:
376             result += '0)'
377         elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
378             result += '0)' # Arbitrary size default values not implemented
379         elif self.rules == 'OPTEXT':
380             result += '0)' # Default value for extensions is not implemented
381         else:
382             result += '&%s_default)' % (self.struct_name + self.name)
383         
384         return result
385     
386     def largest_field_value(self):
387         '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
388         Returns numeric value or a C-expression for assert.'''
389         if self.pbtype == 'MESSAGE':
390             if self.rules == 'REPEATED' and self.allocation == 'STATIC':
391                 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
392             else:
393                 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
394
395         return max(self.tag, self.max_size, self.max_count)        
396
397     def encoded_size(self, allmsgs):
398         '''Return the maximum size that this field can take when encoded,
399         including the field tag. If the size cannot be determined, returns
400         None.'''
401         
402         if self.allocation != 'STATIC':
403             return None
404         
405         if self.pbtype == 'MESSAGE':
406             for msg in allmsgs:
407                 if msg.name == self.submsgname:
408                     encsize = msg.encoded_size(allmsgs)
409                     if encsize is None:
410                         return None # Submessage size is indeterminate
411                         
412                     # Include submessage length prefix
413                     encsize += varint_max_size(encsize.upperlimit())
414                     break
415             else:
416                 # Submessage cannot be found, this currently occurs when
417                 # the submessage type is defined in a different file.
418                 # Instead of direct numeric value, reference the size that
419                 # has been #defined in the other file.
420                 encsize = EncodedSize(self.submsgname + 'size')
421
422                 # We will have to make a conservative assumption on the length
423                 # prefix size, though.
424                 encsize += 5
425
426         elif self.enc_size is None:
427             raise RuntimeError("Could not determine encoded size for %s.%s"
428                                % (self.struct_name, self.name))
429         else:
430             encsize = EncodedSize(self.enc_size)
431         
432         encsize += varint_max_size(self.tag << 3) # Tag + wire type
433
434         if self.rules == 'REPEATED':
435             # Decoders must be always able to handle unpacked arrays.
436             # Therefore we have to reserve space for it, even though
437             # we emit packed arrays ourselves.
438             encsize *= self.max_count
439         
440         return encsize
441
442
443 class ExtensionRange(Field):
444     def __init__(self, struct_name, range_start, field_options):
445         '''Implements a special pb_extension_t* field in an extensible message
446         structure. The range_start signifies the index at which the extensions
447         start. Not necessarily all tags above this are extensions, it is merely
448         a speed optimization.
449         '''
450         self.tag = range_start
451         self.struct_name = struct_name
452         self.name = 'extensions'
453         self.pbtype = 'EXTENSION'
454         self.rules = 'OPTIONAL'
455         self.allocation = 'CALLBACK'
456         self.ctype = 'pb_extension_t'
457         self.array_decl = ''
458         self.default = None
459         self.max_size = 0
460         self.max_count = 0
461         
462     def __str__(self):
463         return '    pb_extension_t *extensions;'
464     
465     def types(self):
466         return None
467     
468     def tags(self):
469         return ''
470     
471     def encoded_size(self, allmsgs):
472         # We exclude extensions from the count, because they cannot be known
473         # until runtime. Other option would be to return None here, but this
474         # way the value remains useful if extensions are not used.
475         return EncodedSize(0)
476
477 class ExtensionField(Field):
478     def __init__(self, struct_name, desc, field_options):
479         self.fullname = struct_name + desc.name
480         self.extendee_name = names_from_type_name(desc.extendee)
481         Field.__init__(self, self.fullname + 'struct', desc, field_options)
482         
483         if self.rules != 'OPTIONAL':
484             self.skip = True
485         else:
486             self.skip = False
487             self.rules = 'OPTEXT'
488
489     def tags(self):
490         '''Return the #define for the tag number of this field.'''
491         identifier = '%s_tag' % self.fullname
492         return '#define %-40s %d\n' % (identifier, self.tag)
493
494     def extension_decl(self):
495         '''Declaration of the extension type in the .pb.h file'''
496         if self.skip:
497             msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
498             msg +='   type of extension fields is currently supported. */\n'
499             return msg
500         
501         return 'extern const pb_extension_type_t %s;\n' % self.fullname
502
503     def extension_def(self):
504         '''Definition of the extension type in the .pb.c file'''
505
506         if self.skip:
507             return ''
508
509         result  = 'typedef struct {\n'
510         result += str(self)
511         result += '\n} %s;\n\n' % self.struct_name
512         result += ('static const pb_field_t %s_field = \n  %s;\n\n' %
513                     (self.fullname, self.pb_field_t(None)))
514         result += 'const pb_extension_type_t %s = {\n' % self.fullname
515         result += '    NULL,\n'
516         result += '    NULL,\n'
517         result += '    &%s_field\n' % self.fullname
518         result += '};\n'
519         return result
520
521
522 # ---------------------------------------------------------------------------
523 #                   Generation of messages (structures)
524 # ---------------------------------------------------------------------------
525
526
527 class Message:
528     def __init__(self, names, desc, message_options):
529         self.name = names
530         self.fields = []
531         
532         for f in desc.field:
533             field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
534             if field_options.type != nanopb_pb2.FT_IGNORE:
535                 self.fields.append(Field(self.name, f, field_options))
536         
537         if len(desc.extension_range) > 0:
538             field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
539             range_start = min([r.start for r in desc.extension_range])
540             if field_options.type != nanopb_pb2.FT_IGNORE:
541                 self.fields.append(ExtensionRange(self.name, range_start, field_options))
542         
543         self.packed = message_options.packed_struct
544         self.ordered_fields = self.fields[:]
545         self.ordered_fields.sort()
546
547     def get_dependencies(self):
548         '''Get list of type names that this structure refers to.'''
549         return [str(field.ctype) for field in self.fields if field.allocation == 'STATIC']
550     
551     def __str__(self):
552         result = 'typedef struct _%s {\n' % self.name
553
554         if not self.ordered_fields:
555             # Empty structs are not allowed in C standard.
556             # Therefore add a dummy field if an empty message occurs.
557             result += '    uint8_t dummy_field;'
558
559         result += '\n'.join([str(f) for f in self.ordered_fields])
560         result += '\n}'
561         
562         if self.packed:
563             result += ' pb_packed'
564         
565         result += ' %s;' % self.name
566         
567         if self.packed:
568             result = 'PB_PACKED_STRUCT_START\n' + result
569             result += '\nPB_PACKED_STRUCT_END'
570         
571         return result
572     
573     def types(self):
574         result = ""
575         for field in self.fields:
576             types = field.types()
577             if types is not None:
578                 result += types + '\n'
579         return result
580     
581     def get_initializer(self, null_init):
582         if not self.ordered_fields:
583             return '{0}'
584     
585         parts = []
586         for field in self.ordered_fields:
587             if field.allocation == 'STATIC':
588                 if field.rules == 'REPEATED':
589                     parts.append('0')
590                     parts.append('{'
591                                  + ', '.join([field.get_initializer(null_init)] * field.max_count)
592                                  + '}')
593                 elif field.rules == 'OPTIONAL':
594                     parts.append('false')
595                     parts.append(field.get_initializer(null_init))
596                 else:
597                     parts.append(field.get_initializer(null_init))
598             elif field.allocation == 'POINTER':
599                 if field.rules == 'REPEATED':
600                     parts.append('0')
601                 parts.append('NULL')
602             elif field.allocation == 'CALLBACK':
603                 if field.pbtype == 'EXTENSION':
604                     parts.append('NULL')
605                 else:
606                     parts.append('{{NULL}, NULL}')
607         return '{' + ', '.join(parts) + '}'
608     
609     def default_decl(self, declaration_only = False):
610         result = ""
611         for field in self.fields:
612             default = field.default_decl(declaration_only)
613             if default is not None:
614                 result += default + '\n'
615         return result
616
617     def fields_declaration(self):
618         result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
619         return result
620
621     def fields_definition(self):
622         result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
623         
624         prev = None
625         for field in self.ordered_fields:
626             result += field.pb_field_t(prev)
627             result += ',\n'
628             prev = field.name
629         
630         result += '    PB_LAST_FIELD\n};'
631         return result
632
633     def encoded_size(self, allmsgs):
634         '''Return the maximum size that this message can take when encoded.
635         If the size cannot be determined, returns None.
636         '''
637         size = EncodedSize(0)
638         for field in self.fields:
639             fsize = field.encoded_size(allmsgs)
640             if fsize is None:
641                 return None
642             size += fsize
643         
644         return size
645
646
647 # ---------------------------------------------------------------------------
648 #                    Processing of entire .proto files
649 # ---------------------------------------------------------------------------
650
651
652 def iterate_messages(desc, names = Names()):
653     '''Recursively find all messages. For each, yield name, DescriptorProto.'''
654     if hasattr(desc, 'message_type'):
655         submsgs = desc.message_type
656     else:
657         submsgs = desc.nested_type
658     
659     for submsg in submsgs:
660         sub_names = names + submsg.name
661         yield sub_names, submsg
662         
663         for x in iterate_messages(submsg, sub_names):
664             yield x
665
666 def iterate_extensions(desc, names = Names()):
667     '''Recursively find all extensions.
668     For each, yield name, FieldDescriptorProto.
669     '''
670     for extension in desc.extension:
671         yield names, extension
672
673     for subname, subdesc in iterate_messages(desc, names):
674         for extension in subdesc.extension:
675             yield subname, extension
676
677 def parse_file(fdesc, file_options):
678     '''Takes a FileDescriptorProto and returns tuple (enums, messages, extensions).'''
679     
680     enums = []
681     messages = []
682     extensions = []
683     
684     if fdesc.package:
685         base_name = Names(fdesc.package.split('.'))
686     else:
687         base_name = Names()
688     
689     for enum in fdesc.enum_type:
690         enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
691         enums.append(Enum(base_name, enum, enum_options))
692     
693     for names, message in iterate_messages(fdesc, base_name):
694         message_options = get_nanopb_suboptions(message, file_options, names)
695         
696         if message_options.skip_message:
697             continue
698         
699         messages.append(Message(names, message, message_options))
700         for enum in message.enum_type:
701             enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
702             enums.append(Enum(names, enum, enum_options))
703     
704     for names, extension in iterate_extensions(fdesc, base_name):
705         field_options = get_nanopb_suboptions(extension, file_options, names + extension.name)
706         if field_options.type != nanopb_pb2.FT_IGNORE:
707             extensions.append(ExtensionField(names, extension, field_options))
708     
709     # Fix field default values where enum short names are used.
710     for enum in enums:
711         if not enum.options.long_names:
712             for message in messages:
713                 for field in message.fields:
714                     if field.default in enum.value_longnames:
715                         idx = enum.value_longnames.index(field.default)
716                         field.default = enum.values[idx][0]
717     
718     return enums, messages, extensions
719
720 def toposort2(data):
721     '''Topological sort.
722     From http://code.activestate.com/recipes/577413-topological-sort/
723     This function is under the MIT license.
724     '''
725     for k, v in data.items():
726         v.discard(k) # Ignore self dependencies
727     extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
728     data.update(dict([(item, set()) for item in extra_items_in_deps]))
729     while True:
730         ordered = set(item for item,dep in data.items() if not dep)
731         if not ordered:
732             break
733         for item in sorted(ordered):
734             yield item
735         data = dict([(item, (dep - ordered)) for item,dep in data.items()
736                 if item not in ordered])
737     assert not data, "A cyclic dependency exists amongst %r" % data
738
739 def sort_dependencies(messages):
740     '''Sort a list of Messages based on dependencies.'''
741     dependencies = {}
742     message_by_name = {}
743     for message in messages:
744         dependencies[str(message.name)] = set(message.get_dependencies())
745         message_by_name[str(message.name)] = message
746     
747     for msgname in toposort2(dependencies):
748         if msgname in message_by_name:
749             yield message_by_name[msgname]
750
751 def make_identifier(headername):
752     '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
753     result = ""
754     for c in headername.upper():
755         if c.isalnum():
756             result += c
757         else:
758             result += '_'
759     return result
760
761 def generate_header(dependencies, headername, enums, messages, extensions, options):
762     '''Generate content for a header file.
763     Generates strings, which should be concatenated and stored to file.
764     '''
765     
766     yield '/* Automatically generated nanopb header */\n'
767     if options.notimestamp:
768         yield '/* Generated by %s */\n\n' % (nanopb_version)
769     else:
770         yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
771     
772     symbol = make_identifier(headername)
773     yield '#ifndef PB_%s_INCLUDED\n' % symbol
774     yield '#define PB_%s_INCLUDED\n' % symbol
775     try:
776         yield options.libformat % ('pb.h')
777     except TypeError:
778         # no %s specified - use whatever was passed in as options.libformat
779         yield options.libformat
780     yield '\n'
781     
782     for dependency in dependencies:
783         noext = os.path.splitext(dependency)[0]
784         yield options.genformat % (noext + options.extension + '.h')
785         yield '\n'
786
787     yield '#if PB_PROTO_HEADER_VERSION != 30\n'
788     yield '#error Regenerate this file with the current version of nanopb generator.\n'
789     yield '#endif\n'
790     yield '\n'
791
792     yield '#ifdef __cplusplus\n'
793     yield 'extern "C" {\n'
794     yield '#endif\n\n'
795     
796     yield '/* Enum definitions */\n'
797     for enum in enums:
798         yield str(enum) + '\n\n'
799     
800     yield '/* Struct definitions */\n'
801     for msg in sort_dependencies(messages):
802         yield msg.types()
803         yield str(msg) + '\n\n'
804     
805     if extensions:
806         yield '/* Extensions */\n'
807         for extension in extensions:
808             yield extension.extension_decl()
809         yield '\n'
810         
811     yield '/* Default values for struct fields */\n'
812     for msg in messages:
813         yield msg.default_decl(True)
814     yield '\n'
815     
816     yield '/* Initializer values for message structs */\n'
817     for msg in messages:
818         identifier = '%s_init_default' % msg.name
819         yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
820     for msg in messages:
821         identifier = '%s_init_zero' % msg.name
822         yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
823     yield '\n'
824     
825     yield '/* Field tags (for use in manual encoding/decoding) */\n'
826     for msg in sort_dependencies(messages):
827         for field in msg.fields:
828             yield field.tags()
829     for extension in extensions:
830         yield extension.tags()
831     yield '\n'
832     
833     yield '/* Struct field encoding specification for nanopb */\n'
834     for msg in messages:
835         yield msg.fields_declaration() + '\n'
836     yield '\n'
837     
838     yield '/* Maximum encoded size of messages (where known) */\n'
839     for msg in messages:
840         msize = msg.encoded_size(messages)
841         if msize is not None:
842             identifier = '%s_size' % msg.name
843             yield '#define %-40s %s\n' % (identifier, msize)
844     yield '\n'
845     
846     yield '#ifdef __cplusplus\n'
847     yield '} /* extern "C" */\n'
848     yield '#endif\n'
849     
850     # End of header
851     yield '\n#endif\n'
852
853 def generate_source(headername, enums, messages, extensions, options):
854     '''Generate content for a source file.'''
855     
856     yield '/* Automatically generated nanopb constant definitions */\n'
857     if options.notimestamp:
858         yield '/* Generated by %s */\n\n' % (nanopb_version)
859     else:
860         yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
861     yield options.genformat % (headername)
862     yield '\n'
863     
864     yield '#if PB_PROTO_HEADER_VERSION != 30\n'
865     yield '#error Regenerate this file with the current version of nanopb generator.\n'
866     yield '#endif\n'
867     yield '\n'
868     
869     for msg in messages:
870         yield msg.default_decl(False)
871     
872     yield '\n\n'
873     
874     for msg in messages:
875         yield msg.fields_definition() + '\n\n'
876     
877     for ext in extensions:
878         yield ext.extension_def() + '\n'
879         
880     # Add checks for numeric limits
881     if messages:
882         count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
883         largest_msg = max(messages, key = count_required_fields)
884         largest_count = count_required_fields(largest_msg)
885         if largest_count > 64:
886             yield '\n/* Check that missing required fields will be properly detected */\n'
887             yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
888             yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
889             yield '       setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
890             yield '#endif\n'
891     
892     worst = 0
893     worst_field = ''
894     checks = []
895     checks_msgnames = []
896     for msg in messages:
897         checks_msgnames.append(msg.name)
898         for field in msg.fields:
899             status = field.largest_field_value()
900             if isinstance(status, (str, unicode)):
901                 checks.append(status)
902             elif status > worst:
903                 worst = status
904                 worst_field = str(field.struct_name) + '.' + str(field.name)
905
906     if worst > 255 or checks:
907         yield '\n/* Check that field information fits in pb_field_t */\n'
908         
909         if worst > 65535 or checks:
910             yield '#if !defined(PB_FIELD_32BIT)\n'
911             if worst > 65535:
912                 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
913             else:
914                 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
915                 msgs = '_'.join(str(n) for n in checks_msgnames)
916                 yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n'
917                 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
918                 yield ' * \n'
919                 yield ' * The reason you need to do this is that some of your messages contain tag\n'
920                 yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n'
921                 yield ' * field descriptors.\n'
922                 yield ' */\n'
923                 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
924             yield '#endif\n\n'
925         
926         if worst < 65536:
927             yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
928             if worst > 255:
929                 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
930             else:
931                 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
932                 msgs = '_'.join(str(n) for n in checks_msgnames)
933                 yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
934                 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
935                 yield ' * \n'
936                 yield ' * The reason you need to do this is that some of your messages contain tag\n'
937                 yield ' * numbers or field sizes that are larger than what can fit in the default\n'
938                 yield ' * 8 bit descriptors.\n'
939                 yield ' */\n'
940                 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
941             yield '#endif\n\n'
942     
943     # Add check for sizeof(double)
944     has_double = False
945     for msg in messages:
946         for field in msg.fields:
947             if field.ctype == 'double':
948                 has_double = True
949     
950     if has_double:
951         yield '\n'
952         yield '/* On some platforms (such as AVR), double is really float.\n'
953         yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
954         yield ' * To get rid of this error, remove any double fields from your .proto.\n'
955         yield ' */\n'
956         yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
957     
958     yield '\n'
959
960 # ---------------------------------------------------------------------------
961 #                    Options parsing for the .proto files
962 # ---------------------------------------------------------------------------
963
964 from fnmatch import fnmatch
965
966 def read_options_file(infile):
967     '''Parse a separate options file to list:
968         [(namemask, options), ...]
969     '''
970     results = []
971     for line in infile:
972         line = line.strip()
973         if not line or line.startswith('//') or line.startswith('#'):
974             continue
975         
976         parts = line.split(None, 1)
977         opts = nanopb_pb2.NanoPBOptions()
978         text_format.Merge(parts[1], opts)
979         results.append((parts[0], opts))
980
981     return results
982
983 class Globals:
984     '''Ugly global variables, should find a good way to pass these.'''
985     verbose_options = False
986     separate_options = []
987     matched_namemasks = set()
988
989 def get_nanopb_suboptions(subdesc, options, name):
990     '''Get copy of options, and merge information from subdesc.'''
991     new_options = nanopb_pb2.NanoPBOptions()
992     new_options.CopyFrom(options)
993     
994     # Handle options defined in a separate file
995     dotname = '.'.join(name.parts)
996     for namemask, options in Globals.separate_options:
997         if fnmatch(dotname, namemask):
998             Globals.matched_namemasks.add(namemask)
999             new_options.MergeFrom(options)
1000     
1001     # Handle options defined in .proto
1002     if isinstance(subdesc.options, descriptor.FieldOptions):
1003         ext_type = nanopb_pb2.nanopb
1004     elif isinstance(subdesc.options, descriptor.FileOptions):
1005         ext_type = nanopb_pb2.nanopb_fileopt
1006     elif isinstance(subdesc.options, descriptor.MessageOptions):
1007         ext_type = nanopb_pb2.nanopb_msgopt
1008     elif isinstance(subdesc.options, descriptor.EnumOptions):
1009         ext_type = nanopb_pb2.nanopb_enumopt
1010     else:
1011         raise Exception("Unknown options type")
1012     
1013     if subdesc.options.HasExtension(ext_type):
1014         ext = subdesc.options.Extensions[ext_type]
1015         new_options.MergeFrom(ext)
1016     
1017     if Globals.verbose_options:
1018         sys.stderr.write("Options for " + dotname + ": ")
1019         sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1020     
1021     return new_options
1022
1023
1024 # ---------------------------------------------------------------------------
1025 #                         Command line interface
1026 # ---------------------------------------------------------------------------
1027
1028 import sys
1029 import os.path    
1030 from optparse import OptionParser
1031
1032 optparser = OptionParser(
1033     usage = "Usage: nanopb_generator.py [options] file.pb ...",
1034     epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1035              "Output will be written to file.pb.h and file.pb.c.")
1036 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1037     help="Exclude file from generated #include list.")
1038 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1039     help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1040 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1041     help="Set name of a separate generator options file.")
1042 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1043     metavar="FORMAT", default='#include "%s"\n',
1044     help="Set format string to use for including other .pb.h files. [default: %default]")
1045 optparser.add_option("-L", "--library-include-format", dest="libformat",
1046     metavar="FORMAT", default='#include <%s>\n',
1047     help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1048 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1049     help="Don't add timestamp to .pb.h and .pb.c preambles")
1050 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1051     help="Don't print anything except errors.")
1052 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1053     help="Print more information.")
1054 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1055     help="Set generator option (max_size, max_count etc.).")
1056
1057 def process_file(filename, fdesc, options):
1058     '''Process a single file.
1059     filename: The full path to the .proto or .pb source file, as string.
1060     fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1061     options: Command line options as they come from OptionsParser.
1062     
1063     Returns a dict:
1064         {'headername': Name of header file,
1065          'headerdata': Data for the .h header file,
1066          'sourcename': Name of the source code file,
1067          'sourcedata': Data for the .c source code file
1068         }
1069     '''
1070     toplevel_options = nanopb_pb2.NanoPBOptions()
1071     for s in options.settings:
1072         text_format.Merge(s, toplevel_options)
1073     
1074     if not fdesc:
1075         data = open(filename, 'rb').read()
1076         fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1077     
1078     # Check if there is a separate .options file
1079     had_abspath = False
1080     try:
1081         optfilename = options.options_file % os.path.splitext(filename)[0]
1082     except TypeError:
1083         # No %s specified, use the filename as-is
1084         optfilename = options.options_file
1085         had_abspath = True
1086
1087     if os.path.isfile(optfilename):
1088         if options.verbose:
1089             sys.stderr.write('Reading options from ' + optfilename + '\n')
1090
1091         Globals.separate_options = read_options_file(open(optfilename, "rU"))
1092     else:
1093         # If we are given a full filename and it does not exist, give an error.
1094         # However, don't give error when we automatically look for .options file
1095         # with the same name as .proto.
1096         if options.verbose or had_abspath:
1097             sys.stderr.write('Options file not found: ' + optfilename)
1098
1099         Globals.separate_options = []
1100
1101     Globals.matched_namemasks = set()
1102     
1103     # Parse the file
1104     file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1105     enums, messages, extensions = parse_file(fdesc, file_options)
1106
1107     # Decide the file names
1108     noext = os.path.splitext(filename)[0]
1109     headername = noext + options.extension + '.h'
1110     sourcename = noext + options.extension + '.c'
1111     headerbasename = os.path.basename(headername)
1112     
1113     # List of .proto files that should not be included in the C header file
1114     # even if they are mentioned in the source .proto.
1115     excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1116     dependencies = [d for d in fdesc.dependency if d not in excludes]
1117     
1118     headerdata = ''.join(generate_header(dependencies, headerbasename, enums,
1119                                          messages, extensions, options))
1120
1121     sourcedata = ''.join(generate_source(headerbasename, enums,
1122                                          messages, extensions, options))
1123
1124     # Check if there were any lines in .options that did not match a member
1125     unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1126     if unmatched and not options.quiet:
1127         sys.stderr.write("Following patterns in " + optfilename + " did not match any fields: "
1128                          + ', '.join(unmatched) + "\n")
1129         if not Globals.verbose_options:
1130             sys.stderr.write("Use  protoc --nanopb-out=-v:.   to see a list of the field names.\n")
1131
1132     return {'headername': headername, 'headerdata': headerdata,
1133             'sourcename': sourcename, 'sourcedata': sourcedata}
1134     
1135 def main_cli():
1136     '''Main function when invoked directly from the command line.'''
1137     
1138     options, filenames = optparser.parse_args()
1139     
1140     if not filenames:
1141         optparser.print_help()
1142         sys.exit(1)
1143     
1144     if options.quiet:
1145         options.verbose = False
1146
1147     Globals.verbose_options = options.verbose
1148     
1149     for filename in filenames:
1150         results = process_file(filename, None, options)
1151         
1152         if not options.quiet:
1153             sys.stderr.write("Writing to " + results['headername'] + " and "
1154                              + results['sourcename'] + "\n")
1155     
1156         open(results['headername'], 'w').write(results['headerdata'])
1157         open(results['sourcename'], 'w').write(results['sourcedata'])        
1158
1159 def main_plugin():
1160     '''Main function when invoked as a protoc plugin.'''
1161
1162     import sys
1163     if sys.platform == "win32":
1164         import os, msvcrt
1165         # Set stdin and stdout to binary mode
1166         msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1167         msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1168     
1169     data = sys.stdin.read()
1170     request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1171     
1172     import shlex
1173     args = shlex.split(request.parameter)
1174     options, dummy = optparser.parse_args(args)
1175     
1176     Globals.verbose_options = options.verbose
1177     
1178     response = plugin_pb2.CodeGeneratorResponse()
1179     
1180     for filename in request.file_to_generate:
1181         for fdesc in request.proto_file:
1182             if fdesc.name == filename:
1183                 results = process_file(filename, fdesc, options)
1184                 
1185                 f = response.file.add()
1186                 f.name = results['headername']
1187                 f.content = results['headerdata']
1188
1189                 f = response.file.add()
1190                 f.name = results['sourcename']
1191                 f.content = results['sourcedata']    
1192     
1193     sys.stdout.write(response.SerializeToString())
1194
1195 if __name__ == '__main__':
1196     # Check if we are running as a plugin under protoc
1197     if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv:
1198         main_plugin()
1199     else:
1200         main_cli()
1201