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