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