Publishing nanopb-0.3.4
[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.3.4"
5
6 import sys
7 import re
8
9 try:
10     # Add some dummy imports to keep packaging tools happy.
11     import google, distutils.util # bbfreeze seems to need these
12     import pkg_resources # pyinstaller / protobuf 2.5 seem to need these
13 except:
14     # Don't care, we will error out later if it is actually important.
15     pass
16
17 try:
18     import google.protobuf.text_format as text_format
19     import google.protobuf.descriptor_pb2 as descriptor
20 except:
21     sys.stderr.write('''
22          *************************************************************
23          *** Could not import the Google protobuf Python libraries ***
24          *** Try installing package 'python-protobuf' or similar.  ***
25          *************************************************************
26     ''' + '\n')
27     raise
28
29 try:
30     import proto.nanopb_pb2 as nanopb_pb2
31     import proto.plugin_pb2 as plugin_pb2
32 except:
33     sys.stderr.write('''
34          ********************************************************************
35          *** Failed to import the protocol definitions for generator.     ***
36          *** You have to run 'make' in the nanopb/generator/proto folder. ***
37          ********************************************************************
38     ''' + '\n')
39     raise
40
41 # ---------------------------------------------------------------------------
42 #                     Generation of single fields
43 # ---------------------------------------------------------------------------
44
45 import time
46 import os.path
47
48 # Values are tuple (c type, pb type, encoded size, int_size_allowed)
49 FieldD = descriptor.FieldDescriptorProto
50 datatypes = {
51     FieldD.TYPE_BOOL:       ('bool',     'BOOL',        1,  False),
52     FieldD.TYPE_DOUBLE:     ('double',   'DOUBLE',      8,  False),
53     FieldD.TYPE_FIXED32:    ('uint32_t', 'FIXED32',     4,  False),
54     FieldD.TYPE_FIXED64:    ('uint64_t', 'FIXED64',     8,  False),
55     FieldD.TYPE_FLOAT:      ('float',    'FLOAT',       4,  False),
56     FieldD.TYPE_INT32:      ('int32_t',  'INT32',      10,  True),
57     FieldD.TYPE_INT64:      ('int64_t',  'INT64',      10,  True),
58     FieldD.TYPE_SFIXED32:   ('int32_t',  'SFIXED32',    4,  False),
59     FieldD.TYPE_SFIXED64:   ('int64_t',  'SFIXED64',    8,  False),
60     FieldD.TYPE_SINT32:     ('int32_t',  'SINT32',      5,  True),
61     FieldD.TYPE_SINT64:     ('int64_t',  'SINT64',     10,  True),
62     FieldD.TYPE_UINT32:     ('uint32_t', 'UINT32',      5,  True),
63     FieldD.TYPE_UINT64:     ('uint64_t', 'UINT64',     10,  True)
64 }
65
66 # Integer size overrides (from .proto settings)
67 intsizes = {
68     nanopb_pb2.IS_8:     'int8_t',
69     nanopb_pb2.IS_16:    'int16_t',
70     nanopb_pb2.IS_32:    'int32_t',
71     nanopb_pb2.IS_64:    'int64_t',
72 }
73
74 class Names:
75     '''Keeps a set of nested names and formats them to C identifier.'''
76     def __init__(self, parts = ()):
77         if isinstance(parts, Names):
78             parts = parts.parts
79         self.parts = tuple(parts)
80     
81     def __str__(self):
82         return '_'.join(self.parts)
83
84     def __add__(self, other):
85         if isinstance(other, (str, unicode)):
86             return Names(self.parts + (other,))
87         elif isinstance(other, tuple):
88             return Names(self.parts + other)
89         else:
90             raise ValueError("Name parts should be of type str")
91     
92     def __eq__(self, other):
93         return isinstance(other, Names) and self.parts == other.parts
94     
95 def names_from_type_name(type_name):
96     '''Parse Names() from FieldDescriptorProto type_name'''
97     if type_name[0] != '.':
98         raise NotImplementedError("Lookup of non-absolute type names is not supported")
99     return Names(type_name[1:].split('.'))
100
101 def varint_max_size(max_value):
102     '''Returns the maximum number of bytes a varint can take when encoded.'''
103     if max_value < 0:
104         max_value = 2**64 - max_value
105     for i in range(1, 11):
106         if (max_value >> (i * 7)) == 0:
107             return i
108     raise ValueError("Value too large for varint: " + str(max_value))
109
110 assert varint_max_size(-1) == 10
111 assert varint_max_size(0) == 1
112 assert varint_max_size(127) == 1
113 assert varint_max_size(128) == 2
114
115 class EncodedSize:
116     '''Class used to represent the encoded size of a field or a message.
117     Consists of a combination of symbolic sizes and integer sizes.'''
118     def __init__(self, value = 0, symbols = []):
119         if isinstance(value, (str, Names)):
120             symbols = [str(value)]
121             value = 0
122         self.value = value
123         self.symbols = symbols
124     
125     def __add__(self, other):
126         if isinstance(other, (int, long)):
127             return EncodedSize(self.value + other, self.symbols)
128         elif isinstance(other, (str, Names)):
129             return EncodedSize(self.value, self.symbols + [str(other)])
130         elif isinstance(other, EncodedSize):
131             return EncodedSize(self.value + other.value, self.symbols + other.symbols)
132         else:
133             raise ValueError("Cannot add size: " + repr(other))
134
135     def __mul__(self, other):
136         if isinstance(other, (int, long)):
137             return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
138         else:
139             raise ValueError("Cannot multiply size: " + repr(other))
140
141     def __str__(self):
142         if not self.symbols:
143             return str(self.value)
144         else:
145             return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
146
147     def upperlimit(self):
148         if not self.symbols:
149             return self.value
150         else:
151             return 2**32 - 1
152
153 class Enum:
154     def __init__(self, names, desc, enum_options):
155         '''desc is EnumDescriptorProto'''
156         
157         self.options = enum_options
158         self.names = names + desc.name
159         
160         if enum_options.long_names:
161             self.values = [(self.names + x.name, x.number) for x in desc.value]            
162         else:
163             self.values = [(names + x.name, x.number) for x in desc.value] 
164         
165         self.value_longnames = [self.names + x.name for x in desc.value]
166         self.packed = enum_options.packed_enum
167     
168     def has_negative(self):
169         for n, v in self.values:
170             if v < 0:
171                 return True
172         return False
173     
174     def encoded_size(self):
175         return max([varint_max_size(v) for n,v in self.values])
176     
177     def __str__(self):
178         result = 'typedef enum _%s {\n' % self.names
179         result += ',\n'.join(["    %s = %d" % x for x in self.values])
180         result += '\n}'
181         
182         if self.packed:
183             result += ' pb_packed'
184         
185         result += ' %s;' % self.names
186         
187         if not self.options.long_names:
188             # Define the long names always so that enum value references
189             # from other files work properly.
190             for i, x in enumerate(self.values):
191                 result += '\n#define %s %s' % (self.value_longnames[i], x[0])
192         
193         return result
194
195 class Field:
196     def __init__(self, struct_name, desc, field_options):
197         '''desc is FieldDescriptorProto'''
198         self.tag = desc.number
199         self.struct_name = struct_name
200         self.union_name = None
201         self.name = desc.name
202         self.default = None
203         self.max_size = None
204         self.max_count = None
205         self.array_decl = ""
206         self.enc_size = None
207         self.ctype = None
208         
209         # Parse field options
210         if field_options.HasField("max_size"):
211             self.max_size = field_options.max_size
212         
213         if field_options.HasField("max_count"):
214             self.max_count = field_options.max_count
215         
216         if desc.HasField('default_value'):
217             self.default = desc.default_value
218            
219         # Check field rules, i.e. required/optional/repeated.
220         can_be_static = True
221         if desc.label == FieldD.LABEL_REQUIRED:
222             self.rules = 'REQUIRED'
223         elif desc.label == FieldD.LABEL_OPTIONAL:
224             self.rules = 'OPTIONAL'
225         elif desc.label == FieldD.LABEL_REPEATED:
226             self.rules = 'REPEATED'
227             if self.max_count is None:
228                 can_be_static = False
229             else:
230                 self.array_decl = '[%d]' % self.max_count
231         else:
232             raise NotImplementedError(desc.label)
233         
234         # Check if the field can be implemented with static allocation
235         # i.e. whether the data size is known.
236         if desc.type == FieldD.TYPE_STRING and self.max_size is None:
237             can_be_static = False
238         
239         if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
240             can_be_static = False
241         
242         # Decide how the field data will be allocated
243         if field_options.type == nanopb_pb2.FT_DEFAULT:
244             if can_be_static:
245                 field_options.type = nanopb_pb2.FT_STATIC
246             else:
247                 field_options.type = nanopb_pb2.FT_CALLBACK
248         
249         if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
250             raise Exception("Field %s is defined as static, but max_size or "
251                             "max_count is not given." % self.name)
252         
253         if field_options.type == nanopb_pb2.FT_STATIC:
254             self.allocation = 'STATIC'
255         elif field_options.type == nanopb_pb2.FT_POINTER:
256             self.allocation = 'POINTER'
257         elif field_options.type == nanopb_pb2.FT_CALLBACK:
258             self.allocation = 'CALLBACK'
259         else:
260             raise NotImplementedError(field_options.type)
261         
262         # Decide the C data type to use in the struct.
263         if datatypes.has_key(desc.type):
264             self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type]
265
266             # Override the field size if user wants to use smaller integers
267             if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT:
268                 self.ctype = intsizes[field_options.int_size]
269                 if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64:
270                     self.ctype = 'u' + self.ctype;
271         elif desc.type == FieldD.TYPE_ENUM:
272             self.pbtype = 'ENUM'
273             self.ctype = names_from_type_name(desc.type_name)
274             if self.default is not None:
275                 self.default = self.ctype + self.default
276             self.enc_size = None # Needs to be filled in when enum values are known
277         elif desc.type == FieldD.TYPE_STRING:
278             self.pbtype = 'STRING'
279             self.ctype = 'char'
280             if self.allocation == 'STATIC':
281                 self.ctype = 'char'
282                 self.array_decl += '[%d]' % self.max_size
283                 self.enc_size = varint_max_size(self.max_size) + self.max_size
284         elif desc.type == FieldD.TYPE_BYTES:
285             self.pbtype = 'BYTES'
286             if self.allocation == 'STATIC':
287                 self.ctype = self.struct_name + self.name + 't'
288                 self.enc_size = varint_max_size(self.max_size) + self.max_size
289             elif self.allocation == 'POINTER':
290                 self.ctype = 'pb_bytes_array_t'
291         elif desc.type == FieldD.TYPE_MESSAGE:
292             self.pbtype = 'MESSAGE'
293             self.ctype = self.submsgname = names_from_type_name(desc.type_name)
294             self.enc_size = None # Needs to be filled in after the message type is available
295         else:
296             raise NotImplementedError(desc.type)
297         
298     def __cmp__(self, other):
299         return cmp(self.tag, other.tag)
300     
301     def __str__(self):
302         result = ''
303         if self.allocation == 'POINTER':
304             if self.rules == 'REPEATED':
305                 result += '    pb_size_t ' + self.name + '_count;\n'
306             
307             if self.pbtype == 'MESSAGE':
308                 # Use struct definition, so recursive submessages are possible
309                 result += '    struct _%s *%s;' % (self.ctype, self.name)
310             elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']:
311                 # String/bytes arrays need to be defined as pointers to pointers
312                 result += '    %s **%s;' % (self.ctype, self.name)
313             else:
314                 result += '    %s *%s;' % (self.ctype, self.name)
315         elif self.allocation == 'CALLBACK':
316             result += '    pb_callback_t %s;' % self.name
317         else:
318             if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
319                 result += '    bool has_' + self.name + ';\n'
320             elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
321                 result += '    pb_size_t ' + self.name + '_count;\n'
322             result += '    %s %s%s;' % (self.ctype, self.name, self.array_decl)
323         return result
324     
325     def types(self):
326         '''Return definitions for any special types this field might need.'''
327         if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
328             result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype)
329         else:
330             result = ''
331         return result
332     
333     def get_dependencies(self):
334         '''Get list of type names used by this field.'''
335         if self.allocation == 'STATIC':
336             return [str(self.ctype)]
337         else:
338             return []
339
340     def get_initializer(self, null_init, inner_init_only = False):
341         '''Return literal expression for this field's default value.
342         null_init: If True, initialize to a 0 value instead of default from .proto
343         inner_init_only: If True, exclude initialization for any count/has fields
344         '''
345
346         inner_init = None
347         if self.pbtype == 'MESSAGE':
348             if null_init:
349                 inner_init = '%s_init_zero' % self.ctype
350             else:
351                 inner_init = '%s_init_default' % self.ctype
352         elif self.default is None or null_init:
353             if self.pbtype == 'STRING':
354                 inner_init = '""'
355             elif self.pbtype == 'BYTES':
356                 inner_init = '{0, {0}}'
357             elif self.pbtype in ('ENUM', 'UENUM'):
358                 inner_init = '(%s)0' % self.ctype
359             else:
360                 inner_init = '0'
361         else:
362             if self.pbtype == 'STRING':
363                 inner_init = self.default.encode('utf-8').encode('string_escape')
364                 inner_init = inner_init.replace('"', '\\"')
365                 inner_init = '"' + inner_init + '"'
366             elif self.pbtype == 'BYTES':
367                 data = str(self.default).decode('string_escape')
368                 data = ['0x%02x' % ord(c) for c in data]
369                 if len(data) == 0:
370                     inner_init = '{0, {0}}'
371                 else:
372                     inner_init = '{%d, {%s}}' % (len(data), ','.join(data))
373             elif self.pbtype in ['FIXED32', 'UINT32']:
374                 inner_init = str(self.default) + 'u'
375             elif self.pbtype in ['FIXED64', 'UINT64']:
376                 inner_init = str(self.default) + 'ull'
377             elif self.pbtype in ['SFIXED64', 'INT64']:
378                 inner_init = str(self.default) + 'll'
379             else:
380                 inner_init = str(self.default)
381         
382         if inner_init_only:
383             return inner_init
384
385         outer_init = None
386         if self.allocation == 'STATIC':
387             if self.rules == 'REPEATED':
388                 outer_init = '0, {'
389                 outer_init += ', '.join([inner_init] * self.max_count)
390                 outer_init += '}'
391             elif self.rules == 'OPTIONAL':
392                 outer_init = 'false, ' + inner_init
393             else:
394                 outer_init = inner_init
395         elif self.allocation == 'POINTER':
396             if self.rules == 'REPEATED':
397                 outer_init = '0, NULL'
398             else:
399                 outer_init = 'NULL'
400         elif self.allocation == 'CALLBACK':
401             if self.pbtype == 'EXTENSION':
402                 outer_init = 'NULL'
403             else:
404                 outer_init = '{{NULL}, NULL}'
405
406         return outer_init
407
408     def default_decl(self, declaration_only = False):
409         '''Return definition for this field's default value.'''
410         if self.default is None:
411             return None
412
413         ctype = self.ctype
414         default = self.get_initializer(False, True)
415         array_decl = ''
416         
417         if self.pbtype == 'STRING':
418             if self.allocation != 'STATIC':
419                 return None # Not implemented
420             array_decl = '[%d]' % self.max_size
421         elif self.pbtype == 'BYTES':
422             if self.allocation != 'STATIC':
423                 return None # Not implemented
424         
425         if declaration_only:
426             return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
427         else:
428             return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
429     
430     def tags(self):
431         '''Return the #define for the tag number of this field.'''
432         identifier = '%s_%s_tag' % (self.struct_name, self.name)
433         return '#define %-40s %d\n' % (identifier, self.tag)
434     
435     def pb_field_t(self, prev_field_name):
436         '''Return the pb_field_t initializer to use in the constant array.
437         prev_field_name is the name of the previous field or None.
438         '''
439
440         if self.rules == 'ONEOF':
441             result = '    PB_ONEOF_FIELD(%s, ' % self.union_name
442         else:
443             result = '    PB_FIELD('
444
445         result += '%3d, ' % self.tag
446         result += '%-8s, ' % self.pbtype
447         result += '%s, ' % self.rules
448         result += '%-8s, ' % self.allocation
449         result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
450         result += '%s, ' % self.struct_name
451         result += '%s, ' % self.name
452         result += '%s, ' % (prev_field_name or self.name)
453         
454         if self.pbtype == 'MESSAGE':
455             result += '&%s_fields)' % self.submsgname
456         elif self.default is None:
457             result += '0)'
458         elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
459             result += '0)' # Arbitrary size default values not implemented
460         elif self.rules == 'OPTEXT':
461             result += '0)' # Default value for extensions is not implemented
462         else:
463             result += '&%s_default)' % (self.struct_name + self.name)
464         
465         return result
466     
467     def largest_field_value(self):
468         '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
469         Returns numeric value or a C-expression for assert.'''
470         if self.pbtype == 'MESSAGE':
471             if self.rules == 'REPEATED' and self.allocation == 'STATIC':
472                 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
473             elif self.rules == 'ONEOF':
474                 return 'pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name)
475             else:
476                 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
477
478         return max(self.tag, self.max_size, self.max_count)        
479
480     def encoded_size(self, dependencies):
481         '''Return the maximum size that this field can take when encoded,
482         including the field tag. If the size cannot be determined, returns
483         None.'''
484         
485         if self.allocation != 'STATIC':
486             return None
487         
488         if self.pbtype == 'MESSAGE':
489             if str(self.submsgname) in dependencies:
490                 submsg = dependencies[str(self.submsgname)]
491                 encsize = submsg.encoded_size(dependencies)
492                 if encsize is None:
493                     return None # Submessage size is indeterminate
494                     
495                 # Include submessage length prefix
496                 encsize += varint_max_size(encsize.upperlimit())
497             else:
498                 # Submessage cannot be found, this currently occurs when
499                 # the submessage type is defined in a different file and
500                 # not using the protoc plugin.
501                 # Instead of direct numeric value, reference the size that
502                 # has been #defined in the other file.
503                 encsize = EncodedSize(self.submsgname + 'size')
504
505                 # We will have to make a conservative assumption on the length
506                 # prefix size, though.
507                 encsize += 5
508
509         elif self.pbtype in ['ENUM', 'UENUM']:
510             if str(self.ctype) in dependencies:
511                 enumtype = dependencies[str(self.ctype)]
512                 encsize = enumtype.encoded_size()
513             else:
514                 # Conservative assumption
515                 encsize = 10
516
517         elif self.enc_size is None:
518             raise RuntimeError("Could not determine encoded size for %s.%s"
519                                % (self.struct_name, self.name))
520         else:
521             encsize = EncodedSize(self.enc_size)
522         
523         encsize += varint_max_size(self.tag << 3) # Tag + wire type
524
525         if self.rules == 'REPEATED':
526             # Decoders must be always able to handle unpacked arrays.
527             # Therefore we have to reserve space for it, even though
528             # we emit packed arrays ourselves.
529             encsize *= self.max_count
530         
531         return encsize
532
533
534 class ExtensionRange(Field):
535     def __init__(self, struct_name, range_start, field_options):
536         '''Implements a special pb_extension_t* field in an extensible message
537         structure. The range_start signifies the index at which the extensions
538         start. Not necessarily all tags above this are extensions, it is merely
539         a speed optimization.
540         '''
541         self.tag = range_start
542         self.struct_name = struct_name
543         self.name = 'extensions'
544         self.pbtype = 'EXTENSION'
545         self.rules = 'OPTIONAL'
546         self.allocation = 'CALLBACK'
547         self.ctype = 'pb_extension_t'
548         self.array_decl = ''
549         self.default = None
550         self.max_size = 0
551         self.max_count = 0
552         
553     def __str__(self):
554         return '    pb_extension_t *extensions;'
555     
556     def types(self):
557         return ''
558     
559     def tags(self):
560         return ''
561     
562     def encoded_size(self, dependencies):
563         # We exclude extensions from the count, because they cannot be known
564         # until runtime. Other option would be to return None here, but this
565         # way the value remains useful if extensions are not used.
566         return EncodedSize(0)
567
568 class ExtensionField(Field):
569     def __init__(self, struct_name, desc, field_options):
570         self.fullname = struct_name + desc.name
571         self.extendee_name = names_from_type_name(desc.extendee)
572         Field.__init__(self, self.fullname + 'struct', desc, field_options)
573         
574         if self.rules != 'OPTIONAL':
575             self.skip = True
576         else:
577             self.skip = False
578             self.rules = 'OPTEXT'
579
580     def tags(self):
581         '''Return the #define for the tag number of this field.'''
582         identifier = '%s_tag' % self.fullname
583         return '#define %-40s %d\n' % (identifier, self.tag)
584
585     def extension_decl(self):
586         '''Declaration of the extension type in the .pb.h file'''
587         if self.skip:
588             msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
589             msg +='   type of extension fields is currently supported. */\n'
590             return msg
591         
592         return ('extern const pb_extension_type_t %s; /* field type: %s */\n' %
593             (self.fullname, str(self).strip()))
594
595     def extension_def(self):
596         '''Definition of the extension type in the .pb.c file'''
597
598         if self.skip:
599             return ''
600
601         result  = 'typedef struct {\n'
602         result += str(self)
603         result += '\n} %s;\n\n' % self.struct_name
604         result += ('static const pb_field_t %s_field = \n  %s;\n\n' %
605                     (self.fullname, self.pb_field_t(None)))
606         result += 'const pb_extension_type_t %s = {\n' % self.fullname
607         result += '    NULL,\n'
608         result += '    NULL,\n'
609         result += '    &%s_field\n' % self.fullname
610         result += '};\n'
611         return result
612
613
614 # ---------------------------------------------------------------------------
615 #                   Generation of oneofs (unions)
616 # ---------------------------------------------------------------------------
617
618 class OneOf(Field):
619     def __init__(self, struct_name, oneof_desc):
620         self.struct_name = struct_name
621         self.name = oneof_desc.name
622         self.ctype = 'union'
623         self.pbtype = 'oneof'
624         self.fields = []
625         self.allocation = 'ONEOF'
626         self.default = None
627         self.rules = 'ONEOF'
628
629     def add_field(self, field):
630         if field.allocation == 'CALLBACK':
631             raise Exception("Callback fields inside of oneof are not supported"
632                             + " (field %s)" % field.name)
633
634         field.union_name = self.name
635         field.rules = 'ONEOF'
636         self.fields.append(field)
637         self.fields.sort(key = lambda f: f.tag)
638
639         # Sort by the lowest tag number inside union
640         self.tag = min([f.tag for f in self.fields])
641
642     def __cmp__(self, other):
643         return cmp(self.tag, other.tag)
644
645     def __str__(self):
646         result = ''
647         if self.fields:
648             result += '    pb_size_t which_' + self.name + ";\n"
649             result += '    union {\n'
650             for f in self.fields:
651                 result += '    ' + str(f).replace('\n', '\n    ') + '\n'
652             result += '    } ' + self.name + ';'
653         return result
654
655     def types(self):
656         return ''.join([f.types() for f in self.fields])
657
658     def get_dependencies(self):
659         deps = []
660         for f in self.fields:
661             deps += f.get_dependencies()
662         return deps
663
664     def get_initializer(self, null_init):
665         return '0, {' + self.fields[0].get_initializer(null_init) + '}'
666
667     def default_decl(self, declaration_only = False):
668         return None
669
670     def tags(self):
671         return '\n'.join([f.tags() for f in self.fields])
672
673     def pb_field_t(self, prev_field_name):
674         result = ',\n'.join([f.pb_field_t(prev_field_name) for f in self.fields])
675         return result
676
677     def largest_field_value(self):
678         return max([f.largest_field_value() for f in self.fields])
679
680     def encoded_size(self, dependencies):
681         largest = EncodedSize(0)
682         for f in self.fields:
683             size = f.encoded_size(dependencies)
684             if size is None:
685                 return None
686             elif size.symbols:
687                 return None # Cannot resolve maximum of symbols
688             elif size.value > largest.value:
689                 largest = size
690
691         return largest
692
693 # ---------------------------------------------------------------------------
694 #                   Generation of messages (structures)
695 # ---------------------------------------------------------------------------
696
697
698 class Message:
699     def __init__(self, names, desc, message_options):
700         self.name = names
701         self.fields = []
702         self.oneofs = {}
703         no_unions = []
704
705         if message_options.msgid:
706             self.msgid = message_options.msgid
707
708         if hasattr(desc, 'oneof_decl'):
709             for i, f in enumerate(desc.oneof_decl):
710                 oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name)
711                 if oneof_options.no_unions:
712                     no_unions.append(i) # No union, but add fields normally
713                 elif oneof_options.type == nanopb_pb2.FT_IGNORE:
714                     pass # No union and skip fields also
715                 else:
716                     oneof = OneOf(self.name, f)
717                     self.oneofs[i] = oneof
718                     self.fields.append(oneof)
719
720         for f in desc.field:
721             field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
722             if field_options.type == nanopb_pb2.FT_IGNORE:
723                 continue
724
725             field = Field(self.name, f, field_options)
726             if (hasattr(f, 'oneof_index') and
727                 f.HasField('oneof_index') and
728                 f.oneof_index not in no_unions):
729                 if f.oneof_index in self.oneofs:
730                     self.oneofs[f.oneof_index].add_field(field)
731             else:
732                 self.fields.append(field)
733         
734         if len(desc.extension_range) > 0:
735             field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
736             range_start = min([r.start for r in desc.extension_range])
737             if field_options.type != nanopb_pb2.FT_IGNORE:
738                 self.fields.append(ExtensionRange(self.name, range_start, field_options))
739         
740         self.packed = message_options.packed_struct
741         self.ordered_fields = self.fields[:]
742         self.ordered_fields.sort()
743
744     def get_dependencies(self):
745         '''Get list of type names that this structure refers to.'''
746         deps = []
747         for f in self.fields:
748             deps += f.get_dependencies()
749         return deps
750     
751     def __str__(self):
752         result = 'typedef struct _%s {\n' % self.name
753
754         if not self.ordered_fields:
755             # Empty structs are not allowed in C standard.
756             # Therefore add a dummy field if an empty message occurs.
757             result += '    uint8_t dummy_field;'
758
759         result += '\n'.join([str(f) for f in self.ordered_fields])
760         result += '\n}'
761         
762         if self.packed:
763             result += ' pb_packed'
764         
765         result += ' %s;' % self.name
766         
767         if self.packed:
768             result = 'PB_PACKED_STRUCT_START\n' + result
769             result += '\nPB_PACKED_STRUCT_END'
770         
771         return result
772     
773     def types(self):
774         return ''.join([f.types() for f in self.fields])
775
776     def get_initializer(self, null_init):
777         if not self.ordered_fields:
778             return '{0}'
779     
780         parts = []
781         for field in self.ordered_fields:
782             parts.append(field.get_initializer(null_init))
783         return '{' + ', '.join(parts) + '}'
784     
785     def default_decl(self, declaration_only = False):
786         result = ""
787         for field in self.fields:
788             default = field.default_decl(declaration_only)
789             if default is not None:
790                 result += default + '\n'
791         return result
792
793     def count_required_fields(self):
794         '''Returns number of required fields inside this message'''
795         count = 0
796         for f in self.fields:
797             if not isinstance(f, OneOf):
798                 if f.rules == 'REQUIRED':
799                     count += 1
800         return count
801
802     def count_all_fields(self):
803         count = 0
804         for f in self.fields:
805             if isinstance(f, OneOf):
806                 count += len(f.fields)
807             else:
808                 count += 1
809         return count
810
811     def fields_declaration(self):
812         result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1)
813         return result
814
815     def fields_definition(self):
816         result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1)
817         
818         prev = None
819         for field in self.ordered_fields:
820             result += field.pb_field_t(prev)
821             result += ',\n'
822             if isinstance(field, OneOf):
823                 prev = field.name + '.' + field.fields[-1].name
824             else:
825                 prev = field.name
826         
827         result += '    PB_LAST_FIELD\n};'
828         return result
829
830     def encoded_size(self, dependencies):
831         '''Return the maximum size that this message can take when encoded.
832         If the size cannot be determined, returns None.
833         '''
834         size = EncodedSize(0)
835         for field in self.fields:
836             fsize = field.encoded_size(dependencies)
837             if fsize is None:
838                 return None
839             size += fsize
840         
841         return size
842
843
844 # ---------------------------------------------------------------------------
845 #                    Processing of entire .proto files
846 # ---------------------------------------------------------------------------
847
848 def iterate_messages(desc, names = Names()):
849     '''Recursively find all messages. For each, yield name, DescriptorProto.'''
850     if hasattr(desc, 'message_type'):
851         submsgs = desc.message_type
852     else:
853         submsgs = desc.nested_type
854     
855     for submsg in submsgs:
856         sub_names = names + submsg.name
857         yield sub_names, submsg
858         
859         for x in iterate_messages(submsg, sub_names):
860             yield x
861
862 def iterate_extensions(desc, names = Names()):
863     '''Recursively find all extensions.
864     For each, yield name, FieldDescriptorProto.
865     '''
866     for extension in desc.extension:
867         yield names, extension
868
869     for subname, subdesc in iterate_messages(desc, names):
870         for extension in subdesc.extension:
871             yield subname, extension
872
873 def toposort2(data):
874     '''Topological sort.
875     From http://code.activestate.com/recipes/577413-topological-sort/
876     This function is under the MIT license.
877     '''
878     for k, v in data.items():
879         v.discard(k) # Ignore self dependencies
880     extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
881     data.update(dict([(item, set()) for item in extra_items_in_deps]))
882     while True:
883         ordered = set(item for item,dep in data.items() if not dep)
884         if not ordered:
885             break
886         for item in sorted(ordered):
887             yield item
888         data = dict([(item, (dep - ordered)) for item,dep in data.items()
889                 if item not in ordered])
890     assert not data, "A cyclic dependency exists amongst %r" % data
891
892 def sort_dependencies(messages):
893     '''Sort a list of Messages based on dependencies.'''
894     dependencies = {}
895     message_by_name = {}
896     for message in messages:
897         dependencies[str(message.name)] = set(message.get_dependencies())
898         message_by_name[str(message.name)] = message
899     
900     for msgname in toposort2(dependencies):
901         if msgname in message_by_name:
902             yield message_by_name[msgname]
903
904 def make_identifier(headername):
905     '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
906     result = ""
907     for c in headername.upper():
908         if c.isalnum():
909             result += c
910         else:
911             result += '_'
912     return result
913
914 class ProtoFile:
915     def __init__(self, fdesc, file_options):
916         '''Takes a FileDescriptorProto and parses it.'''
917         self.fdesc = fdesc
918         self.file_options = file_options
919         self.dependencies = {}
920         self.parse()
921         
922         # Some of types used in this file probably come from the file itself.
923         # Thus it has implicit dependency on itself.
924         self.add_dependency(self)
925
926     def parse(self):
927         self.enums = []
928         self.messages = []
929         self.extensions = []
930         
931         if self.fdesc.package:
932             base_name = Names(self.fdesc.package.split('.'))
933         else:
934             base_name = Names()
935     
936         for enum in self.fdesc.enum_type:
937             enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
938             self.enums.append(Enum(base_name, enum, enum_options))
939         
940         for names, message in iterate_messages(self.fdesc, base_name):
941             message_options = get_nanopb_suboptions(message, self.file_options, names)
942             
943             if message_options.skip_message:
944                 continue
945        
946             self.messages.append(Message(names, message, message_options))
947             for enum in message.enum_type:
948                 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
949                 self.enums.append(Enum(names, enum, enum_options))
950         
951         for names, extension in iterate_extensions(self.fdesc, base_name):
952             field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name)
953             if field_options.type != nanopb_pb2.FT_IGNORE:
954                 self.extensions.append(ExtensionField(names, extension, field_options))
955     
956     def add_dependency(self, other):
957         for enum in other.enums:
958             self.dependencies[str(enum.names)] = enum
959         
960         for msg in other.messages:
961             self.dependencies[str(msg.name)] = msg
962         
963         # Fix field default values where enum short names are used.
964         for enum in other.enums:
965             if not enum.options.long_names:
966                 for message in self.messages:
967                     for field in message.fields:
968                         if field.default in enum.value_longnames:
969                             idx = enum.value_longnames.index(field.default)
970                             field.default = enum.values[idx][0]
971         
972         # Fix field data types where enums have negative values.
973         for enum in other.enums:
974             if not enum.has_negative():
975                 for message in self.messages:
976                     for field in message.fields:
977                         if field.pbtype == 'ENUM' and field.ctype == enum.names:
978                             field.pbtype = 'UENUM'
979
980     def generate_header(self, includes, headername, options):
981         '''Generate content for a header file.
982         Generates strings, which should be concatenated and stored to file.
983         '''
984         
985         yield '/* Automatically generated nanopb header */\n'
986         if options.notimestamp:
987             yield '/* Generated by %s */\n\n' % (nanopb_version)
988         else:
989             yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
990         
991         symbol = make_identifier(headername)
992         yield '#ifndef PB_%s_INCLUDED\n' % symbol
993         yield '#define PB_%s_INCLUDED\n' % symbol
994         try:
995             yield options.libformat % ('pb.h')
996         except TypeError:
997             # no %s specified - use whatever was passed in as options.libformat
998             yield options.libformat
999         yield '\n'
1000         
1001         for incfile in includes:
1002             noext = os.path.splitext(incfile)[0]
1003             yield options.genformat % (noext + options.extension + '.h')
1004             yield '\n'
1005
1006         yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1007         yield '#error Regenerate this file with the current version of nanopb generator.\n'
1008         yield '#endif\n'
1009         yield '\n'
1010
1011         yield '#ifdef __cplusplus\n'
1012         yield 'extern "C" {\n'
1013         yield '#endif\n\n'
1014         
1015         if self.enums:
1016             yield '/* Enum definitions */\n'
1017             for enum in self.enums:
1018                 yield str(enum) + '\n\n'
1019         
1020         if self.messages:
1021             yield '/* Struct definitions */\n'
1022             for msg in sort_dependencies(self.messages):
1023                 yield msg.types()
1024                 yield str(msg) + '\n\n'
1025         
1026         if self.extensions:
1027             yield '/* Extensions */\n'
1028             for extension in self.extensions:
1029                 yield extension.extension_decl()
1030             yield '\n'
1031         
1032         if self.messages:
1033             yield '/* Default values for struct fields */\n'
1034             for msg in self.messages:
1035                 yield msg.default_decl(True)
1036             yield '\n'
1037         
1038             yield '/* Initializer values for message structs */\n'
1039             for msg in self.messages:
1040                 identifier = '%s_init_default' % msg.name
1041                 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
1042             for msg in self.messages:
1043                 identifier = '%s_init_zero' % msg.name
1044                 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
1045             yield '\n'
1046         
1047             yield '/* Field tags (for use in manual encoding/decoding) */\n'
1048             for msg in sort_dependencies(self.messages):
1049                 for field in msg.fields:
1050                     yield field.tags()
1051             for extension in self.extensions:
1052                 yield extension.tags()
1053             yield '\n'
1054         
1055             yield '/* Struct field encoding specification for nanopb */\n'
1056             for msg in self.messages:
1057                 yield msg.fields_declaration() + '\n'
1058             yield '\n'
1059         
1060             yield '/* Maximum encoded size of messages (where known) */\n'
1061             for msg in self.messages:
1062                 msize = msg.encoded_size(self.dependencies)
1063                 if msize is not None:
1064                     identifier = '%s_size' % msg.name
1065                     yield '#define %-40s %s\n' % (identifier, msize)
1066             yield '\n'
1067
1068             yield '/* Message IDs (where set with "msgid" option) */\n'
1069             
1070             yield '#ifdef PB_MSGID\n'
1071             for msg in self.messages:
1072                 if hasattr(msg,'msgid'):
1073                     yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name)
1074             yield '\n'
1075
1076             symbol = make_identifier(headername.split('.')[0])
1077             yield '#define %s_MESSAGES \\\n' % symbol
1078
1079             for msg in self.messages:
1080                 m = "-1"
1081                 msize = msg.encoded_size(self.dependencies)
1082                 if msize is not None:
1083                     m = msize
1084                 if hasattr(msg,'msgid'):
1085                     yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name)
1086             yield '\n'
1087
1088             for msg in self.messages:
1089                 if hasattr(msg,'msgid'):
1090                     yield '#define %s_msgid %d\n' % (msg.name, msg.msgid)
1091             yield '\n'
1092
1093             yield '#endif\n\n'
1094
1095         yield '#ifdef __cplusplus\n'
1096         yield '} /* extern "C" */\n'
1097         yield '#endif\n'
1098         
1099         # End of header
1100         yield '\n#endif\n'
1101
1102     def generate_source(self, headername, options):
1103         '''Generate content for a source file.'''
1104         
1105         yield '/* Automatically generated nanopb constant definitions */\n'
1106         if options.notimestamp:
1107             yield '/* Generated by %s */\n\n' % (nanopb_version)
1108         else:
1109             yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1110         yield options.genformat % (headername)
1111         yield '\n'
1112         
1113         yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1114         yield '#error Regenerate this file with the current version of nanopb generator.\n'
1115         yield '#endif\n'
1116         yield '\n'
1117         
1118         for msg in self.messages:
1119             yield msg.default_decl(False)
1120         
1121         yield '\n\n'
1122         
1123         for msg in self.messages:
1124             yield msg.fields_definition() + '\n\n'
1125         
1126         for ext in self.extensions:
1127             yield ext.extension_def() + '\n'
1128             
1129         # Add checks for numeric limits
1130         if self.messages:
1131             largest_msg = max(self.messages, key = lambda m: m.count_required_fields())
1132             largest_count = largest_msg.count_required_fields()
1133             if largest_count > 64:
1134                 yield '\n/* Check that missing required fields will be properly detected */\n'
1135                 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
1136                 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
1137                 yield '       setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
1138                 yield '#endif\n'
1139         
1140         worst = 0
1141         worst_field = ''
1142         checks = []
1143         checks_msgnames = []
1144         for msg in self.messages:
1145             checks_msgnames.append(msg.name)
1146             for field in msg.fields:
1147                 status = field.largest_field_value()
1148                 if isinstance(status, (str, unicode)):
1149                     checks.append(status)
1150                 elif status > worst:
1151                     worst = status
1152                     worst_field = str(field.struct_name) + '.' + str(field.name)
1153
1154         if worst > 255 or checks:
1155             yield '\n/* Check that field information fits in pb_field_t */\n'
1156             
1157             if worst > 65535 or checks:
1158                 yield '#if !defined(PB_FIELD_32BIT)\n'
1159                 if worst > 65535:
1160                     yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
1161                 else:
1162                     assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
1163                     msgs = '_'.join(str(n) for n in checks_msgnames)
1164                     yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n'
1165                     yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1166                     yield ' * \n'
1167                     yield ' * The reason you need to do this is that some of your messages contain tag\n'
1168                     yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n'
1169                     yield ' * field descriptors.\n'
1170                     yield ' */\n'
1171                     yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1172                 yield '#endif\n\n'
1173             
1174             if worst < 65536:
1175                 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
1176                 if worst > 255:
1177                     yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
1178                 else:
1179                     assertion = ' && '.join(str(c) + ' < 256' for c in checks)
1180                     msgs = '_'.join(str(n) for n in checks_msgnames)
1181                     yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
1182                     yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1183                     yield ' * \n'
1184                     yield ' * The reason you need to do this is that some of your messages contain tag\n'
1185                     yield ' * numbers or field sizes that are larger than what can fit in the default\n'
1186                     yield ' * 8 bit descriptors.\n'
1187                     yield ' */\n'
1188                     yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1189                 yield '#endif\n\n'
1190         
1191         # Add check for sizeof(double)
1192         has_double = False
1193         for msg in self.messages:
1194             for field in msg.fields:
1195                 if field.ctype == 'double':
1196                     has_double = True
1197         
1198         if has_double:
1199             yield '\n'
1200             yield '/* On some platforms (such as AVR), double is really float.\n'
1201             yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
1202             yield ' * To get rid of this error, remove any double fields from your .proto.\n'
1203             yield ' */\n'
1204             yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
1205         
1206         yield '\n'
1207
1208 # ---------------------------------------------------------------------------
1209 #                    Options parsing for the .proto files
1210 # ---------------------------------------------------------------------------
1211
1212 from fnmatch import fnmatch
1213
1214 def read_options_file(infile):
1215     '''Parse a separate options file to list:
1216         [(namemask, options), ...]
1217     '''
1218     results = []
1219     data = infile.read()
1220     data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE)
1221     data = re.sub('//.*?$', '', data, flags = re.MULTILINE)
1222     data = re.sub('#.*?$', '', data, flags = re.MULTILINE)
1223     for i, line in enumerate(data.split('\n')):
1224         line = line.strip()
1225         if not line:
1226             continue
1227         
1228         parts = line.split(None, 1)
1229         
1230         if len(parts) < 2:
1231             sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1232                              "Option lines should have space between field name and options. " +
1233                              "Skipping line: '%s'\n" % line)
1234             continue
1235         
1236         opts = nanopb_pb2.NanoPBOptions()
1237         
1238         try:
1239             text_format.Merge(parts[1], opts)
1240         except Exception, e:
1241             sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1242                              "Unparseable option line: '%s'. " % line +
1243                              "Error: %s\n" % str(e))
1244             continue
1245         results.append((parts[0], opts))
1246
1247     return results
1248
1249 class Globals:
1250     '''Ugly global variables, should find a good way to pass these.'''
1251     verbose_options = False
1252     separate_options = []
1253     matched_namemasks = set()
1254
1255 def get_nanopb_suboptions(subdesc, options, name):
1256     '''Get copy of options, and merge information from subdesc.'''
1257     new_options = nanopb_pb2.NanoPBOptions()
1258     new_options.CopyFrom(options)
1259     
1260     # Handle options defined in a separate file
1261     dotname = '.'.join(name.parts)
1262     for namemask, options in Globals.separate_options:
1263         if fnmatch(dotname, namemask):
1264             Globals.matched_namemasks.add(namemask)
1265             new_options.MergeFrom(options)
1266     
1267     # Handle options defined in .proto
1268     if isinstance(subdesc.options, descriptor.FieldOptions):
1269         ext_type = nanopb_pb2.nanopb
1270     elif isinstance(subdesc.options, descriptor.FileOptions):
1271         ext_type = nanopb_pb2.nanopb_fileopt
1272     elif isinstance(subdesc.options, descriptor.MessageOptions):
1273         ext_type = nanopb_pb2.nanopb_msgopt
1274     elif isinstance(subdesc.options, descriptor.EnumOptions):
1275         ext_type = nanopb_pb2.nanopb_enumopt
1276     else:
1277         raise Exception("Unknown options type")
1278     
1279     if subdesc.options.HasExtension(ext_type):
1280         ext = subdesc.options.Extensions[ext_type]
1281         new_options.MergeFrom(ext)
1282     
1283     if Globals.verbose_options:
1284         sys.stderr.write("Options for " + dotname + ": ")
1285         sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1286     
1287     return new_options
1288
1289
1290 # ---------------------------------------------------------------------------
1291 #                         Command line interface
1292 # ---------------------------------------------------------------------------
1293
1294 import sys
1295 import os.path    
1296 from optparse import OptionParser
1297
1298 optparser = OptionParser(
1299     usage = "Usage: nanopb_generator.py [options] file.pb ...",
1300     epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1301              "Output will be written to file.pb.h and file.pb.c.")
1302 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1303     help="Exclude file from generated #include list.")
1304 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1305     help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1306 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1307     help="Set name of a separate generator options file.")
1308 optparser.add_option("-I", "--options-path", dest="options_path", metavar="DIR",
1309     action="append", default = [],
1310     help="Search for .options files additionally in this path")
1311 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1312     metavar="FORMAT", default='#include "%s"\n',
1313     help="Set format string to use for including other .pb.h files. [default: %default]")
1314 optparser.add_option("-L", "--library-include-format", dest="libformat",
1315     metavar="FORMAT", default='#include <%s>\n',
1316     help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1317 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1318     help="Don't add timestamp to .pb.h and .pb.c preambles")
1319 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1320     help="Don't print anything except errors.")
1321 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1322     help="Print more information.")
1323 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1324     help="Set generator option (max_size, max_count etc.).")
1325
1326 def parse_file(filename, fdesc, options):
1327     '''Parse a single file. Returns a ProtoFile instance.'''
1328     toplevel_options = nanopb_pb2.NanoPBOptions()
1329     for s in options.settings:
1330         text_format.Merge(s, toplevel_options)
1331     
1332     if not fdesc:
1333         data = open(filename, 'rb').read()
1334         fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1335     
1336     # Check if there is a separate .options file
1337     had_abspath = False
1338     try:
1339         optfilename = options.options_file % os.path.splitext(filename)[0]
1340     except TypeError:
1341         # No %s specified, use the filename as-is
1342         optfilename = options.options_file
1343         had_abspath = True
1344
1345     paths = ['.'] + options.options_path
1346     for p in paths:
1347         if os.path.isfile(os.path.join(p, optfilename)):
1348             optfilename = os.path.join(p, optfilename)
1349             if options.verbose:
1350                 sys.stderr.write('Reading options from ' + optfilename + '\n')
1351             Globals.separate_options = read_options_file(open(optfilename, "rU"))
1352             break
1353     else:
1354         # If we are given a full filename and it does not exist, give an error.
1355         # However, don't give error when we automatically look for .options file
1356         # with the same name as .proto.
1357         if options.verbose or had_abspath:
1358             sys.stderr.write('Options file not found: ' + optfilename + '\n')
1359         Globals.separate_options = []
1360
1361     Globals.matched_namemasks = set()
1362     
1363     # Parse the file
1364     file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1365     f = ProtoFile(fdesc, file_options)
1366     f.optfilename = optfilename
1367     
1368     return f
1369
1370 def process_file(filename, fdesc, options, other_files = {}):
1371     '''Process a single file.
1372     filename: The full path to the .proto or .pb source file, as string.
1373     fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1374     options: Command line options as they come from OptionsParser.
1375     
1376     Returns a dict:
1377         {'headername': Name of header file,
1378          'headerdata': Data for the .h header file,
1379          'sourcename': Name of the source code file,
1380          'sourcedata': Data for the .c source code file
1381         }
1382     '''
1383     f = parse_file(filename, fdesc, options)
1384
1385     # Provide dependencies if available
1386     for dep in f.fdesc.dependency:
1387         if dep in other_files:
1388             f.add_dependency(other_files[dep])
1389
1390     # Decide the file names
1391     noext = os.path.splitext(filename)[0]
1392     headername = noext + options.extension + '.h'
1393     sourcename = noext + options.extension + '.c'
1394     headerbasename = os.path.basename(headername)
1395     
1396     # List of .proto files that should not be included in the C header file
1397     # even if they are mentioned in the source .proto.
1398     excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1399     includes = [d for d in f.fdesc.dependency if d not in excludes]
1400     
1401     headerdata = ''.join(f.generate_header(includes, headerbasename, options))
1402     sourcedata = ''.join(f.generate_source(headerbasename, options))
1403
1404     # Check if there were any lines in .options that did not match a member
1405     unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1406     if unmatched and not options.quiet:
1407         sys.stderr.write("Following patterns in " + f.optfilename + " did not match any fields: "
1408                          + ', '.join(unmatched) + "\n")
1409         if not Globals.verbose_options:
1410             sys.stderr.write("Use  protoc --nanopb-out=-v:.   to see a list of the field names.\n")
1411
1412     return {'headername': headername, 'headerdata': headerdata,
1413             'sourcename': sourcename, 'sourcedata': sourcedata}
1414     
1415 def main_cli():
1416     '''Main function when invoked directly from the command line.'''
1417     
1418     options, filenames = optparser.parse_args()
1419     
1420     if not filenames:
1421         optparser.print_help()
1422         sys.exit(1)
1423     
1424     if options.quiet:
1425         options.verbose = False
1426
1427     Globals.verbose_options = options.verbose
1428     
1429     for filename in filenames:
1430         results = process_file(filename, None, options)
1431         
1432         if not options.quiet:
1433             sys.stderr.write("Writing to " + results['headername'] + " and "
1434                              + results['sourcename'] + "\n")
1435     
1436         open(results['headername'], 'w').write(results['headerdata'])
1437         open(results['sourcename'], 'w').write(results['sourcedata'])        
1438
1439 def main_plugin():
1440     '''Main function when invoked as a protoc plugin.'''
1441
1442     import sys
1443     if sys.platform == "win32":
1444         import os, msvcrt
1445         # Set stdin and stdout to binary mode
1446         msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1447         msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1448     
1449     data = sys.stdin.read()
1450     request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1451     
1452     try:
1453         # Versions of Python prior to 2.7.3 do not support unicode
1454         # input to shlex.split(). Try to convert to str if possible.
1455         params = str(request.parameter)
1456     except UnicodeEncodeError:
1457         params = request.parameter
1458     
1459     import shlex
1460     args = shlex.split(params)
1461     options, dummy = optparser.parse_args(args)
1462     
1463     Globals.verbose_options = options.verbose
1464     
1465     response = plugin_pb2.CodeGeneratorResponse()
1466     
1467     # Google's protoc does not currently indicate the full path of proto files.
1468     # Instead always add the main file path to the search dirs, that works for
1469     # the common case.
1470     import os.path
1471     options.options_path.append(os.path.dirname(request.file_to_generate[0]))
1472     
1473     # Process any include files first, in order to have them
1474     # available as dependencies
1475     other_files = {}
1476     for fdesc in request.proto_file:
1477         other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options)
1478     
1479     for filename in request.file_to_generate:
1480         for fdesc in request.proto_file:
1481             if fdesc.name == filename:
1482                 results = process_file(filename, fdesc, options, other_files)
1483                 
1484                 f = response.file.add()
1485                 f.name = results['headername']
1486                 f.content = results['headerdata']
1487
1488                 f = response.file.add()
1489                 f.name = results['sourcename']
1490                 f.content = results['sourcedata']    
1491     
1492     sys.stdout.write(response.SerializeToString())
1493
1494 if __name__ == '__main__':
1495     # Check if we are running as a plugin under protoc
1496     if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv:
1497         main_plugin()
1498     else:
1499         main_cli()
1500