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