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