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