text_format.py 29 KB

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