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