nanopb_generator.py 60 KB

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