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