text_format.py 28 KB

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