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