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