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