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