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