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