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