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