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