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