text_format.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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. # Copyright 2007 Google Inc. All Rights Reserved.
  31. """Contains routines for printing protocol messages in text format."""
  32. __author__ = 'kenton@google.com (Kenton Varda)'
  33. import io
  34. import re
  35. import six
  36. if six.PY3:
  37. long = int
  38. from google.protobuf.internal import type_checkers
  39. from google.protobuf import descriptor
  40. from google.protobuf import text_encoding
  41. __all__ = ['MessageToString', 'PrintMessage', 'PrintField',
  42. 'PrintFieldValue', 'Merge']
  43. _INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(),
  44. type_checkers.Int32ValueChecker(),
  45. type_checkers.Uint64ValueChecker(),
  46. type_checkers.Int64ValueChecker())
  47. _FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?', re.IGNORECASE)
  48. _FLOAT_NAN = re.compile('nanf?', re.IGNORECASE)
  49. _FLOAT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_FLOAT,
  50. descriptor.FieldDescriptor.CPPTYPE_DOUBLE])
  51. class Error(Exception):
  52. """Top-level module error for text_format."""
  53. class ParseError(Error):
  54. """Thrown in case of ASCII parsing error."""
  55. def MessageToString(message, as_utf8=False, as_one_line=False,
  56. pointy_brackets=False, use_index_order=False,
  57. float_format=None):
  58. """Convert protobuf message to text format.
  59. Floating point values can be formatted compactly with 15 digits of
  60. precision (which is the most that IEEE 754 "double" can guarantee)
  61. using float_format='.15g'.
  62. Args:
  63. message: The protocol buffers message.
  64. as_utf8: Produce text output in UTF8 format.
  65. as_one_line: Don't introduce newlines between fields.
  66. pointy_brackets: If True, use angle brackets instead of curly braces for
  67. nesting.
  68. use_index_order: If True, print fields of a proto message using the order
  69. defined in source code instead of the field number. By default, use the
  70. field number order.
  71. float_format: If set, use this to specify floating point number formatting
  72. (per the "Format Specification Mini-Language"); otherwise, str() is used.
  73. Returns:
  74. A string of the text formatted protocol buffer message.
  75. """
  76. out = io.BytesIO()
  77. PrintMessage(message, out, as_utf8=as_utf8, as_one_line=as_one_line,
  78. pointy_brackets=pointy_brackets,
  79. use_index_order=use_index_order,
  80. float_format=float_format)
  81. result = out.getvalue()
  82. out.close()
  83. if as_one_line:
  84. return result.rstrip()
  85. return result
  86. def _IsMapEntry(field):
  87. return (field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  88. field.message_type.has_options and
  89. field.message_type.GetOptions().map_entry)
  90. def PrintMessage(message, out, indent=0, as_utf8=False, as_one_line=False,
  91. pointy_brackets=False, use_index_order=False,
  92. float_format=None):
  93. fields = message.ListFields()
  94. if use_index_order:
  95. fields.sort(key=lambda x: x[0].index)
  96. for field, value in fields:
  97. if _IsMapEntry(field):
  98. for key in sorted(value):
  99. # This is slow for maps with submessage entires because it copies the
  100. # entire tree. Unfortunately this would take significant refactoring
  101. # of this file to work around.
  102. #
  103. # TODO(haberman): refactor and optimize if this becomes an issue.
  104. entry_submsg = field.message_type._concrete_class(
  105. key=key, value=value[key])
  106. PrintField(field, entry_submsg, out, indent, as_utf8, as_one_line,
  107. pointy_brackets=pointy_brackets,
  108. use_index_order=use_index_order, float_format=float_format)
  109. elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  110. for element in value:
  111. PrintField(field, element, out, indent, as_utf8, as_one_line,
  112. pointy_brackets=pointy_brackets,
  113. use_index_order=use_index_order,
  114. float_format=float_format)
  115. else:
  116. PrintField(field, value, out, indent, as_utf8, as_one_line,
  117. pointy_brackets=pointy_brackets,
  118. use_index_order=use_index_order,
  119. float_format=float_format)
  120. def PrintField(field, value, out, indent=0, as_utf8=False, as_one_line=False,
  121. pointy_brackets=False, use_index_order=False, float_format=None):
  122. """Print a single field name/value pair. For repeated fields, the value
  123. should be a single element."""
  124. out.write(' ' * indent)
  125. if field.is_extension:
  126. out.write('[')
  127. if (field.containing_type.GetOptions().message_set_wire_format and
  128. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  129. field.message_type == field.extension_scope and
  130. field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL):
  131. out.write(field.message_type.full_name)
  132. else:
  133. out.write(field.full_name)
  134. out.write(']')
  135. elif field.type == descriptor.FieldDescriptor.TYPE_GROUP:
  136. # For groups, use the capitalized name.
  137. out.write(field.message_type.name)
  138. else:
  139. if isinstance(field.name, six.text_type):
  140. name = field.name.encode('utf-8')
  141. else:
  142. name = field.name
  143. out.write(name)
  144. if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  145. # The colon is optional in this case, but our cross-language golden files
  146. # don't include it.
  147. out.write(': ')
  148. PrintFieldValue(field, value, out, indent, as_utf8, as_one_line,
  149. pointy_brackets=pointy_brackets,
  150. use_index_order=use_index_order,
  151. float_format=float_format)
  152. if as_one_line:
  153. out.write(' ')
  154. else:
  155. out.write('\n')
  156. def PrintFieldValue(field, value, out, indent=0, as_utf8=False,
  157. as_one_line=False, pointy_brackets=False,
  158. use_index_order=False,
  159. float_format=None):
  160. """Print a single field value (not including name). For repeated fields,
  161. the value should be a single element."""
  162. if pointy_brackets:
  163. openb = '<'
  164. closeb = '>'
  165. else:
  166. openb = '{'
  167. closeb = '}'
  168. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  169. if as_one_line:
  170. out.write(' %s ' % openb)
  171. PrintMessage(value, out, indent, as_utf8, as_one_line,
  172. pointy_brackets=pointy_brackets,
  173. use_index_order=use_index_order,
  174. float_format=float_format)
  175. out.write(closeb)
  176. else:
  177. out.write(' %s\n' % openb)
  178. PrintMessage(value, out, indent + 2, as_utf8, as_one_line,
  179. pointy_brackets=pointy_brackets,
  180. use_index_order=use_index_order,
  181. float_format=float_format)
  182. out.write(' ' * indent + closeb)
  183. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
  184. enum_value = field.enum_type.values_by_number.get(value, None)
  185. if enum_value is not None:
  186. out.write(enum_value.name)
  187. else:
  188. out.write(str(value))
  189. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
  190. out.write('\"')
  191. if isinstance(value, six.text_type):
  192. out_value = value.encode('utf-8')
  193. else:
  194. out_value = value
  195. if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  196. # We need to escape non-UTF8 chars in TYPE_BYTES field.
  197. out_as_utf8 = False
  198. else:
  199. out_as_utf8 = as_utf8
  200. out.write(text_encoding.CEscape(out_value, out_as_utf8))
  201. out.write('\"')
  202. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
  203. if value:
  204. out.write('true')
  205. else:
  206. out.write('false')
  207. elif field.cpp_type in _FLOAT_TYPES and float_format is not None:
  208. out.write('{1:{0}}'.format(float_format, value))
  209. else:
  210. out.write(str(value))
  211. def Parse(text, message):
  212. """Parses an ASCII representation of a protocol message into a message.
  213. Args:
  214. text: Message ASCII representation.
  215. message: A protocol buffer message to merge into.
  216. Returns:
  217. The same message passed as argument.
  218. Raises:
  219. ParseError: On ASCII parsing problems.
  220. """
  221. if not isinstance(text, str): text = text.decode('utf-8')
  222. return ParseLines(text.split('\n'), message)
  223. def Merge(text, message):
  224. """Parses an ASCII representation of a protocol message into a message.
  225. Like Parse(), but allows repeated values for a non-repeated field, and uses
  226. the last one.
  227. Args:
  228. text: Message ASCII representation.
  229. message: A protocol buffer message to merge into.
  230. Returns:
  231. The same message passed as argument.
  232. Raises:
  233. ParseError: On ASCII parsing problems.
  234. """
  235. return MergeLines(text.split('\n'), message)
  236. def ParseLines(lines, message):
  237. """Parses an ASCII representation of a protocol message into a message.
  238. Args:
  239. lines: An iterable of lines of a message's ASCII representation.
  240. message: A protocol buffer message to merge into.
  241. Returns:
  242. The same message passed as argument.
  243. Raises:
  244. ParseError: On ASCII parsing problems.
  245. """
  246. _ParseOrMerge(lines, message, False)
  247. return message
  248. def MergeLines(lines, message):
  249. """Parses an ASCII representation of a protocol message into a message.
  250. Args:
  251. lines: An iterable of lines of a message's ASCII representation.
  252. message: A protocol buffer message to merge into.
  253. Returns:
  254. The same message passed as argument.
  255. Raises:
  256. ParseError: On ASCII parsing problems.
  257. """
  258. _ParseOrMerge(lines, message, True)
  259. return message
  260. def _ParseOrMerge(lines, message, allow_multiple_scalars):
  261. """Converts an ASCII representation of a protocol message into a message.
  262. Args:
  263. lines: Lines of a message's ASCII representation.
  264. message: A protocol buffer message to merge into.
  265. allow_multiple_scalars: Determines if repeated values for a non-repeated
  266. field are permitted, e.g., the string "foo: 1 foo: 2" for a
  267. required/optional field named "foo".
  268. Raises:
  269. ParseError: On ASCII parsing problems.
  270. """
  271. tokenizer = _Tokenizer(lines)
  272. while not tokenizer.AtEnd():
  273. _MergeField(tokenizer, message, allow_multiple_scalars)
  274. def _MergeField(tokenizer, message, allow_multiple_scalars):
  275. """Merges a single protocol message field into a message.
  276. Args:
  277. tokenizer: A tokenizer to parse the field name and values.
  278. message: A protocol message to record the data.
  279. allow_multiple_scalars: Determines if repeated values for a non-repeated
  280. field are permitted, e.g., the string "foo: 1 foo: 2" for a
  281. required/optional field named "foo".
  282. Raises:
  283. ParseError: In case of ASCII parsing problems.
  284. """
  285. message_descriptor = message.DESCRIPTOR
  286. if (hasattr(message_descriptor, 'syntax') and
  287. message_descriptor.syntax == 'proto3'):
  288. # Proto3 doesn't represent presence so we can't test if multiple
  289. # scalars have occurred. We have to allow them.
  290. allow_multiple_scalars = True
  291. if tokenizer.TryConsume('['):
  292. name = [tokenizer.ConsumeIdentifier()]
  293. while tokenizer.TryConsume('.'):
  294. name.append(tokenizer.ConsumeIdentifier())
  295. name = '.'.join(name)
  296. if not message_descriptor.is_extendable:
  297. raise tokenizer.ParseErrorPreviousToken(
  298. 'Message type "%s" does not have extensions.' %
  299. message_descriptor.full_name)
  300. # pylint: disable=protected-access
  301. field = message.Extensions._FindExtensionByName(name)
  302. # pylint: enable=protected-access
  303. if not field:
  304. raise tokenizer.ParseErrorPreviousToken(
  305. 'Extension "%s" not registered.' % name)
  306. elif message_descriptor != field.containing_type:
  307. raise tokenizer.ParseErrorPreviousToken(
  308. 'Extension "%s" does not extend message type "%s".' % (
  309. name, message_descriptor.full_name))
  310. tokenizer.Consume(']')
  311. else:
  312. name = tokenizer.ConsumeIdentifier()
  313. field = message_descriptor.fields_by_name.get(name, None)
  314. # Group names are expected to be capitalized as they appear in the
  315. # .proto file, which actually matches their type names, not their field
  316. # names.
  317. if not field:
  318. field = message_descriptor.fields_by_name.get(name.lower(), None)
  319. if field and field.type != descriptor.FieldDescriptor.TYPE_GROUP:
  320. field = None
  321. if (field and field.type == descriptor.FieldDescriptor.TYPE_GROUP and
  322. field.message_type.name != name):
  323. field = None
  324. if not field:
  325. raise tokenizer.ParseErrorPreviousToken(
  326. 'Message type "%s" has no field named "%s".' % (
  327. message_descriptor.full_name, name))
  328. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  329. is_map_entry = _IsMapEntry(field)
  330. tokenizer.TryConsume(':')
  331. if tokenizer.TryConsume('<'):
  332. end_token = '>'
  333. else:
  334. tokenizer.Consume('{')
  335. end_token = '}'
  336. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  337. if field.is_extension:
  338. sub_message = message.Extensions[field].add()
  339. elif is_map_entry:
  340. sub_message = field.message_type._concrete_class()
  341. else:
  342. sub_message = getattr(message, field.name).add()
  343. else:
  344. if field.is_extension:
  345. sub_message = message.Extensions[field]
  346. else:
  347. sub_message = getattr(message, field.name)
  348. sub_message.SetInParent()
  349. while not tokenizer.TryConsume(end_token):
  350. if tokenizer.AtEnd():
  351. raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token))
  352. _MergeField(tokenizer, sub_message, allow_multiple_scalars)
  353. if is_map_entry:
  354. value_cpptype = field.message_type.fields_by_name['value'].cpp_type
  355. if value_cpptype == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  356. value = getattr(message, field.name)[sub_message.key]
  357. value.MergeFrom(sub_message.value)
  358. else:
  359. getattr(message, field.name)[sub_message.key] = sub_message.value
  360. else:
  361. _MergeScalarField(tokenizer, message, field, allow_multiple_scalars)
  362. # For historical reasons, fields may optionally be separated by commas or
  363. # semicolons.
  364. if not tokenizer.TryConsume(','):
  365. tokenizer.TryConsume(';')
  366. def _MergeScalarField(tokenizer, message, field, allow_multiple_scalars):
  367. """Merges a single protocol message scalar field into a message.
  368. Args:
  369. tokenizer: A tokenizer to parse the field value.
  370. message: A protocol message to record the data.
  371. field: The descriptor of the field to be merged.
  372. allow_multiple_scalars: Determines if repeated values for a non-repeated
  373. field are permitted, e.g., the string "foo: 1 foo: 2" for a
  374. required/optional field named "foo".
  375. Raises:
  376. ParseError: In case of ASCII parsing problems.
  377. RuntimeError: On runtime errors.
  378. """
  379. tokenizer.Consume(':')
  380. value = None
  381. if field.type in (descriptor.FieldDescriptor.TYPE_INT32,
  382. descriptor.FieldDescriptor.TYPE_SINT32,
  383. descriptor.FieldDescriptor.TYPE_SFIXED32):
  384. value = tokenizer.ConsumeInt32()
  385. elif field.type in (descriptor.FieldDescriptor.TYPE_INT64,
  386. descriptor.FieldDescriptor.TYPE_SINT64,
  387. descriptor.FieldDescriptor.TYPE_SFIXED64):
  388. value = tokenizer.ConsumeInt64()
  389. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32,
  390. descriptor.FieldDescriptor.TYPE_FIXED32):
  391. value = tokenizer.ConsumeUint32()
  392. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64,
  393. descriptor.FieldDescriptor.TYPE_FIXED64):
  394. value = tokenizer.ConsumeUint64()
  395. elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT,
  396. descriptor.FieldDescriptor.TYPE_DOUBLE):
  397. value = tokenizer.ConsumeFloat()
  398. elif field.type == descriptor.FieldDescriptor.TYPE_BOOL:
  399. value = tokenizer.ConsumeBool()
  400. elif field.type == descriptor.FieldDescriptor.TYPE_STRING:
  401. value = tokenizer.ConsumeString()
  402. elif field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  403. value = tokenizer.ConsumeByteString()
  404. elif field.type == descriptor.FieldDescriptor.TYPE_ENUM:
  405. value = tokenizer.ConsumeEnum(field)
  406. else:
  407. raise RuntimeError('Unknown field type %d' % field.type)
  408. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  409. if field.is_extension:
  410. message.Extensions[field].append(value)
  411. else:
  412. getattr(message, field.name).append(value)
  413. else:
  414. if field.is_extension:
  415. if not allow_multiple_scalars and message.HasExtension(field):
  416. raise tokenizer.ParseErrorPreviousToken(
  417. 'Message type "%s" should not have multiple "%s" extensions.' %
  418. (message.DESCRIPTOR.full_name, field.full_name))
  419. else:
  420. message.Extensions[field] = value
  421. else:
  422. if not allow_multiple_scalars and message.HasField(field.name):
  423. raise tokenizer.ParseErrorPreviousToken(
  424. 'Message type "%s" should not have multiple "%s" fields.' %
  425. (message.DESCRIPTOR.full_name, field.name))
  426. else:
  427. setattr(message, field.name, value)
  428. class _Tokenizer(object):
  429. """Protocol buffer ASCII representation tokenizer.
  430. This class handles the lower level string parsing by splitting it into
  431. meaningful tokens.
  432. It was directly ported from the Java protocol buffer API.
  433. """
  434. _WHITESPACE = re.compile('(\\s|(#.*$))+', re.MULTILINE)
  435. _TOKEN = re.compile(
  436. '[a-zA-Z_][0-9a-zA-Z_+-]*|' # an identifier
  437. '[0-9+-][0-9a-zA-Z_.+-]*|' # a number
  438. '\"([^\"\n\\\\]|\\\\.)*(\"|\\\\?$)|' # a double-quoted string
  439. '\'([^\'\n\\\\]|\\\\.)*(\'|\\\\?$)') # a single-quoted string
  440. _IDENTIFIER = re.compile(r'\w+')
  441. def __init__(self, lines):
  442. self._position = 0
  443. self._line = -1
  444. self._column = 0
  445. self._token_start = None
  446. self.token = ''
  447. self._lines = iter(lines)
  448. self._current_line = ''
  449. self._previous_line = 0
  450. self._previous_column = 0
  451. self._more_lines = True
  452. self._SkipWhitespace()
  453. self.NextToken()
  454. def AtEnd(self):
  455. """Checks the end of the text was reached.
  456. Returns:
  457. True iff the end was reached.
  458. """
  459. return not self.token
  460. def _PopLine(self):
  461. while len(self._current_line) <= self._column:
  462. try:
  463. self._current_line = next(self._lines)
  464. except StopIteration:
  465. self._current_line = ''
  466. self._more_lines = False
  467. return
  468. else:
  469. self._line += 1
  470. self._column = 0
  471. def _SkipWhitespace(self):
  472. while True:
  473. self._PopLine()
  474. match = self._WHITESPACE.match(self._current_line, self._column)
  475. if not match:
  476. break
  477. length = len(match.group(0))
  478. self._column += length
  479. def TryConsume(self, token):
  480. """Tries to consume a given piece of text.
  481. Args:
  482. token: Text to consume.
  483. Returns:
  484. True iff the text was consumed.
  485. """
  486. if self.token == token:
  487. self.NextToken()
  488. return True
  489. return False
  490. def Consume(self, token):
  491. """Consumes a piece of text.
  492. Args:
  493. token: Text to consume.
  494. Raises:
  495. ParseError: If the text couldn't be consumed.
  496. """
  497. if not self.TryConsume(token):
  498. raise self._ParseError('Expected "%s".' % token)
  499. def ConsumeIdentifier(self):
  500. """Consumes protocol message field identifier.
  501. Returns:
  502. Identifier string.
  503. Raises:
  504. ParseError: If an identifier couldn't be consumed.
  505. """
  506. result = self.token
  507. if not self._IDENTIFIER.match(result):
  508. raise self._ParseError('Expected identifier.')
  509. self.NextToken()
  510. return result
  511. def ConsumeInt32(self):
  512. """Consumes a signed 32bit integer number.
  513. Returns:
  514. The integer parsed.
  515. Raises:
  516. ParseError: If a signed 32bit integer couldn't be consumed.
  517. """
  518. try:
  519. result = ParseInteger(self.token, is_signed=True, is_long=False)
  520. except ValueError as e:
  521. raise self._ParseError(str(e))
  522. self.NextToken()
  523. return result
  524. def ConsumeUint32(self):
  525. """Consumes an unsigned 32bit integer number.
  526. Returns:
  527. The integer parsed.
  528. Raises:
  529. ParseError: If an unsigned 32bit integer couldn't be consumed.
  530. """
  531. try:
  532. result = ParseInteger(self.token, is_signed=False, is_long=False)
  533. except ValueError as e:
  534. raise self._ParseError(str(e))
  535. self.NextToken()
  536. return result
  537. def ConsumeInt64(self):
  538. """Consumes a signed 64bit integer number.
  539. Returns:
  540. The integer parsed.
  541. Raises:
  542. ParseError: If a signed 64bit integer couldn't be consumed.
  543. """
  544. try:
  545. result = ParseInteger(self.token, is_signed=True, is_long=True)
  546. except ValueError as e:
  547. raise self._ParseError(str(e))
  548. self.NextToken()
  549. return result
  550. def ConsumeUint64(self):
  551. """Consumes an unsigned 64bit integer number.
  552. Returns:
  553. The integer parsed.
  554. Raises:
  555. ParseError: If an unsigned 64bit integer couldn't be consumed.
  556. """
  557. try:
  558. result = ParseInteger(self.token, is_signed=False, is_long=True)
  559. except ValueError as e:
  560. raise self._ParseError(str(e))
  561. self.NextToken()
  562. return result
  563. def ConsumeFloat(self):
  564. """Consumes an floating point number.
  565. Returns:
  566. The number parsed.
  567. Raises:
  568. ParseError: If a floating point number couldn't be consumed.
  569. """
  570. try:
  571. result = ParseFloat(self.token)
  572. except ValueError as e:
  573. raise self._ParseError(str(e))
  574. self.NextToken()
  575. return result
  576. def ConsumeBool(self):
  577. """Consumes a boolean value.
  578. Returns:
  579. The bool parsed.
  580. Raises:
  581. ParseError: If a boolean value couldn't be consumed.
  582. """
  583. try:
  584. result = ParseBool(self.token)
  585. except ValueError as e:
  586. raise self._ParseError(str(e))
  587. self.NextToken()
  588. return result
  589. def ConsumeString(self):
  590. """Consumes a string value.
  591. Returns:
  592. The string parsed.
  593. Raises:
  594. ParseError: If a string value couldn't be consumed.
  595. """
  596. the_bytes = self.ConsumeByteString()
  597. try:
  598. return six.text_type(the_bytes, 'utf-8')
  599. except UnicodeDecodeError as e:
  600. raise self._StringParseError(e)
  601. def ConsumeByteString(self):
  602. """Consumes a byte array value.
  603. Returns:
  604. The array parsed (as a string).
  605. Raises:
  606. ParseError: If a byte array value couldn't be consumed.
  607. """
  608. the_list = [self._ConsumeSingleByteString()]
  609. while self.token and self.token[0] in ('\'', '"'):
  610. the_list.append(self._ConsumeSingleByteString())
  611. return b''.join(the_list)
  612. def _ConsumeSingleByteString(self):
  613. """Consume one token of a string literal.
  614. String literals (whether bytes or text) can come in multiple adjacent
  615. tokens which are automatically concatenated, like in C or Python. This
  616. method only consumes one token.
  617. Raises:
  618. ParseError: When the wrong format data is found.
  619. """
  620. text = self.token
  621. if len(text) < 1 or text[0] not in ('\'', '"'):
  622. raise self._ParseError('Expected string but found: %r' % (text,))
  623. if len(text) < 2 or text[-1] != text[0]:
  624. raise self._ParseError('String missing ending quote: %r' % (text,))
  625. try:
  626. result = text_encoding.CUnescape(text[1:-1])
  627. except ValueError as e:
  628. raise self._ParseError(str(e))
  629. self.NextToken()
  630. return result
  631. def ConsumeEnum(self, field):
  632. try:
  633. result = ParseEnum(field, self.token)
  634. except ValueError as e:
  635. raise self._ParseError(str(e))
  636. self.NextToken()
  637. return result
  638. def ParseErrorPreviousToken(self, message):
  639. """Creates and *returns* a ParseError for the previously read token.
  640. Args:
  641. message: A message to set for the exception.
  642. Returns:
  643. A ParseError instance.
  644. """
  645. return ParseError('%d:%d : %s' % (
  646. self._previous_line + 1, self._previous_column + 1, message))
  647. def _ParseError(self, message):
  648. """Creates and *returns* a ParseError for the current token."""
  649. return ParseError('%d:%d : %s' % (
  650. self._line + 1, self._column + 1, message))
  651. def _StringParseError(self, e):
  652. return self._ParseError('Couldn\'t parse string: ' + str(e))
  653. def NextToken(self):
  654. """Reads the next meaningful token."""
  655. self._previous_line = self._line
  656. self._previous_column = self._column
  657. self._column += len(self.token)
  658. self._SkipWhitespace()
  659. if not self._more_lines:
  660. self.token = ''
  661. return
  662. match = self._TOKEN.match(self._current_line, self._column)
  663. if match:
  664. token = match.group(0)
  665. self.token = token
  666. else:
  667. self.token = self._current_line[self._column]
  668. def ParseInteger(text, is_signed=False, is_long=False):
  669. """Parses an integer.
  670. Args:
  671. text: The text to parse.
  672. is_signed: True if a signed integer must be parsed.
  673. is_long: True if a long integer must be parsed.
  674. Returns:
  675. The integer value.
  676. Raises:
  677. ValueError: Thrown Iff the text is not a valid integer.
  678. """
  679. # Do the actual parsing. Exception handling is propagated to caller.
  680. try:
  681. # We force 32-bit values to int and 64-bit values to long to make
  682. # alternate implementations where the distinction is more significant
  683. # (e.g. the C++ implementation) simpler.
  684. if is_long:
  685. result = long(text, 0)
  686. else:
  687. result = int(text, 0)
  688. except ValueError:
  689. raise ValueError('Couldn\'t parse integer: %s' % text)
  690. # Check if the integer is sane. Exceptions handled by callers.
  691. checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
  692. checker.CheckValue(result)
  693. return result
  694. def ParseFloat(text):
  695. """Parse a floating point number.
  696. Args:
  697. text: Text to parse.
  698. Returns:
  699. The number parsed.
  700. Raises:
  701. ValueError: If a floating point number couldn't be parsed.
  702. """
  703. try:
  704. # Assume Python compatible syntax.
  705. return float(text)
  706. except ValueError:
  707. # Check alternative spellings.
  708. if _FLOAT_INFINITY.match(text):
  709. if text[0] == '-':
  710. return float('-inf')
  711. else:
  712. return float('inf')
  713. elif _FLOAT_NAN.match(text):
  714. return float('nan')
  715. else:
  716. # assume '1.0f' format
  717. try:
  718. return float(text.rstrip('f'))
  719. except ValueError:
  720. raise ValueError('Couldn\'t parse float: %s' % text)
  721. def ParseBool(text):
  722. """Parse a boolean value.
  723. Args:
  724. text: Text to parse.
  725. Returns:
  726. Boolean values parsed
  727. Raises:
  728. ValueError: If text is not a valid boolean.
  729. """
  730. if text in ('true', 't', '1'):
  731. return True
  732. elif text in ('false', 'f', '0'):
  733. return False
  734. else:
  735. raise ValueError('Expected "true" or "false".')
  736. def ParseEnum(field, value):
  737. """Parse an enum value.
  738. The value can be specified by a number (the enum value), or by
  739. a string literal (the enum name).
  740. Args:
  741. field: Enum field descriptor.
  742. value: String value.
  743. Returns:
  744. Enum value number.
  745. Raises:
  746. ValueError: If the enum value could not be parsed.
  747. """
  748. enum_descriptor = field.enum_type
  749. try:
  750. number = int(value, 0)
  751. except ValueError:
  752. # Identifier.
  753. enum_value = enum_descriptor.values_by_name.get(value, None)
  754. if enum_value is None:
  755. raise ValueError(
  756. 'Enum type "%s" has no value named %s.' % (
  757. enum_descriptor.full_name, value))
  758. else:
  759. # Numeric value.
  760. enum_value = enum_descriptor.values_by_number.get(number, None)
  761. if enum_value is None:
  762. raise ValueError(
  763. 'Enum type "%s" has no value with number %d.' % (
  764. enum_descriptor.full_name, number))
  765. return enum_value.number