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