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