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