text_format.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  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
  44. from google.protobuf.internal import type_checkers
  45. from google.protobuf import descriptor
  46. from google.protobuf import text_encoding
  47. __all__ = ['MessageToString', 'PrintMessage', 'PrintField',
  48. 'PrintFieldValue', 'Merge']
  49. _INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(),
  50. type_checkers.Int32ValueChecker(),
  51. type_checkers.Uint64ValueChecker(),
  52. type_checkers.Int64ValueChecker())
  53. _FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?', re.IGNORECASE)
  54. _FLOAT_NAN = re.compile('nanf?', re.IGNORECASE)
  55. _FLOAT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_FLOAT,
  56. descriptor.FieldDescriptor.CPPTYPE_DOUBLE])
  57. _QUOTES = frozenset(("'", '"'))
  58. class Error(Exception):
  59. """Top-level module error for text_format."""
  60. class ParseError(Error):
  61. """Thrown in case of text parsing error."""
  62. class TextWriter(object):
  63. def __init__(self, as_utf8):
  64. if six.PY2:
  65. self._writer = io.BytesIO()
  66. else:
  67. self._writer = io.StringIO()
  68. def write(self, val):
  69. if six.PY2:
  70. if isinstance(val, six.text_type):
  71. val = val.encode('utf-8')
  72. return self._writer.write(val)
  73. def close(self):
  74. return self._writer.close()
  75. def getvalue(self):
  76. return self._writer.getvalue()
  77. def MessageToString(message, as_utf8=False, as_one_line=False,
  78. pointy_brackets=False, use_index_order=False,
  79. float_format=None, use_field_number=False):
  80. """Convert protobuf message to text format.
  81. Floating point values can be formatted compactly with 15 digits of
  82. precision (which is the most that IEEE 754 "double" can guarantee)
  83. using float_format='.15g'. To ensure that converting to text and back to a
  84. proto will result in an identical value, float_format='.17g' should be used.
  85. Args:
  86. message: The protocol buffers message.
  87. as_utf8: Produce text output in UTF8 format.
  88. as_one_line: Don't introduce newlines between fields.
  89. pointy_brackets: If True, use angle brackets instead of curly braces for
  90. nesting.
  91. use_index_order: If True, print fields of a proto message using the order
  92. defined in source code instead of the field number. By default, use the
  93. field number order.
  94. float_format: If set, use this to specify floating point number formatting
  95. (per the "Format Specification Mini-Language"); otherwise, str() is used.
  96. use_field_number: If True, print field numbers instead of names.
  97. Returns:
  98. A string of the text formatted protocol buffer message.
  99. """
  100. out = TextWriter(as_utf8)
  101. printer = _Printer(out, 0, as_utf8, as_one_line,
  102. pointy_brackets, use_index_order, float_format,
  103. use_field_number)
  104. printer.PrintMessage(message)
  105. result = out.getvalue()
  106. out.close()
  107. if as_one_line:
  108. return result.rstrip()
  109. return result
  110. def _IsMapEntry(field):
  111. return (field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  112. field.message_type.has_options and
  113. field.message_type.GetOptions().map_entry)
  114. def PrintMessage(message, out, indent=0, as_utf8=False, as_one_line=False,
  115. pointy_brackets=False, use_index_order=False,
  116. float_format=None, use_field_number=False):
  117. printer = _Printer(out, indent, as_utf8, as_one_line,
  118. pointy_brackets, use_index_order, float_format,
  119. use_field_number)
  120. printer.PrintMessage(message)
  121. def PrintField(field, value, out, indent=0, as_utf8=False, as_one_line=False,
  122. pointy_brackets=False, use_index_order=False, float_format=None):
  123. """Print a single field name/value pair."""
  124. printer = _Printer(out, indent, as_utf8, as_one_line,
  125. pointy_brackets, use_index_order, float_format)
  126. printer.PrintField(field, value)
  127. def PrintFieldValue(field, value, out, indent=0, as_utf8=False,
  128. as_one_line=False, pointy_brackets=False,
  129. use_index_order=False,
  130. float_format=None):
  131. """Print a single field value (not including name)."""
  132. printer = _Printer(out, indent, as_utf8, as_one_line,
  133. pointy_brackets, use_index_order, float_format)
  134. printer.PrintFieldValue(field, value)
  135. class _Printer(object):
  136. """Text format printer for protocol message."""
  137. def __init__(self, out, indent=0, as_utf8=False, as_one_line=False,
  138. pointy_brackets=False, use_index_order=False, float_format=None,
  139. use_field_number=False):
  140. """Initialize the Printer.
  141. Floating point values can be formatted compactly with 15 digits of
  142. precision (which is the most that IEEE 754 "double" can guarantee)
  143. using float_format='.15g'. To ensure that converting to text and back to a
  144. proto will result in an identical value, float_format='.17g' should be used.
  145. Args:
  146. out: To record the text format result.
  147. indent: The indent level for pretty print.
  148. as_utf8: Produce text output in UTF8 format.
  149. as_one_line: Don't introduce newlines between fields.
  150. pointy_brackets: If True, use angle brackets instead of curly braces for
  151. nesting.
  152. use_index_order: If True, print fields of a proto message using the order
  153. defined in source code instead of the field number. By default, use the
  154. field number order.
  155. float_format: If set, use this to specify floating point number formatting
  156. (per the "Format Specification Mini-Language"); otherwise, str() is
  157. used.
  158. use_field_number: If True, print field numbers instead of names.
  159. """
  160. self.out = out
  161. self.indent = indent
  162. self.as_utf8 = as_utf8
  163. self.as_one_line = as_one_line
  164. self.pointy_brackets = pointy_brackets
  165. self.use_index_order = use_index_order
  166. self.float_format = float_format
  167. self.use_field_number = use_field_number
  168. def PrintMessage(self, message):
  169. """Convert protobuf message to text format.
  170. Args:
  171. message: The protocol buffers message.
  172. """
  173. fields = message.ListFields()
  174. if self.use_index_order:
  175. fields.sort(key=lambda x: x[0].index)
  176. for field, value in fields:
  177. if _IsMapEntry(field):
  178. for key in sorted(value):
  179. # This is slow for maps with submessage entires because it copies the
  180. # entire tree. Unfortunately this would take significant refactoring
  181. # of this file to work around.
  182. #
  183. # TODO(haberman): refactor and optimize if this becomes an issue.
  184. entry_submsg = field.message_type._concrete_class(
  185. key=key, value=value[key])
  186. self.PrintField(field, entry_submsg)
  187. elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  188. for element in value:
  189. self.PrintField(field, element)
  190. else:
  191. self.PrintField(field, value)
  192. def PrintField(self, field, value):
  193. """Print a single field name/value pair."""
  194. out = self.out
  195. out.write(' ' * self.indent)
  196. if self.use_field_number:
  197. out.write(str(field.number))
  198. else:
  199. if field.is_extension:
  200. out.write('[')
  201. if (field.containing_type.GetOptions().message_set_wire_format and
  202. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  203. field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL):
  204. out.write(field.message_type.full_name)
  205. else:
  206. out.write(field.full_name)
  207. out.write(']')
  208. elif field.type == descriptor.FieldDescriptor.TYPE_GROUP:
  209. # For groups, use the capitalized name.
  210. out.write(field.message_type.name)
  211. else:
  212. out.write(field.name)
  213. if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  214. # The colon is optional in this case, but our cross-language golden files
  215. # don't include it.
  216. out.write(': ')
  217. self.PrintFieldValue(field, value)
  218. if self.as_one_line:
  219. out.write(' ')
  220. else:
  221. out.write('\n')
  222. def PrintFieldValue(self, field, value):
  223. """Print a single field value (not including name).
  224. For repeated fields, the value should be a single element.
  225. Args:
  226. field: The descriptor of the field to be printed.
  227. value: The value of the field.
  228. """
  229. out = self.out
  230. if self.pointy_brackets:
  231. openb = '<'
  232. closeb = '>'
  233. else:
  234. openb = '{'
  235. closeb = '}'
  236. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  237. if self.as_one_line:
  238. out.write(' %s ' % openb)
  239. self.PrintMessage(value)
  240. out.write(closeb)
  241. else:
  242. out.write(' %s\n' % openb)
  243. self.indent += 2
  244. self.PrintMessage(value)
  245. self.indent -= 2
  246. out.write(' ' * self.indent + closeb)
  247. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
  248. enum_value = field.enum_type.values_by_number.get(value, None)
  249. if enum_value is not None:
  250. out.write(enum_value.name)
  251. else:
  252. out.write(str(value))
  253. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
  254. out.write('\"')
  255. if isinstance(value, six.text_type):
  256. out_value = value.encode('utf-8')
  257. else:
  258. out_value = value
  259. if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  260. # We need to escape non-UTF8 chars in TYPE_BYTES field.
  261. out_as_utf8 = False
  262. else:
  263. out_as_utf8 = self.as_utf8
  264. out.write(text_encoding.CEscape(out_value, out_as_utf8))
  265. out.write('\"')
  266. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
  267. if value:
  268. out.write('true')
  269. else:
  270. out.write('false')
  271. elif field.cpp_type in _FLOAT_TYPES and self.float_format is not None:
  272. out.write('{1:{0}}'.format(self.float_format, value))
  273. else:
  274. out.write(str(value))
  275. def Parse(text, message,
  276. allow_unknown_extension=False, allow_field_number=False):
  277. """Parses an text representation of a protocol message into a message.
  278. Args:
  279. text: Message text representation.
  280. message: A protocol buffer message to merge into.
  281. allow_unknown_extension: if True, skip over missing extensions and keep
  282. parsing
  283. allow_field_number: if True, both field number and field name are allowed.
  284. Returns:
  285. The same message passed as argument.
  286. Raises:
  287. ParseError: On text parsing problems.
  288. """
  289. if not isinstance(text, str):
  290. text = text.decode('utf-8')
  291. return ParseLines(text.split('\n'), message, allow_unknown_extension,
  292. allow_field_number)
  293. def Merge(text, message, allow_unknown_extension=False,
  294. allow_field_number=False):
  295. """Parses an text representation of a protocol message into a message.
  296. Like Parse(), but allows repeated values for a non-repeated field, and uses
  297. the last one.
  298. Args:
  299. text: Message text representation.
  300. message: A protocol buffer message to merge into.
  301. allow_unknown_extension: if True, skip over missing extensions and keep
  302. parsing
  303. allow_field_number: if True, both field number and field name are allowed.
  304. Returns:
  305. The same message passed as argument.
  306. Raises:
  307. ParseError: On text parsing problems.
  308. """
  309. return MergeLines(text.split('\n'), message, allow_unknown_extension,
  310. allow_field_number)
  311. def ParseLines(lines, message, allow_unknown_extension=False,
  312. allow_field_number=False):
  313. """Parses an text representation of a protocol message into a message.
  314. Args:
  315. lines: An iterable of lines of a message's text representation.
  316. message: A protocol buffer message to merge into.
  317. allow_unknown_extension: if True, skip over missing extensions and keep
  318. parsing
  319. allow_field_number: if True, both field number and field name are allowed.
  320. Returns:
  321. The same message passed as argument.
  322. Raises:
  323. ParseError: On text parsing problems.
  324. """
  325. parser = _Parser(allow_unknown_extension, allow_field_number)
  326. return parser.ParseLines(lines, message)
  327. def MergeLines(lines, message, allow_unknown_extension=False,
  328. allow_field_number=False):
  329. """Parses an text representation of a protocol message into a message.
  330. Args:
  331. lines: An iterable of lines of a message's text representation.
  332. message: A protocol buffer message to merge into.
  333. allow_unknown_extension: if True, skip over missing extensions and keep
  334. parsing
  335. allow_field_number: if True, both field number and field name are allowed.
  336. Returns:
  337. The same message passed as argument.
  338. Raises:
  339. ParseError: On text parsing problems.
  340. """
  341. parser = _Parser(allow_unknown_extension, allow_field_number)
  342. return parser.MergeLines(lines, message)
  343. class _Parser(object):
  344. """Text format parser for protocol message."""
  345. def __init__(self, allow_unknown_extension=False, allow_field_number=False):
  346. self.allow_unknown_extension = allow_unknown_extension
  347. self.allow_field_number = allow_field_number
  348. def ParseFromString(self, text, message):
  349. """Parses an text representation of a protocol message into a message."""
  350. if not isinstance(text, str):
  351. text = text.decode('utf-8')
  352. return self.ParseLines(text.split('\n'), message)
  353. def ParseLines(self, lines, message):
  354. """Parses an text representation of a protocol message into a message."""
  355. self._allow_multiple_scalars = False
  356. self._ParseOrMerge(lines, message)
  357. return message
  358. def MergeFromString(self, text, message):
  359. """Merges an text representation of a protocol message into a message."""
  360. return self._MergeLines(text.split('\n'), message)
  361. def MergeLines(self, lines, message):
  362. """Merges an text representation of a protocol message into a message."""
  363. self._allow_multiple_scalars = True
  364. self._ParseOrMerge(lines, message)
  365. return message
  366. def _ParseOrMerge(self, lines, message):
  367. """Converts an text representation of a protocol message into a message.
  368. Args:
  369. lines: Lines of a message's text representation.
  370. message: A protocol buffer message to merge into.
  371. Raises:
  372. ParseError: On text parsing problems.
  373. """
  374. tokenizer = _Tokenizer(lines)
  375. while not tokenizer.AtEnd():
  376. self._MergeField(tokenizer, message)
  377. def _MergeField(self, tokenizer, message):
  378. """Merges a single protocol message field into a message.
  379. Args:
  380. tokenizer: A tokenizer to parse the field name and values.
  381. message: A protocol message to record the data.
  382. Raises:
  383. ParseError: In case of text parsing problems.
  384. """
  385. message_descriptor = message.DESCRIPTOR
  386. if (hasattr(message_descriptor, 'syntax') and
  387. message_descriptor.syntax == 'proto3'):
  388. # Proto3 doesn't represent presence so we can't test if multiple
  389. # scalars have occurred. We have to allow them.
  390. self._allow_multiple_scalars = True
  391. if tokenizer.TryConsume('['):
  392. name = [tokenizer.ConsumeIdentifier()]
  393. while tokenizer.TryConsume('.'):
  394. name.append(tokenizer.ConsumeIdentifier())
  395. name = '.'.join(name)
  396. if not message_descriptor.is_extendable:
  397. raise tokenizer.ParseErrorPreviousToken(
  398. 'Message type "%s" does not have extensions.' %
  399. message_descriptor.full_name)
  400. # pylint: disable=protected-access
  401. field = message.Extensions._FindExtensionByName(name)
  402. # pylint: enable=protected-access
  403. if not field:
  404. if self.allow_unknown_extension:
  405. field = None
  406. else:
  407. raise tokenizer.ParseErrorPreviousToken(
  408. 'Extension "%s" not registered.' % name)
  409. elif message_descriptor != field.containing_type:
  410. raise tokenizer.ParseErrorPreviousToken(
  411. 'Extension "%s" does not extend message type "%s".' % (
  412. name, message_descriptor.full_name))
  413. tokenizer.Consume(']')
  414. else:
  415. name = tokenizer.ConsumeIdentifier()
  416. if self.allow_field_number and name.isdigit():
  417. number = ParseInteger(name, True, True)
  418. field = message_descriptor.fields_by_number.get(number, None)
  419. if not field and message_descriptor.is_extendable:
  420. field = message.Extensions._FindExtensionByNumber(number)
  421. else:
  422. field = message_descriptor.fields_by_name.get(name, None)
  423. # Group names are expected to be capitalized as they appear in the
  424. # .proto file, which actually matches their type names, not their field
  425. # names.
  426. if not field:
  427. field = message_descriptor.fields_by_name.get(name.lower(), None)
  428. if field and field.type != descriptor.FieldDescriptor.TYPE_GROUP:
  429. field = None
  430. if (field and field.type == descriptor.FieldDescriptor.TYPE_GROUP and
  431. field.message_type.name != name):
  432. field = None
  433. if not field:
  434. raise tokenizer.ParseErrorPreviousToken(
  435. 'Message type "%s" has no field named "%s".' % (
  436. message_descriptor.full_name, name))
  437. if field:
  438. if not self._allow_multiple_scalars and field.containing_oneof:
  439. # Check if there's a different field set in this oneof.
  440. # Note that we ignore the case if the same field was set before, and we
  441. # apply _allow_multiple_scalars to non-scalar fields as well.
  442. which_oneof = message.WhichOneof(field.containing_oneof.name)
  443. if which_oneof is not None and which_oneof != field.name:
  444. raise tokenizer.ParseErrorPreviousToken(
  445. 'Field "%s" is specified along with field "%s", another member '
  446. 'of oneof "%s" for message type "%s".' % (
  447. field.name, which_oneof, field.containing_oneof.name,
  448. message_descriptor.full_name))
  449. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  450. tokenizer.TryConsume(':')
  451. merger = self._MergeMessageField
  452. else:
  453. tokenizer.Consume(':')
  454. merger = self._MergeScalarField
  455. if (field.label == descriptor.FieldDescriptor.LABEL_REPEATED
  456. and tokenizer.TryConsume('[')):
  457. # Short repeated format, e.g. "foo: [1, 2, 3]"
  458. while True:
  459. merger(tokenizer, message, field)
  460. if tokenizer.TryConsume(']'): break
  461. tokenizer.Consume(',')
  462. else:
  463. merger(tokenizer, message, field)
  464. else: # Proto field is unknown.
  465. assert self.allow_unknown_extension
  466. _SkipFieldContents(tokenizer)
  467. # For historical reasons, fields may optionally be separated by commas or
  468. # semicolons.
  469. if not tokenizer.TryConsume(','):
  470. tokenizer.TryConsume(';')
  471. def _MergeMessageField(self, tokenizer, message, field):
  472. """Merges a single scalar field into a message.
  473. Args:
  474. tokenizer: A tokenizer to parse the field value.
  475. message: The message of which field is a member.
  476. field: The descriptor of the field to be merged.
  477. Raises:
  478. ParseError: In case of text parsing problems.
  479. """
  480. is_map_entry = _IsMapEntry(field)
  481. if tokenizer.TryConsume('<'):
  482. end_token = '>'
  483. else:
  484. tokenizer.Consume('{')
  485. end_token = '}'
  486. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  487. if field.is_extension:
  488. sub_message = message.Extensions[field].add()
  489. elif is_map_entry:
  490. # pylint: disable=protected-access
  491. sub_message = field.message_type._concrete_class()
  492. else:
  493. sub_message = getattr(message, field.name).add()
  494. else:
  495. if field.is_extension:
  496. sub_message = message.Extensions[field]
  497. else:
  498. sub_message = getattr(message, field.name)
  499. sub_message.SetInParent()
  500. while not tokenizer.TryConsume(end_token):
  501. if tokenizer.AtEnd():
  502. raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token,))
  503. self._MergeField(tokenizer, sub_message)
  504. if is_map_entry:
  505. value_cpptype = field.message_type.fields_by_name['value'].cpp_type
  506. if value_cpptype == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  507. value = getattr(message, field.name)[sub_message.key]
  508. value.MergeFrom(sub_message.value)
  509. else:
  510. getattr(message, field.name)[sub_message.key] = sub_message.value
  511. def _MergeScalarField(self, tokenizer, message, field):
  512. """Merges a single scalar field into a message.
  513. Args:
  514. tokenizer: A tokenizer to parse the field value.
  515. message: A protocol message to record the data.
  516. field: The descriptor of the field to be merged.
  517. Raises:
  518. ParseError: In case of text parsing problems.
  519. RuntimeError: On runtime errors.
  520. """
  521. _ = self.allow_unknown_extension
  522. value = None
  523. if field.type in (descriptor.FieldDescriptor.TYPE_INT32,
  524. descriptor.FieldDescriptor.TYPE_SINT32,
  525. descriptor.FieldDescriptor.TYPE_SFIXED32):
  526. value = tokenizer.ConsumeInt32()
  527. elif field.type in (descriptor.FieldDescriptor.TYPE_INT64,
  528. descriptor.FieldDescriptor.TYPE_SINT64,
  529. descriptor.FieldDescriptor.TYPE_SFIXED64):
  530. value = tokenizer.ConsumeInt64()
  531. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32,
  532. descriptor.FieldDescriptor.TYPE_FIXED32):
  533. value = tokenizer.ConsumeUint32()
  534. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64,
  535. descriptor.FieldDescriptor.TYPE_FIXED64):
  536. value = tokenizer.ConsumeUint64()
  537. elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT,
  538. descriptor.FieldDescriptor.TYPE_DOUBLE):
  539. value = tokenizer.ConsumeFloat()
  540. elif field.type == descriptor.FieldDescriptor.TYPE_BOOL:
  541. value = tokenizer.ConsumeBool()
  542. elif field.type == descriptor.FieldDescriptor.TYPE_STRING:
  543. value = tokenizer.ConsumeString()
  544. elif field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  545. value = tokenizer.ConsumeByteString()
  546. elif field.type == descriptor.FieldDescriptor.TYPE_ENUM:
  547. value = tokenizer.ConsumeEnum(field)
  548. else:
  549. raise RuntimeError('Unknown field type %d' % field.type)
  550. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  551. if field.is_extension:
  552. message.Extensions[field].append(value)
  553. else:
  554. getattr(message, field.name).append(value)
  555. else:
  556. if field.is_extension:
  557. if not self._allow_multiple_scalars and message.HasExtension(field):
  558. raise tokenizer.ParseErrorPreviousToken(
  559. 'Message type "%s" should not have multiple "%s" extensions.' %
  560. (message.DESCRIPTOR.full_name, field.full_name))
  561. else:
  562. message.Extensions[field] = value
  563. else:
  564. if not self._allow_multiple_scalars and message.HasField(field.name):
  565. raise tokenizer.ParseErrorPreviousToken(
  566. 'Message type "%s" should not have multiple "%s" fields.' %
  567. (message.DESCRIPTOR.full_name, field.name))
  568. else:
  569. setattr(message, field.name, value)
  570. def _SkipFieldContents(tokenizer):
  571. """Skips over contents (value or message) of a field.
  572. Args:
  573. tokenizer: A tokenizer to parse the field name and values.
  574. """
  575. # Try to guess the type of this field.
  576. # If this field is not a message, there should be a ":" between the
  577. # field name and the field value and also the field value should not
  578. # start with "{" or "<" which indicates the beginning of a message body.
  579. # If there is no ":" or there is a "{" or "<" after ":", this field has
  580. # to be a message or the input is ill-formed.
  581. if tokenizer.TryConsume(':') and not tokenizer.LookingAt(
  582. '{') and not tokenizer.LookingAt('<'):
  583. _SkipFieldValue(tokenizer)
  584. else:
  585. _SkipFieldMessage(tokenizer)
  586. def _SkipField(tokenizer):
  587. """Skips over a complete field (name and value/message).
  588. Args:
  589. tokenizer: A tokenizer to parse the field name and values.
  590. """
  591. if tokenizer.TryConsume('['):
  592. # Consume extension name.
  593. tokenizer.ConsumeIdentifier()
  594. while tokenizer.TryConsume('.'):
  595. tokenizer.ConsumeIdentifier()
  596. tokenizer.Consume(']')
  597. else:
  598. tokenizer.ConsumeIdentifier()
  599. _SkipFieldContents(tokenizer)
  600. # For historical reasons, fields may optionally be separated by commas or
  601. # semicolons.
  602. if not tokenizer.TryConsume(','):
  603. tokenizer.TryConsume(';')
  604. def _SkipFieldMessage(tokenizer):
  605. """Skips over a field message.
  606. Args:
  607. tokenizer: A tokenizer to parse the field name and values.
  608. """
  609. if tokenizer.TryConsume('<'):
  610. delimiter = '>'
  611. else:
  612. tokenizer.Consume('{')
  613. delimiter = '}'
  614. while not tokenizer.LookingAt('>') and not tokenizer.LookingAt('}'):
  615. _SkipField(tokenizer)
  616. tokenizer.Consume(delimiter)
  617. def _SkipFieldValue(tokenizer):
  618. """Skips over a field value.
  619. Args:
  620. tokenizer: A tokenizer to parse the field name and values.
  621. Raises:
  622. ParseError: In case an invalid field value is found.
  623. """
  624. # String/bytes tokens can come in multiple adjacent string literals.
  625. # If we can consume one, consume as many as we can.
  626. if tokenizer.TryConsumeByteString():
  627. while tokenizer.TryConsumeByteString():
  628. pass
  629. return
  630. if (not tokenizer.TryConsumeIdentifier() and
  631. not tokenizer.TryConsumeInt64() and
  632. not tokenizer.TryConsumeUint64() and
  633. not tokenizer.TryConsumeFloat()):
  634. raise ParseError('Invalid field value: ' + tokenizer.token)
  635. class _Tokenizer(object):
  636. """Protocol buffer text representation tokenizer.
  637. This class handles the lower level string parsing by splitting it into
  638. meaningful tokens.
  639. It was directly ported from the Java protocol buffer API.
  640. """
  641. _WHITESPACE = re.compile('(\\s|(#.*$))+', re.MULTILINE)
  642. _TOKEN = re.compile('|'.join([
  643. r'[a-zA-Z_][0-9a-zA-Z_+-]*', # an identifier
  644. r'([0-9+-]|(\.[0-9]))[0-9a-zA-Z_.+-]*', # a number
  645. ] + [ # quoted str for each quote mark
  646. r'{qt}([^{qt}\n\\]|\\.)*({qt}|\\?$)'.format(qt=mark) for mark in _QUOTES
  647. ]))
  648. _IDENTIFIER = re.compile(r'\w+')
  649. def __init__(self, lines):
  650. self._position = 0
  651. self._line = -1
  652. self._column = 0
  653. self._token_start = None
  654. self.token = ''
  655. self._lines = iter(lines)
  656. self._current_line = ''
  657. self._previous_line = 0
  658. self._previous_column = 0
  659. self._more_lines = True
  660. self._SkipWhitespace()
  661. self.NextToken()
  662. def LookingAt(self, token):
  663. return self.token == token
  664. def AtEnd(self):
  665. """Checks the end of the text was reached.
  666. Returns:
  667. True iff the end was reached.
  668. """
  669. return not self.token
  670. def _PopLine(self):
  671. while len(self._current_line) <= self._column:
  672. try:
  673. self._current_line = next(self._lines)
  674. except StopIteration:
  675. self._current_line = ''
  676. self._more_lines = False
  677. return
  678. else:
  679. self._line += 1
  680. self._column = 0
  681. def _SkipWhitespace(self):
  682. while True:
  683. self._PopLine()
  684. match = self._WHITESPACE.match(self._current_line, self._column)
  685. if not match:
  686. break
  687. length = len(match.group(0))
  688. self._column += length
  689. def TryConsume(self, token):
  690. """Tries to consume a given piece of text.
  691. Args:
  692. token: Text to consume.
  693. Returns:
  694. True iff the text was consumed.
  695. """
  696. if self.token == token:
  697. self.NextToken()
  698. return True
  699. return False
  700. def Consume(self, token):
  701. """Consumes a piece of text.
  702. Args:
  703. token: Text to consume.
  704. Raises:
  705. ParseError: If the text couldn't be consumed.
  706. """
  707. if not self.TryConsume(token):
  708. raise self._ParseError('Expected "%s".' % token)
  709. def TryConsumeIdentifier(self):
  710. try:
  711. self.ConsumeIdentifier()
  712. return True
  713. except ParseError:
  714. return False
  715. def ConsumeIdentifier(self):
  716. """Consumes protocol message field identifier.
  717. Returns:
  718. Identifier string.
  719. Raises:
  720. ParseError: If an identifier couldn't be consumed.
  721. """
  722. result = self.token
  723. if not self._IDENTIFIER.match(result):
  724. raise self._ParseError('Expected identifier.')
  725. self.NextToken()
  726. return result
  727. def ConsumeInt32(self):
  728. """Consumes a signed 32bit integer number.
  729. Returns:
  730. The integer parsed.
  731. Raises:
  732. ParseError: If a signed 32bit integer couldn't be consumed.
  733. """
  734. try:
  735. result = ParseInteger(self.token, is_signed=True, is_long=False)
  736. except ValueError as e:
  737. raise self._ParseError(str(e))
  738. self.NextToken()
  739. return result
  740. def ConsumeUint32(self):
  741. """Consumes an unsigned 32bit integer number.
  742. Returns:
  743. The integer parsed.
  744. Raises:
  745. ParseError: If an unsigned 32bit integer couldn't be consumed.
  746. """
  747. try:
  748. result = ParseInteger(self.token, is_signed=False, is_long=False)
  749. except ValueError as e:
  750. raise self._ParseError(str(e))
  751. self.NextToken()
  752. return result
  753. def TryConsumeInt64(self):
  754. try:
  755. self.ConsumeInt64()
  756. return True
  757. except ParseError:
  758. return False
  759. def ConsumeInt64(self):
  760. """Consumes a signed 64bit integer number.
  761. Returns:
  762. The integer parsed.
  763. Raises:
  764. ParseError: If a signed 64bit integer couldn't be consumed.
  765. """
  766. try:
  767. result = ParseInteger(self.token, is_signed=True, is_long=True)
  768. except ValueError as e:
  769. raise self._ParseError(str(e))
  770. self.NextToken()
  771. return result
  772. def TryConsumeUint64(self):
  773. try:
  774. self.ConsumeUint64()
  775. return True
  776. except ParseError:
  777. return False
  778. def ConsumeUint64(self):
  779. """Consumes an unsigned 64bit integer number.
  780. Returns:
  781. The integer parsed.
  782. Raises:
  783. ParseError: If an unsigned 64bit integer couldn't be consumed.
  784. """
  785. try:
  786. result = ParseInteger(self.token, is_signed=False, is_long=True)
  787. except ValueError as e:
  788. raise self._ParseError(str(e))
  789. self.NextToken()
  790. return result
  791. def TryConsumeFloat(self):
  792. try:
  793. self.ConsumeFloat()
  794. return True
  795. except ParseError:
  796. return False
  797. def ConsumeFloat(self):
  798. """Consumes an floating point number.
  799. Returns:
  800. The number parsed.
  801. Raises:
  802. ParseError: If a floating point number couldn't be consumed.
  803. """
  804. try:
  805. result = ParseFloat(self.token)
  806. except ValueError as e:
  807. raise self._ParseError(str(e))
  808. self.NextToken()
  809. return result
  810. def ConsumeBool(self):
  811. """Consumes a boolean value.
  812. Returns:
  813. The bool parsed.
  814. Raises:
  815. ParseError: If a boolean value couldn't be consumed.
  816. """
  817. try:
  818. result = ParseBool(self.token)
  819. except ValueError as e:
  820. raise self._ParseError(str(e))
  821. self.NextToken()
  822. return result
  823. def TryConsumeByteString(self):
  824. try:
  825. self.ConsumeByteString()
  826. return True
  827. except ParseError:
  828. return False
  829. def ConsumeString(self):
  830. """Consumes a string value.
  831. Returns:
  832. The string parsed.
  833. Raises:
  834. ParseError: If a string value couldn't be consumed.
  835. """
  836. the_bytes = self.ConsumeByteString()
  837. try:
  838. return six.text_type(the_bytes, 'utf-8')
  839. except UnicodeDecodeError as e:
  840. raise self._StringParseError(e)
  841. def ConsumeByteString(self):
  842. """Consumes a byte array value.
  843. Returns:
  844. The array parsed (as a string).
  845. Raises:
  846. ParseError: If a byte array value couldn't be consumed.
  847. """
  848. the_list = [self._ConsumeSingleByteString()]
  849. while self.token and self.token[0] in _QUOTES:
  850. the_list.append(self._ConsumeSingleByteString())
  851. return b''.join(the_list)
  852. def _ConsumeSingleByteString(self):
  853. """Consume one token of a string literal.
  854. String literals (whether bytes or text) can come in multiple adjacent
  855. tokens which are automatically concatenated, like in C or Python. This
  856. method only consumes one token.
  857. Returns:
  858. The token parsed.
  859. Raises:
  860. ParseError: When the wrong format data is found.
  861. """
  862. text = self.token
  863. if len(text) < 1 or text[0] not in _QUOTES:
  864. raise self._ParseError('Expected string but found: %r' % (text,))
  865. if len(text) < 2 or text[-1] != text[0]:
  866. raise self._ParseError('String missing ending quote: %r' % (text,))
  867. try:
  868. result = text_encoding.CUnescape(text[1:-1])
  869. except ValueError as e:
  870. raise self._ParseError(str(e))
  871. self.NextToken()
  872. return result
  873. def ConsumeEnum(self, field):
  874. try:
  875. result = ParseEnum(field, self.token)
  876. except ValueError as e:
  877. raise self._ParseError(str(e))
  878. self.NextToken()
  879. return result
  880. def ParseErrorPreviousToken(self, message):
  881. """Creates and *returns* a ParseError for the previously read token.
  882. Args:
  883. message: A message to set for the exception.
  884. Returns:
  885. A ParseError instance.
  886. """
  887. return ParseError('%d:%d : %s' % (
  888. self._previous_line + 1, self._previous_column + 1, message))
  889. def _ParseError(self, message):
  890. """Creates and *returns* a ParseError for the current token."""
  891. return ParseError('%d:%d : %s' % (
  892. self._line + 1, self._column + 1, message))
  893. def _StringParseError(self, e):
  894. return self._ParseError('Couldn\'t parse string: ' + str(e))
  895. def NextToken(self):
  896. """Reads the next meaningful token."""
  897. self._previous_line = self._line
  898. self._previous_column = self._column
  899. self._column += len(self.token)
  900. self._SkipWhitespace()
  901. if not self._more_lines:
  902. self.token = ''
  903. return
  904. match = self._TOKEN.match(self._current_line, self._column)
  905. if match:
  906. token = match.group(0)
  907. self.token = token
  908. else:
  909. self.token = self._current_line[self._column]
  910. def ParseInteger(text, is_signed=False, is_long=False):
  911. """Parses an integer.
  912. Args:
  913. text: The text to parse.
  914. is_signed: True if a signed integer must be parsed.
  915. is_long: True if a long integer must be parsed.
  916. Returns:
  917. The integer value.
  918. Raises:
  919. ValueError: Thrown Iff the text is not a valid integer.
  920. """
  921. # Do the actual parsing. Exception handling is propagated to caller.
  922. try:
  923. # We force 32-bit values to int and 64-bit values to long to make
  924. # alternate implementations where the distinction is more significant
  925. # (e.g. the C++ implementation) simpler.
  926. if is_long:
  927. result = long(text, 0)
  928. else:
  929. result = int(text, 0)
  930. except ValueError:
  931. raise ValueError('Couldn\'t parse integer: %s' % text)
  932. # Check if the integer is sane. Exceptions handled by callers.
  933. checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
  934. checker.CheckValue(result)
  935. return result
  936. def ParseFloat(text):
  937. """Parse a floating point number.
  938. Args:
  939. text: Text to parse.
  940. Returns:
  941. The number parsed.
  942. Raises:
  943. ValueError: If a floating point number couldn't be parsed.
  944. """
  945. try:
  946. # Assume Python compatible syntax.
  947. return float(text)
  948. except ValueError:
  949. # Check alternative spellings.
  950. if _FLOAT_INFINITY.match(text):
  951. if text[0] == '-':
  952. return float('-inf')
  953. else:
  954. return float('inf')
  955. elif _FLOAT_NAN.match(text):
  956. return float('nan')
  957. else:
  958. # assume '1.0f' format
  959. try:
  960. return float(text.rstrip('f'))
  961. except ValueError:
  962. raise ValueError('Couldn\'t parse float: %s' % text)
  963. def ParseBool(text):
  964. """Parse a boolean value.
  965. Args:
  966. text: Text to parse.
  967. Returns:
  968. Boolean values parsed
  969. Raises:
  970. ValueError: If text is not a valid boolean.
  971. """
  972. if text in ('true', 't', '1'):
  973. return True
  974. elif text in ('false', 'f', '0'):
  975. return False
  976. else:
  977. raise ValueError('Expected "true" or "false".')
  978. def ParseEnum(field, value):
  979. """Parse an enum value.
  980. The value can be specified by a number (the enum value), or by
  981. a string literal (the enum name).
  982. Args:
  983. field: Enum field descriptor.
  984. value: String value.
  985. Returns:
  986. Enum value number.
  987. Raises:
  988. ValueError: If the enum value could not be parsed.
  989. """
  990. enum_descriptor = field.enum_type
  991. try:
  992. number = int(value, 0)
  993. except ValueError:
  994. # Identifier.
  995. enum_value = enum_descriptor.values_by_name.get(value, None)
  996. if enum_value is None:
  997. raise ValueError(
  998. 'Enum type "%s" has no value named %s.' % (
  999. enum_descriptor.full_name, value))
  1000. else:
  1001. # Numeric value.
  1002. enum_value = enum_descriptor.values_by_number.get(number, None)
  1003. if enum_value is None:
  1004. raise ValueError(
  1005. 'Enum type "%s" has no value with number %d.' % (
  1006. enum_descriptor.full_name, number))
  1007. return enum_value.number