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