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