text_format.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # https://developers.google.com/protocol-buffers/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Contains routines for printing protocol messages in text format.
  31. Simple usage example:
  32. # Create a proto object and serialize it to a text proto string.
  33. message = my_proto_pb2.MyMessage(foo='bar')
  34. text_proto = text_format.MessageToString(message)
  35. # Parse a text proto string.
  36. message = text_format.Parse(text_proto, my_proto_pb2.MyMessage())
  37. """
  38. __author__ = 'kenton@google.com (Kenton Varda)'
  39. import io
  40. import re
  41. import six
  42. if six.PY3:
  43. long = int # pylint: disable=redefined-builtin,invalid-name
  44. # pylint: disable=g-import-not-at-top
  45. from google.protobuf.internal import type_checkers
  46. from google.protobuf import descriptor
  47. from google.protobuf import text_encoding
  48. __all__ = ['MessageToString', 'PrintMessage', 'PrintField', 'PrintFieldValue',
  49. 'Merge']
  50. _INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(),
  51. type_checkers.Int32ValueChecker(),
  52. type_checkers.Uint64ValueChecker(),
  53. type_checkers.Int64ValueChecker())
  54. _FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?', re.IGNORECASE)
  55. _FLOAT_NAN = re.compile('nanf?', re.IGNORECASE)
  56. _FLOAT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_FLOAT,
  57. descriptor.FieldDescriptor.CPPTYPE_DOUBLE])
  58. _QUOTES = frozenset(("'", '"'))
  59. _ANY_FULL_TYPE_NAME = 'google.protobuf.Any'
  60. class Error(Exception):
  61. """Top-level module error for text_format."""
  62. class ParseError(Error):
  63. """Thrown in case of text parsing or tokenizing error."""
  64. def __init__(self, message=None, line=None, column=None):
  65. if message is not None and line is not None:
  66. loc = str(line)
  67. if column is not None:
  68. loc += ':{0}'.format(column)
  69. message = '{0} : {1}'.format(loc, message)
  70. if message is not None:
  71. super(ParseError, self).__init__(message)
  72. else:
  73. super(ParseError, self).__init__()
  74. self._line = line
  75. self._column = column
  76. def GetLine(self):
  77. return self._line
  78. def GetColumn(self):
  79. return self._column
  80. class TextWriter(object):
  81. def __init__(self, as_utf8):
  82. if six.PY2:
  83. self._writer = io.BytesIO()
  84. else:
  85. self._writer = io.StringIO()
  86. def write(self, val):
  87. if six.PY2:
  88. if isinstance(val, six.text_type):
  89. val = val.encode('utf-8')
  90. return self._writer.write(val)
  91. def close(self):
  92. return self._writer.close()
  93. def getvalue(self):
  94. return self._writer.getvalue()
  95. def MessageToString(message,
  96. as_utf8=False,
  97. as_one_line=False,
  98. pointy_brackets=False,
  99. use_index_order=False,
  100. float_format=None,
  101. use_field_number=False,
  102. descriptor_pool=None,
  103. indent=0):
  104. """Convert protobuf message to text format.
  105. Floating point values can be formatted compactly with 15 digits of
  106. precision (which is the most that IEEE 754 "double" can guarantee)
  107. using float_format='.15g'. To ensure that converting to text and back to a
  108. proto will result in an identical value, float_format='.17g' should be used.
  109. Args:
  110. message: The protocol buffers message.
  111. as_utf8: Produce text output in UTF8 format.
  112. as_one_line: Don't introduce newlines between fields.
  113. pointy_brackets: If True, use angle brackets instead of curly braces for
  114. nesting.
  115. use_index_order: If True, print fields of a proto message using the order
  116. defined in source code instead of the field number. By default, use the
  117. field number order.
  118. float_format: If set, use this to specify floating point number formatting
  119. (per the "Format Specification Mini-Language"); otherwise, str() is used.
  120. use_field_number: If True, print field numbers instead of names.
  121. descriptor_pool: A DescriptorPool used to resolve Any types.
  122. indent: The indent level, in terms of spaces, for pretty print.
  123. Returns:
  124. A string of the text formatted protocol buffer message.
  125. """
  126. out = TextWriter(as_utf8)
  127. printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
  128. use_index_order, float_format, use_field_number,
  129. descriptor_pool)
  130. printer.PrintMessage(message)
  131. result = out.getvalue()
  132. out.close()
  133. if as_one_line:
  134. return result.rstrip()
  135. return result
  136. def _IsMapEntry(field):
  137. return (field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  138. field.message_type.has_options and
  139. field.message_type.GetOptions().map_entry)
  140. def PrintMessage(message,
  141. out,
  142. indent=0,
  143. as_utf8=False,
  144. as_one_line=False,
  145. pointy_brackets=False,
  146. use_index_order=False,
  147. float_format=None,
  148. use_field_number=False,
  149. descriptor_pool=None):
  150. printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
  151. use_index_order, float_format, use_field_number,
  152. descriptor_pool)
  153. printer.PrintMessage(message)
  154. def PrintField(field,
  155. value,
  156. out,
  157. indent=0,
  158. as_utf8=False,
  159. as_one_line=False,
  160. pointy_brackets=False,
  161. use_index_order=False,
  162. float_format=None):
  163. """Print a single field name/value pair."""
  164. printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
  165. use_index_order, float_format)
  166. printer.PrintField(field, value)
  167. def PrintFieldValue(field,
  168. value,
  169. out,
  170. indent=0,
  171. as_utf8=False,
  172. as_one_line=False,
  173. pointy_brackets=False,
  174. use_index_order=False,
  175. float_format=None):
  176. """Print a single field value (not including name)."""
  177. printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
  178. use_index_order, float_format)
  179. printer.PrintFieldValue(field, value)
  180. def _BuildMessageFromTypeName(type_name, descriptor_pool):
  181. """Returns a protobuf message instance.
  182. Args:
  183. type_name: Fully-qualified protobuf message type name string.
  184. descriptor_pool: DescriptorPool instance.
  185. Returns:
  186. A Message instance of type matching type_name, or None if the a Descriptor
  187. wasn't found matching type_name.
  188. """
  189. # pylint: disable=g-import-not-at-top
  190. from google.protobuf import symbol_database
  191. database = symbol_database.Default()
  192. try:
  193. message_descriptor = descriptor_pool.FindMessageTypeByName(type_name)
  194. except KeyError:
  195. return None
  196. message_type = database.GetPrototype(message_descriptor)
  197. return message_type()
  198. class _Printer(object):
  199. """Text format printer for protocol message."""
  200. def __init__(self,
  201. out,
  202. indent=0,
  203. as_utf8=False,
  204. as_one_line=False,
  205. pointy_brackets=False,
  206. use_index_order=False,
  207. float_format=None,
  208. use_field_number=False,
  209. descriptor_pool=None):
  210. """Initialize the Printer.
  211. Floating point values can be formatted compactly with 15 digits of
  212. precision (which is the most that IEEE 754 "double" can guarantee)
  213. using float_format='.15g'. To ensure that converting to text and back to a
  214. proto will result in an identical value, float_format='.17g' should be used.
  215. Args:
  216. out: To record the text format result.
  217. indent: The indent level for pretty print.
  218. as_utf8: Produce text output in UTF8 format.
  219. as_one_line: Don't introduce newlines between fields.
  220. pointy_brackets: If True, use angle brackets instead of curly braces for
  221. nesting.
  222. use_index_order: If True, print fields of a proto message using the order
  223. defined in source code instead of the field number. By default, use the
  224. field number order.
  225. float_format: If set, use this to specify floating point number formatting
  226. (per the "Format Specification Mini-Language"); otherwise, str() is
  227. used.
  228. use_field_number: If True, print field numbers instead of names.
  229. descriptor_pool: A DescriptorPool used to resolve Any types.
  230. """
  231. self.out = out
  232. self.indent = indent
  233. self.as_utf8 = as_utf8
  234. self.as_one_line = as_one_line
  235. self.pointy_brackets = pointy_brackets
  236. self.use_index_order = use_index_order
  237. self.float_format = float_format
  238. self.use_field_number = use_field_number
  239. self.descriptor_pool = descriptor_pool
  240. def _TryPrintAsAnyMessage(self, message):
  241. """Serializes if message is a google.protobuf.Any field."""
  242. packed_message = _BuildMessageFromTypeName(message.TypeName(),
  243. self.descriptor_pool)
  244. if packed_message:
  245. packed_message.MergeFromString(message.value)
  246. self.out.write('%s[%s]' % (self.indent * ' ', message.type_url))
  247. self._PrintMessageFieldValue(packed_message)
  248. self.out.write(' ' if self.as_one_line else '\n')
  249. return True
  250. else:
  251. return False
  252. def PrintMessage(self, message):
  253. """Convert protobuf message to text format.
  254. Args:
  255. message: The protocol buffers message.
  256. """
  257. if (message.DESCRIPTOR.full_name == _ANY_FULL_TYPE_NAME and
  258. self.descriptor_pool and self._TryPrintAsAnyMessage(message)):
  259. return
  260. fields = message.ListFields()
  261. if self.use_index_order:
  262. fields.sort(key=lambda x: x[0].index)
  263. for field, value in fields:
  264. if _IsMapEntry(field):
  265. for key in sorted(value):
  266. # This is slow for maps with submessage entires because it copies the
  267. # entire tree. Unfortunately this would take significant refactoring
  268. # of this file to work around.
  269. #
  270. # TODO(haberman): refactor and optimize if this becomes an issue.
  271. entry_submsg = value.GetEntryClass()(key=key, value=value[key])
  272. self.PrintField(field, entry_submsg)
  273. elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  274. for element in value:
  275. self.PrintField(field, element)
  276. else:
  277. self.PrintField(field, value)
  278. def PrintField(self, field, value):
  279. """Print a single field name/value pair."""
  280. out = self.out
  281. out.write(' ' * self.indent)
  282. if self.use_field_number:
  283. out.write(str(field.number))
  284. else:
  285. if field.is_extension:
  286. out.write('[')
  287. if (field.containing_type.GetOptions().message_set_wire_format and
  288. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  289. field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL):
  290. out.write(field.message_type.full_name)
  291. else:
  292. out.write(field.full_name)
  293. out.write(']')
  294. elif field.type == descriptor.FieldDescriptor.TYPE_GROUP:
  295. # For groups, use the capitalized name.
  296. out.write(field.message_type.name)
  297. else:
  298. out.write(field.name)
  299. if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  300. # The colon is optional in this case, but our cross-language golden files
  301. # don't include it.
  302. out.write(': ')
  303. self.PrintFieldValue(field, value)
  304. if self.as_one_line:
  305. out.write(' ')
  306. else:
  307. out.write('\n')
  308. def _PrintMessageFieldValue(self, value):
  309. if self.pointy_brackets:
  310. openb = '<'
  311. closeb = '>'
  312. else:
  313. openb = '{'
  314. closeb = '}'
  315. if self.as_one_line:
  316. self.out.write(' %s ' % openb)
  317. self.PrintMessage(value)
  318. self.out.write(closeb)
  319. else:
  320. self.out.write(' %s\n' % openb)
  321. self.indent += 2
  322. self.PrintMessage(value)
  323. self.indent -= 2
  324. self.out.write(' ' * self.indent + closeb)
  325. def PrintFieldValue(self, field, value):
  326. """Print a single field value (not including name).
  327. For repeated fields, the value should be a single element.
  328. Args:
  329. field: The descriptor of the field to be printed.
  330. value: The value of the field.
  331. """
  332. out = self.out
  333. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  334. self._PrintMessageFieldValue(value)
  335. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
  336. enum_value = field.enum_type.values_by_number.get(value, None)
  337. if enum_value is not None:
  338. out.write(enum_value.name)
  339. else:
  340. out.write(str(value))
  341. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
  342. out.write('\"')
  343. if isinstance(value, six.text_type):
  344. out_value = value.encode('utf-8')
  345. else:
  346. out_value = value
  347. if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  348. # We need to escape non-UTF8 chars in TYPE_BYTES field.
  349. out_as_utf8 = False
  350. else:
  351. out_as_utf8 = self.as_utf8
  352. out.write(text_encoding.CEscape(out_value, out_as_utf8))
  353. out.write('\"')
  354. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
  355. if value:
  356. out.write('true')
  357. else:
  358. out.write('false')
  359. elif field.cpp_type in _FLOAT_TYPES and self.float_format is not None:
  360. out.write('{1:{0}}'.format(self.float_format, value))
  361. else:
  362. out.write(str(value))
  363. def Parse(text,
  364. message,
  365. allow_unknown_extension=False,
  366. allow_field_number=False,
  367. descriptor_pool=None):
  368. """Parses a text representation of a protocol message into a message.
  369. Args:
  370. text: Message text representation.
  371. message: A protocol buffer message to merge into.
  372. allow_unknown_extension: if True, skip over missing extensions and keep
  373. parsing
  374. allow_field_number: if True, both field number and field name are allowed.
  375. descriptor_pool: A DescriptorPool used to resolve Any types.
  376. Returns:
  377. The same message passed as argument.
  378. Raises:
  379. ParseError: On text parsing problems.
  380. """
  381. if not isinstance(text, str):
  382. text = text.decode('utf-8')
  383. return ParseLines(text.split('\n'),
  384. message,
  385. allow_unknown_extension,
  386. allow_field_number,
  387. descriptor_pool=descriptor_pool)
  388. def Merge(text,
  389. message,
  390. allow_unknown_extension=False,
  391. allow_field_number=False,
  392. descriptor_pool=None):
  393. """Parses a text representation of a protocol message into a message.
  394. Like Parse(), but allows repeated values for a non-repeated field, and uses
  395. the last one.
  396. Args:
  397. text: Message text representation.
  398. message: A protocol buffer message to merge into.
  399. allow_unknown_extension: if True, skip over missing extensions and keep
  400. parsing
  401. allow_field_number: if True, both field number and field name are allowed.
  402. descriptor_pool: A DescriptorPool used to resolve Any types.
  403. Returns:
  404. The same message passed as argument.
  405. Raises:
  406. ParseError: On text parsing problems.
  407. """
  408. return MergeLines(
  409. text.split('\n'),
  410. message,
  411. allow_unknown_extension,
  412. allow_field_number,
  413. descriptor_pool=descriptor_pool)
  414. def ParseLines(lines,
  415. message,
  416. allow_unknown_extension=False,
  417. allow_field_number=False,
  418. descriptor_pool=None):
  419. """Parses a text representation of a protocol message into a message.
  420. Args:
  421. lines: An iterable of lines of a message's text representation.
  422. message: A protocol buffer message to merge into.
  423. allow_unknown_extension: if True, skip over missing extensions and keep
  424. parsing
  425. allow_field_number: if True, both field number and field name are allowed.
  426. descriptor_pool: A DescriptorPool used to resolve Any types.
  427. Returns:
  428. The same message passed as argument.
  429. Raises:
  430. ParseError: On text parsing problems.
  431. """
  432. parser = _Parser(allow_unknown_extension,
  433. allow_field_number,
  434. descriptor_pool=descriptor_pool)
  435. return parser.ParseLines(lines, message)
  436. def MergeLines(lines,
  437. message,
  438. allow_unknown_extension=False,
  439. allow_field_number=False,
  440. descriptor_pool=None):
  441. """Parses a text representation of a protocol message into a message.
  442. Args:
  443. lines: An iterable of lines of a message's text representation.
  444. message: A protocol buffer message to merge into.
  445. allow_unknown_extension: if True, skip over missing extensions and keep
  446. parsing
  447. allow_field_number: if True, both field number and field name are allowed.
  448. descriptor_pool: A DescriptorPool used to resolve Any types.
  449. Returns:
  450. The same message passed as argument.
  451. Raises:
  452. ParseError: On text parsing problems.
  453. """
  454. parser = _Parser(allow_unknown_extension,
  455. allow_field_number,
  456. descriptor_pool=descriptor_pool)
  457. return parser.MergeLines(lines, message)
  458. class _Parser(object):
  459. """Text format parser for protocol message."""
  460. def __init__(self,
  461. allow_unknown_extension=False,
  462. allow_field_number=False,
  463. descriptor_pool=None):
  464. self.allow_unknown_extension = allow_unknown_extension
  465. self.allow_field_number = allow_field_number
  466. self.descriptor_pool = descriptor_pool
  467. def ParseFromString(self, text, message):
  468. """Parses a text representation of a protocol message into a message."""
  469. if not isinstance(text, str):
  470. text = text.decode('utf-8')
  471. return self.ParseLines(text.split('\n'), message)
  472. def ParseLines(self, lines, message):
  473. """Parses a text representation of a protocol message into a message."""
  474. self._allow_multiple_scalars = False
  475. self._ParseOrMerge(lines, message)
  476. return message
  477. def MergeFromString(self, text, message):
  478. """Merges a text representation of a protocol message into a message."""
  479. return self._MergeLines(text.split('\n'), message)
  480. def MergeLines(self, lines, message):
  481. """Merges a text representation of a protocol message into a message."""
  482. self._allow_multiple_scalars = True
  483. self._ParseOrMerge(lines, message)
  484. return message
  485. def _ParseOrMerge(self, lines, message):
  486. """Converts a text representation of a protocol message into a message.
  487. Args:
  488. lines: Lines of a message's text representation.
  489. message: A protocol buffer message to merge into.
  490. Raises:
  491. ParseError: On text parsing problems.
  492. """
  493. tokenizer = Tokenizer(lines)
  494. while not tokenizer.AtEnd():
  495. self._MergeField(tokenizer, message)
  496. def _MergeField(self, tokenizer, message):
  497. """Merges a single protocol message field into a message.
  498. Args:
  499. tokenizer: A tokenizer to parse the field name and values.
  500. message: A protocol message to record the data.
  501. Raises:
  502. ParseError: In case of text parsing problems.
  503. """
  504. message_descriptor = message.DESCRIPTOR
  505. if (hasattr(message_descriptor, 'syntax') and
  506. message_descriptor.syntax == 'proto3'):
  507. # Proto3 doesn't represent presence so we can't test if multiple
  508. # scalars have occurred. We have to allow them.
  509. self._allow_multiple_scalars = True
  510. if tokenizer.TryConsume('['):
  511. name = [tokenizer.ConsumeIdentifier()]
  512. while tokenizer.TryConsume('.'):
  513. name.append(tokenizer.ConsumeIdentifier())
  514. name = '.'.join(name)
  515. if not message_descriptor.is_extendable:
  516. raise tokenizer.ParseErrorPreviousToken(
  517. 'Message type "%s" does not have extensions.' %
  518. message_descriptor.full_name)
  519. # pylint: disable=protected-access
  520. field = message.Extensions._FindExtensionByName(name)
  521. # pylint: enable=protected-access
  522. if not field:
  523. if self.allow_unknown_extension:
  524. field = None
  525. else:
  526. raise tokenizer.ParseErrorPreviousToken(
  527. 'Extension "%s" not registered.' % name)
  528. elif message_descriptor != field.containing_type:
  529. raise tokenizer.ParseErrorPreviousToken(
  530. 'Extension "%s" does not extend message type "%s".' %
  531. (name, message_descriptor.full_name))
  532. tokenizer.Consume(']')
  533. else:
  534. name = tokenizer.ConsumeIdentifierOrNumber()
  535. if self.allow_field_number and name.isdigit():
  536. number = ParseInteger(name, True, True)
  537. field = message_descriptor.fields_by_number.get(number, None)
  538. if not field and message_descriptor.is_extendable:
  539. field = message.Extensions._FindExtensionByNumber(number)
  540. else:
  541. field = message_descriptor.fields_by_name.get(name, None)
  542. # Group names are expected to be capitalized as they appear in the
  543. # .proto file, which actually matches their type names, not their field
  544. # names.
  545. if not field:
  546. field = message_descriptor.fields_by_name.get(name.lower(), None)
  547. if field and field.type != descriptor.FieldDescriptor.TYPE_GROUP:
  548. field = None
  549. if (field and field.type == descriptor.FieldDescriptor.TYPE_GROUP and
  550. field.message_type.name != name):
  551. field = None
  552. if not field:
  553. raise tokenizer.ParseErrorPreviousToken(
  554. 'Message type "%s" has no field named "%s".' %
  555. (message_descriptor.full_name, name))
  556. if field:
  557. if not self._allow_multiple_scalars and field.containing_oneof:
  558. # Check if there's a different field set in this oneof.
  559. # Note that we ignore the case if the same field was set before, and we
  560. # apply _allow_multiple_scalars to non-scalar fields as well.
  561. which_oneof = message.WhichOneof(field.containing_oneof.name)
  562. if which_oneof is not None and which_oneof != field.name:
  563. raise tokenizer.ParseErrorPreviousToken(
  564. 'Field "%s" is specified along with field "%s", another member '
  565. 'of oneof "%s" for message type "%s".' %
  566. (field.name, which_oneof, field.containing_oneof.name,
  567. message_descriptor.full_name))
  568. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  569. tokenizer.TryConsume(':')
  570. merger = self._MergeMessageField
  571. else:
  572. tokenizer.Consume(':')
  573. merger = self._MergeScalarField
  574. if (field.label == descriptor.FieldDescriptor.LABEL_REPEATED and
  575. tokenizer.TryConsume('[')):
  576. # Short repeated format, e.g. "foo: [1, 2, 3]"
  577. while True:
  578. merger(tokenizer, message, field)
  579. if tokenizer.TryConsume(']'):
  580. break
  581. tokenizer.Consume(',')
  582. else:
  583. merger(tokenizer, message, field)
  584. else: # Proto field is unknown.
  585. assert self.allow_unknown_extension
  586. _SkipFieldContents(tokenizer)
  587. # For historical reasons, fields may optionally be separated by commas or
  588. # semicolons.
  589. if not tokenizer.TryConsume(','):
  590. tokenizer.TryConsume(';')
  591. def _ConsumeAnyTypeUrl(self, tokenizer):
  592. """Consumes a google.protobuf.Any type URL and returns the type name."""
  593. # Consume "type.googleapis.com/".
  594. tokenizer.ConsumeIdentifier()
  595. tokenizer.Consume('.')
  596. tokenizer.ConsumeIdentifier()
  597. tokenizer.Consume('.')
  598. tokenizer.ConsumeIdentifier()
  599. tokenizer.Consume('/')
  600. # Consume the fully-qualified type name.
  601. name = [tokenizer.ConsumeIdentifier()]
  602. while tokenizer.TryConsume('.'):
  603. name.append(tokenizer.ConsumeIdentifier())
  604. return '.'.join(name)
  605. def _MergeMessageField(self, tokenizer, message, field):
  606. """Merges a single scalar field into a message.
  607. Args:
  608. tokenizer: A tokenizer to parse the field value.
  609. message: The message of which field is a member.
  610. field: The descriptor of the field to be merged.
  611. Raises:
  612. ParseError: In case of text parsing problems.
  613. """
  614. is_map_entry = _IsMapEntry(field)
  615. if tokenizer.TryConsume('<'):
  616. end_token = '>'
  617. else:
  618. tokenizer.Consume('{')
  619. end_token = '}'
  620. if (field.message_type.full_name == _ANY_FULL_TYPE_NAME and
  621. tokenizer.TryConsume('[')):
  622. packed_type_name = self._ConsumeAnyTypeUrl(tokenizer)
  623. tokenizer.Consume(']')
  624. tokenizer.TryConsume(':')
  625. if tokenizer.TryConsume('<'):
  626. expanded_any_end_token = '>'
  627. else:
  628. tokenizer.Consume('{')
  629. expanded_any_end_token = '}'
  630. if not self.descriptor_pool:
  631. raise ParseError('Descriptor pool required to parse expanded Any field')
  632. expanded_any_sub_message = _BuildMessageFromTypeName(packed_type_name,
  633. self.descriptor_pool)
  634. if not expanded_any_sub_message:
  635. raise ParseError('Type %s not found in descriptor pool' %
  636. packed_type_name)
  637. while not tokenizer.TryConsume(expanded_any_end_token):
  638. if tokenizer.AtEnd():
  639. raise tokenizer.ParseErrorPreviousToken('Expected "%s".' %
  640. (expanded_any_end_token,))
  641. self._MergeField(tokenizer, expanded_any_sub_message)
  642. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  643. any_message = getattr(message, field.name).add()
  644. else:
  645. any_message = getattr(message, field.name)
  646. any_message.Pack(expanded_any_sub_message)
  647. elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  648. if field.is_extension:
  649. sub_message = message.Extensions[field].add()
  650. elif is_map_entry:
  651. sub_message = getattr(message, field.name).GetEntryClass()()
  652. else:
  653. sub_message = getattr(message, field.name).add()
  654. else:
  655. if field.is_extension:
  656. sub_message = message.Extensions[field]
  657. else:
  658. sub_message = getattr(message, field.name)
  659. sub_message.SetInParent()
  660. while not tokenizer.TryConsume(end_token):
  661. if tokenizer.AtEnd():
  662. raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token,))
  663. self._MergeField(tokenizer, sub_message)
  664. if is_map_entry:
  665. value_cpptype = field.message_type.fields_by_name['value'].cpp_type
  666. if value_cpptype == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  667. value = getattr(message, field.name)[sub_message.key]
  668. value.MergeFrom(sub_message.value)
  669. else:
  670. getattr(message, field.name)[sub_message.key] = sub_message.value
  671. def _MergeScalarField(self, tokenizer, message, field):
  672. """Merges a single scalar field into a message.
  673. Args:
  674. tokenizer: A tokenizer to parse the field value.
  675. message: A protocol message to record the data.
  676. field: The descriptor of the field to be merged.
  677. Raises:
  678. ParseError: In case of text parsing problems.
  679. RuntimeError: On runtime errors.
  680. """
  681. _ = self.allow_unknown_extension
  682. value = None
  683. if field.type in (descriptor.FieldDescriptor.TYPE_INT32,
  684. descriptor.FieldDescriptor.TYPE_SINT32,
  685. descriptor.FieldDescriptor.TYPE_SFIXED32):
  686. value = _ConsumeInt32(tokenizer)
  687. elif field.type in (descriptor.FieldDescriptor.TYPE_INT64,
  688. descriptor.FieldDescriptor.TYPE_SINT64,
  689. descriptor.FieldDescriptor.TYPE_SFIXED64):
  690. value = _ConsumeInt64(tokenizer)
  691. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32,
  692. descriptor.FieldDescriptor.TYPE_FIXED32):
  693. value = _ConsumeUint32(tokenizer)
  694. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64,
  695. descriptor.FieldDescriptor.TYPE_FIXED64):
  696. value = _ConsumeUint64(tokenizer)
  697. elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT,
  698. descriptor.FieldDescriptor.TYPE_DOUBLE):
  699. value = tokenizer.ConsumeFloat()
  700. elif field.type == descriptor.FieldDescriptor.TYPE_BOOL:
  701. value = tokenizer.ConsumeBool()
  702. elif field.type == descriptor.FieldDescriptor.TYPE_STRING:
  703. value = tokenizer.ConsumeString()
  704. elif field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  705. value = tokenizer.ConsumeByteString()
  706. elif field.type == descriptor.FieldDescriptor.TYPE_ENUM:
  707. value = tokenizer.ConsumeEnum(field)
  708. else:
  709. raise RuntimeError('Unknown field type %d' % field.type)
  710. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  711. if field.is_extension:
  712. message.Extensions[field].append(value)
  713. else:
  714. getattr(message, field.name).append(value)
  715. else:
  716. if field.is_extension:
  717. if not self._allow_multiple_scalars and message.HasExtension(field):
  718. raise tokenizer.ParseErrorPreviousToken(
  719. 'Message type "%s" should not have multiple "%s" extensions.' %
  720. (message.DESCRIPTOR.full_name, field.full_name))
  721. else:
  722. message.Extensions[field] = value
  723. else:
  724. if not self._allow_multiple_scalars and message.HasField(field.name):
  725. raise tokenizer.ParseErrorPreviousToken(
  726. 'Message type "%s" should not have multiple "%s" fields.' %
  727. (message.DESCRIPTOR.full_name, field.name))
  728. else:
  729. setattr(message, field.name, value)
  730. def _SkipFieldContents(tokenizer):
  731. """Skips over contents (value or message) of a field.
  732. Args:
  733. tokenizer: A tokenizer to parse the field name and values.
  734. """
  735. # Try to guess the type of this field.
  736. # If this field is not a message, there should be a ":" between the
  737. # field name and the field value and also the field value should not
  738. # start with "{" or "<" which indicates the beginning of a message body.
  739. # If there is no ":" or there is a "{" or "<" after ":", this field has
  740. # to be a message or the input is ill-formed.
  741. if tokenizer.TryConsume(':') and not tokenizer.LookingAt(
  742. '{') and not tokenizer.LookingAt('<'):
  743. _SkipFieldValue(tokenizer)
  744. else:
  745. _SkipFieldMessage(tokenizer)
  746. def _SkipField(tokenizer):
  747. """Skips over a complete field (name and value/message).
  748. Args:
  749. tokenizer: A tokenizer to parse the field name and values.
  750. """
  751. if tokenizer.TryConsume('['):
  752. # Consume extension name.
  753. tokenizer.ConsumeIdentifier()
  754. while tokenizer.TryConsume('.'):
  755. tokenizer.ConsumeIdentifier()
  756. tokenizer.Consume(']')
  757. else:
  758. tokenizer.ConsumeIdentifier()
  759. _SkipFieldContents(tokenizer)
  760. # For historical reasons, fields may optionally be separated by commas or
  761. # semicolons.
  762. if not tokenizer.TryConsume(','):
  763. tokenizer.TryConsume(';')
  764. def _SkipFieldMessage(tokenizer):
  765. """Skips over a field message.
  766. Args:
  767. tokenizer: A tokenizer to parse the field name and values.
  768. """
  769. if tokenizer.TryConsume('<'):
  770. delimiter = '>'
  771. else:
  772. tokenizer.Consume('{')
  773. delimiter = '}'
  774. while not tokenizer.LookingAt('>') and not tokenizer.LookingAt('}'):
  775. _SkipField(tokenizer)
  776. tokenizer.Consume(delimiter)
  777. def _SkipFieldValue(tokenizer):
  778. """Skips over a field value.
  779. Args:
  780. tokenizer: A tokenizer to parse the field name and values.
  781. Raises:
  782. ParseError: In case an invalid field value is found.
  783. """
  784. # String/bytes tokens can come in multiple adjacent string literals.
  785. # If we can consume one, consume as many as we can.
  786. if tokenizer.TryConsumeByteString():
  787. while tokenizer.TryConsumeByteString():
  788. pass
  789. return
  790. if (not tokenizer.TryConsumeIdentifier() and
  791. not _TryConsumeInt64(tokenizer) and not _TryConsumeUint64(tokenizer) and
  792. not tokenizer.TryConsumeFloat()):
  793. raise ParseError('Invalid field value: ' + tokenizer.token)
  794. class Tokenizer(object):
  795. """Protocol buffer text representation tokenizer.
  796. This class handles the lower level string parsing by splitting it into
  797. meaningful tokens.
  798. It was directly ported from the Java protocol buffer API.
  799. """
  800. _WHITESPACE = re.compile(r'\s+')
  801. _COMMENT = re.compile(r'(\s*#.*$)', re.MULTILINE)
  802. _WHITESPACE_OR_COMMENT = re.compile(r'(\s|(#.*$))+', re.MULTILINE)
  803. _TOKEN = re.compile('|'.join([
  804. r'[a-zA-Z_][0-9a-zA-Z_+-]*', # an identifier
  805. r'([0-9+-]|(\.[0-9]))[0-9a-zA-Z_.+-]*', # a number
  806. ] + [ # quoted str for each quote mark
  807. r'{qt}([^{qt}\n\\]|\\.)*({qt}|\\?$)'.format(qt=mark) for mark in _QUOTES
  808. ]))
  809. _IDENTIFIER = re.compile(r'[^\d\W]\w*')
  810. _IDENTIFIER_OR_NUMBER = re.compile(r'\w+')
  811. def __init__(self, lines, skip_comments=True):
  812. self._position = 0
  813. self._line = -1
  814. self._column = 0
  815. self._token_start = None
  816. self.token = ''
  817. self._lines = iter(lines)
  818. self._current_line = ''
  819. self._previous_line = 0
  820. self._previous_column = 0
  821. self._more_lines = True
  822. self._skip_comments = skip_comments
  823. self._whitespace_pattern = (skip_comments and self._WHITESPACE_OR_COMMENT
  824. or self._WHITESPACE)
  825. self._SkipWhitespace()
  826. self.NextToken()
  827. def LookingAt(self, token):
  828. return self.token == token
  829. def AtEnd(self):
  830. """Checks the end of the text was reached.
  831. Returns:
  832. True iff the end was reached.
  833. """
  834. return not self.token
  835. def _PopLine(self):
  836. while len(self._current_line) <= self._column:
  837. try:
  838. self._current_line = next(self._lines)
  839. except StopIteration:
  840. self._current_line = ''
  841. self._more_lines = False
  842. return
  843. else:
  844. self._line += 1
  845. self._column = 0
  846. def _SkipWhitespace(self):
  847. while True:
  848. self._PopLine()
  849. match = self._whitespace_pattern.match(self._current_line, self._column)
  850. if not match:
  851. break
  852. length = len(match.group(0))
  853. self._column += length
  854. def TryConsume(self, token):
  855. """Tries to consume a given piece of text.
  856. Args:
  857. token: Text to consume.
  858. Returns:
  859. True iff the text was consumed.
  860. """
  861. if self.token == token:
  862. self.NextToken()
  863. return True
  864. return False
  865. def Consume(self, token):
  866. """Consumes a piece of text.
  867. Args:
  868. token: Text to consume.
  869. Raises:
  870. ParseError: If the text couldn't be consumed.
  871. """
  872. if not self.TryConsume(token):
  873. raise self.ParseError('Expected "%s".' % token)
  874. def ConsumeComment(self):
  875. result = self.token
  876. if not self._COMMENT.match(result):
  877. raise self.ParseError('Expected comment.')
  878. self.NextToken()
  879. return result
  880. def ConsumeCommentOrTrailingComment(self):
  881. """Consumes a comment, returns a 2-tuple (trailing bool, comment str)."""
  882. # Tokenizer initializes _previous_line and _previous_column to 0. As the
  883. # tokenizer starts, it looks like there is a previous token on the line.
  884. just_started = self._line == 0 and self._column == 0
  885. before_parsing = self._previous_line
  886. comment = self.ConsumeComment()
  887. # A trailing comment is a comment on the same line than the previous token.
  888. trailing = (self._previous_line == before_parsing
  889. and not just_started)
  890. return trailing, comment
  891. def TryConsumeIdentifier(self):
  892. try:
  893. self.ConsumeIdentifier()
  894. return True
  895. except ParseError:
  896. return False
  897. def ConsumeIdentifier(self):
  898. """Consumes protocol message field identifier.
  899. Returns:
  900. Identifier string.
  901. Raises:
  902. ParseError: If an identifier couldn't be consumed.
  903. """
  904. result = self.token
  905. if not self._IDENTIFIER.match(result):
  906. raise self.ParseError('Expected identifier.')
  907. self.NextToken()
  908. return result
  909. def TryConsumeIdentifierOrNumber(self):
  910. try:
  911. self.ConsumeIdentifierOrNumber()
  912. return True
  913. except ParseError:
  914. return False
  915. def ConsumeIdentifierOrNumber(self):
  916. """Consumes protocol message field identifier.
  917. Returns:
  918. Identifier string.
  919. Raises:
  920. ParseError: If an identifier couldn't be consumed.
  921. """
  922. result = self.token
  923. if not self._IDENTIFIER_OR_NUMBER.match(result):
  924. raise self.ParseError('Expected identifier or number.')
  925. self.NextToken()
  926. return result
  927. def TryConsumeInteger(self):
  928. try:
  929. # Note: is_long only affects value type, not whether an error is raised.
  930. self.ConsumeInteger()
  931. return True
  932. except ParseError:
  933. return False
  934. def ConsumeInteger(self, is_long=False):
  935. """Consumes an integer number.
  936. Args:
  937. is_long: True if the value should be returned as a long integer.
  938. Returns:
  939. The integer parsed.
  940. Raises:
  941. ParseError: If an integer couldn't be consumed.
  942. """
  943. try:
  944. result = _ParseAbstractInteger(self.token, is_long=is_long)
  945. except ValueError as e:
  946. raise self.ParseError(str(e))
  947. self.NextToken()
  948. return result
  949. def TryConsumeFloat(self):
  950. try:
  951. self.ConsumeFloat()
  952. return True
  953. except ParseError:
  954. return False
  955. def ConsumeFloat(self):
  956. """Consumes an floating point number.
  957. Returns:
  958. The number parsed.
  959. Raises:
  960. ParseError: If a floating point number couldn't be consumed.
  961. """
  962. try:
  963. result = ParseFloat(self.token)
  964. except ValueError as e:
  965. raise self.ParseError(str(e))
  966. self.NextToken()
  967. return result
  968. def ConsumeBool(self):
  969. """Consumes a boolean value.
  970. Returns:
  971. The bool parsed.
  972. Raises:
  973. ParseError: If a boolean value couldn't be consumed.
  974. """
  975. try:
  976. result = ParseBool(self.token)
  977. except ValueError as e:
  978. raise self.ParseError(str(e))
  979. self.NextToken()
  980. return result
  981. def TryConsumeByteString(self):
  982. try:
  983. self.ConsumeByteString()
  984. return True
  985. except ParseError:
  986. return False
  987. def ConsumeString(self):
  988. """Consumes a string value.
  989. Returns:
  990. The string parsed.
  991. Raises:
  992. ParseError: If a string value couldn't be consumed.
  993. """
  994. the_bytes = self.ConsumeByteString()
  995. try:
  996. return six.text_type(the_bytes, 'utf-8')
  997. except UnicodeDecodeError as e:
  998. raise self._StringParseError(e)
  999. def ConsumeByteString(self):
  1000. """Consumes a byte array value.
  1001. Returns:
  1002. The array parsed (as a string).
  1003. Raises:
  1004. ParseError: If a byte array value couldn't be consumed.
  1005. """
  1006. the_list = [self._ConsumeSingleByteString()]
  1007. while self.token and self.token[0] in _QUOTES:
  1008. the_list.append(self._ConsumeSingleByteString())
  1009. return b''.join(the_list)
  1010. def _ConsumeSingleByteString(self):
  1011. """Consume one token of a string literal.
  1012. String literals (whether bytes or text) can come in multiple adjacent
  1013. tokens which are automatically concatenated, like in C or Python. This
  1014. method only consumes one token.
  1015. Returns:
  1016. The token parsed.
  1017. Raises:
  1018. ParseError: When the wrong format data is found.
  1019. """
  1020. text = self.token
  1021. if len(text) < 1 or text[0] not in _QUOTES:
  1022. raise self.ParseError('Expected string but found: %r' % (text,))
  1023. if len(text) < 2 or text[-1] != text[0]:
  1024. raise self.ParseError('String missing ending quote: %r' % (text,))
  1025. try:
  1026. result = text_encoding.CUnescape(text[1:-1])
  1027. except ValueError as e:
  1028. raise self.ParseError(str(e))
  1029. self.NextToken()
  1030. return result
  1031. def ConsumeEnum(self, field):
  1032. try:
  1033. result = ParseEnum(field, self.token)
  1034. except ValueError as e:
  1035. raise self.ParseError(str(e))
  1036. self.NextToken()
  1037. return result
  1038. def ParseErrorPreviousToken(self, message):
  1039. """Creates and *returns* a ParseError for the previously read token.
  1040. Args:
  1041. message: A message to set for the exception.
  1042. Returns:
  1043. A ParseError instance.
  1044. """
  1045. return ParseError(message, self._previous_line + 1,
  1046. self._previous_column + 1)
  1047. def ParseError(self, message):
  1048. """Creates and *returns* a ParseError for the current token."""
  1049. return ParseError(message, self._line + 1, self._column + 1)
  1050. def _StringParseError(self, e):
  1051. return self.ParseError('Couldn\'t parse string: ' + str(e))
  1052. def NextToken(self):
  1053. """Reads the next meaningful token."""
  1054. self._previous_line = self._line
  1055. self._previous_column = self._column
  1056. self._column += len(self.token)
  1057. self._SkipWhitespace()
  1058. if not self._more_lines:
  1059. self.token = ''
  1060. return
  1061. match = self._TOKEN.match(self._current_line, self._column)
  1062. if not match and not self._skip_comments:
  1063. match = self._COMMENT.match(self._current_line, self._column)
  1064. if match:
  1065. token = match.group(0)
  1066. self.token = token
  1067. else:
  1068. self.token = self._current_line[self._column]
  1069. # Aliased so it can still be accessed by current visibility violators.
  1070. # TODO(dbarnett): Migrate violators to textformat_tokenizer.
  1071. _Tokenizer = Tokenizer # pylint: disable=invalid-name
  1072. def _ConsumeInt32(tokenizer):
  1073. """Consumes a signed 32bit integer number from tokenizer.
  1074. Args:
  1075. tokenizer: A tokenizer used to parse the number.
  1076. Returns:
  1077. The integer parsed.
  1078. Raises:
  1079. ParseError: If a signed 32bit integer couldn't be consumed.
  1080. """
  1081. return _ConsumeInteger(tokenizer, is_signed=True, is_long=False)
  1082. def _ConsumeUint32(tokenizer):
  1083. """Consumes an unsigned 32bit integer number from tokenizer.
  1084. Args:
  1085. tokenizer: A tokenizer used to parse the number.
  1086. Returns:
  1087. The integer parsed.
  1088. Raises:
  1089. ParseError: If an unsigned 32bit integer couldn't be consumed.
  1090. """
  1091. return _ConsumeInteger(tokenizer, is_signed=False, is_long=False)
  1092. def _TryConsumeInt64(tokenizer):
  1093. try:
  1094. _ConsumeInt64(tokenizer)
  1095. return True
  1096. except ParseError:
  1097. return False
  1098. def _ConsumeInt64(tokenizer):
  1099. """Consumes a signed 32bit integer number from tokenizer.
  1100. Args:
  1101. tokenizer: A tokenizer used to parse the number.
  1102. Returns:
  1103. The integer parsed.
  1104. Raises:
  1105. ParseError: If a signed 32bit integer couldn't be consumed.
  1106. """
  1107. return _ConsumeInteger(tokenizer, is_signed=True, is_long=True)
  1108. def _TryConsumeUint64(tokenizer):
  1109. try:
  1110. _ConsumeUint64(tokenizer)
  1111. return True
  1112. except ParseError:
  1113. return False
  1114. def _ConsumeUint64(tokenizer):
  1115. """Consumes an unsigned 64bit integer number from tokenizer.
  1116. Args:
  1117. tokenizer: A tokenizer used to parse the number.
  1118. Returns:
  1119. The integer parsed.
  1120. Raises:
  1121. ParseError: If an unsigned 64bit integer couldn't be consumed.
  1122. """
  1123. return _ConsumeInteger(tokenizer, is_signed=False, is_long=True)
  1124. def _TryConsumeInteger(tokenizer, is_signed=False, is_long=False):
  1125. try:
  1126. _ConsumeInteger(tokenizer, is_signed=is_signed, is_long=is_long)
  1127. return True
  1128. except ParseError:
  1129. return False
  1130. def _ConsumeInteger(tokenizer, is_signed=False, is_long=False):
  1131. """Consumes an integer number from tokenizer.
  1132. Args:
  1133. tokenizer: A tokenizer used to parse the number.
  1134. is_signed: True if a signed integer must be parsed.
  1135. is_long: True if a long integer must be parsed.
  1136. Returns:
  1137. The integer parsed.
  1138. Raises:
  1139. ParseError: If an integer with given characteristics couldn't be consumed.
  1140. """
  1141. try:
  1142. result = ParseInteger(tokenizer.token, is_signed=is_signed, is_long=is_long)
  1143. except ValueError as e:
  1144. raise tokenizer.ParseError(str(e))
  1145. tokenizer.NextToken()
  1146. return result
  1147. def ParseInteger(text, is_signed=False, is_long=False):
  1148. """Parses an integer.
  1149. Args:
  1150. text: The text to parse.
  1151. is_signed: True if a signed integer must be parsed.
  1152. is_long: True if a long integer must be parsed.
  1153. Returns:
  1154. The integer value.
  1155. Raises:
  1156. ValueError: Thrown Iff the text is not a valid integer.
  1157. """
  1158. # Do the actual parsing. Exception handling is propagated to caller.
  1159. result = _ParseAbstractInteger(text, is_long=is_long)
  1160. # Check if the integer is sane. Exceptions handled by callers.
  1161. checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
  1162. checker.CheckValue(result)
  1163. return result
  1164. def _ParseAbstractInteger(text, is_long=False):
  1165. """Parses an integer without checking size/signedness.
  1166. Args:
  1167. text: The text to parse.
  1168. is_long: True if the value should be returned as a long integer.
  1169. Returns:
  1170. The integer value.
  1171. Raises:
  1172. ValueError: Thrown Iff the text is not a valid integer.
  1173. """
  1174. # Do the actual parsing. Exception handling is propagated to caller.
  1175. try:
  1176. # We force 32-bit values to int and 64-bit values to long to make
  1177. # alternate implementations where the distinction is more significant
  1178. # (e.g. the C++ implementation) simpler.
  1179. if is_long:
  1180. return long(text, 0)
  1181. else:
  1182. return int(text, 0)
  1183. except ValueError:
  1184. raise ValueError('Couldn\'t parse integer: %s' % text)
  1185. def ParseFloat(text):
  1186. """Parse a floating point number.
  1187. Args:
  1188. text: Text to parse.
  1189. Returns:
  1190. The number parsed.
  1191. Raises:
  1192. ValueError: If a floating point number couldn't be parsed.
  1193. """
  1194. try:
  1195. # Assume Python compatible syntax.
  1196. return float(text)
  1197. except ValueError:
  1198. # Check alternative spellings.
  1199. if _FLOAT_INFINITY.match(text):
  1200. if text[0] == '-':
  1201. return float('-inf')
  1202. else:
  1203. return float('inf')
  1204. elif _FLOAT_NAN.match(text):
  1205. return float('nan')
  1206. else:
  1207. # assume '1.0f' format
  1208. try:
  1209. return float(text.rstrip('f'))
  1210. except ValueError:
  1211. raise ValueError('Couldn\'t parse float: %s' % text)
  1212. def ParseBool(text):
  1213. """Parse a boolean value.
  1214. Args:
  1215. text: Text to parse.
  1216. Returns:
  1217. Boolean values parsed
  1218. Raises:
  1219. ValueError: If text is not a valid boolean.
  1220. """
  1221. if text in ('true', 't', '1', 'True'):
  1222. return True
  1223. elif text in ('false', 'f', '0', 'False'):
  1224. return False
  1225. else:
  1226. raise ValueError('Expected "true" or "false".')
  1227. def ParseEnum(field, value):
  1228. """Parse an enum value.
  1229. The value can be specified by a number (the enum value), or by
  1230. a string literal (the enum name).
  1231. Args:
  1232. field: Enum field descriptor.
  1233. value: String value.
  1234. Returns:
  1235. Enum value number.
  1236. Raises:
  1237. ValueError: If the enum value could not be parsed.
  1238. """
  1239. enum_descriptor = field.enum_type
  1240. try:
  1241. number = int(value, 0)
  1242. except ValueError:
  1243. # Identifier.
  1244. enum_value = enum_descriptor.values_by_name.get(value, None)
  1245. if enum_value is None:
  1246. raise ValueError('Enum type "%s" has no value named %s.' %
  1247. (enum_descriptor.full_name, value))
  1248. else:
  1249. # Numeric value.
  1250. enum_value = enum_descriptor.values_by_number.get(number, None)
  1251. if enum_value is None:
  1252. raise ValueError('Enum type "%s" has no value with number %d.' %
  1253. (enum_descriptor.full_name, number))
  1254. return enum_value.number