text_format.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # http://code.google.com/p/protobuf/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Contains routines for printing protocol messages in text format."""
  31. __author__ = 'kenton@google.com (Kenton Varda)'
  32. import cStringIO
  33. import re
  34. from collections import deque
  35. from google.protobuf.internal import type_checkers
  36. from google.protobuf import descriptor
  37. __all__ = [ 'MessageToString', 'PrintMessage', 'PrintField',
  38. 'PrintFieldValue', 'Merge' ]
  39. _INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(),
  40. type_checkers.Int32ValueChecker(),
  41. type_checkers.Uint64ValueChecker(),
  42. type_checkers.Int64ValueChecker())
  43. _FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?', re.IGNORECASE)
  44. _FLOAT_NAN = re.compile('nanf?', re.IGNORECASE)
  45. class ParseError(Exception):
  46. """Thrown in case of ASCII parsing error."""
  47. def MessageToString(message, as_utf8=False, as_one_line=False):
  48. out = cStringIO.StringIO()
  49. PrintMessage(message, out, as_utf8=as_utf8, as_one_line=as_one_line)
  50. result = out.getvalue()
  51. out.close()
  52. if as_one_line:
  53. return result.rstrip()
  54. return result
  55. def PrintMessage(message, out, indent=0, as_utf8=False, as_one_line=False):
  56. for field, value in message.ListFields():
  57. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  58. for element in value:
  59. PrintField(field, element, out, indent, as_utf8, as_one_line)
  60. else:
  61. PrintField(field, value, out, indent, as_utf8, as_one_line)
  62. def PrintField(field, value, out, indent=0, as_utf8=False, as_one_line=False):
  63. """Print a single field name/value pair. For repeated fields, the value
  64. should be a single element."""
  65. out.write(' ' * indent);
  66. if field.is_extension:
  67. out.write('[')
  68. if (field.containing_type.GetOptions().message_set_wire_format and
  69. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  70. field.message_type == field.extension_scope and
  71. field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL):
  72. out.write(field.message_type.full_name)
  73. else:
  74. out.write(field.full_name)
  75. out.write(']')
  76. elif field.type == descriptor.FieldDescriptor.TYPE_GROUP:
  77. # For groups, use the capitalized name.
  78. out.write(field.message_type.name)
  79. else:
  80. out.write(field.name)
  81. if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  82. # The colon is optional in this case, but our cross-language golden files
  83. # don't include it.
  84. out.write(': ')
  85. PrintFieldValue(field, value, out, indent, as_utf8, as_one_line)
  86. if as_one_line:
  87. out.write(' ')
  88. else:
  89. out.write('\n')
  90. def PrintFieldValue(field, value, out, indent=0,
  91. as_utf8=False, as_one_line=False):
  92. """Print a single field value (not including name). For repeated fields,
  93. the value should be a single element."""
  94. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  95. if as_one_line:
  96. out.write(' { ')
  97. PrintMessage(value, out, indent, as_utf8, as_one_line)
  98. out.write('}')
  99. else:
  100. out.write(' {\n')
  101. PrintMessage(value, out, indent + 2, as_utf8, as_one_line)
  102. out.write(' ' * indent + '}')
  103. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
  104. enum_value = field.enum_type.values_by_number.get(value, None)
  105. if enum_value is not None:
  106. out.write(enum_value.name)
  107. else:
  108. out.write(str(value))
  109. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
  110. out.write('\"')
  111. if type(value) is unicode:
  112. out.write(_CEscape(value.encode('utf-8'), as_utf8))
  113. else:
  114. out.write(_CEscape(value, as_utf8))
  115. out.write('\"')
  116. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
  117. if value:
  118. out.write("true")
  119. else:
  120. out.write("false")
  121. else:
  122. out.write(str(value))
  123. def Merge(text, message):
  124. """Merges an ASCII representation of a protocol message into a message.
  125. Args:
  126. text: Message ASCII representation.
  127. message: A protocol buffer message to merge into.
  128. Raises:
  129. ParseError: On ASCII parsing problems.
  130. """
  131. tokenizer = _Tokenizer(text)
  132. while not tokenizer.AtEnd():
  133. _MergeField(tokenizer, message)
  134. def _MergeField(tokenizer, message):
  135. """Merges a single protocol message field into a message.
  136. Args:
  137. tokenizer: A tokenizer to parse the field name and values.
  138. message: A protocol message to record the data.
  139. Raises:
  140. ParseError: In case of ASCII parsing problems.
  141. """
  142. message_descriptor = message.DESCRIPTOR
  143. if tokenizer.TryConsume('['):
  144. name = [tokenizer.ConsumeIdentifier()]
  145. while tokenizer.TryConsume('.'):
  146. name.append(tokenizer.ConsumeIdentifier())
  147. name = '.'.join(name)
  148. if not message_descriptor.is_extendable:
  149. raise tokenizer.ParseErrorPreviousToken(
  150. 'Message type "%s" does not have extensions.' %
  151. message_descriptor.full_name)
  152. field = message.Extensions._FindExtensionByName(name)
  153. if not field:
  154. raise tokenizer.ParseErrorPreviousToken(
  155. 'Extension "%s" not registered.' % name)
  156. elif message_descriptor != field.containing_type:
  157. raise tokenizer.ParseErrorPreviousToken(
  158. 'Extension "%s" does not extend message type "%s".' % (
  159. name, message_descriptor.full_name))
  160. tokenizer.Consume(']')
  161. else:
  162. name = tokenizer.ConsumeIdentifier()
  163. field = message_descriptor.fields_by_name.get(name, None)
  164. # Group names are expected to be capitalized as they appear in the
  165. # .proto file, which actually matches their type names, not their field
  166. # names.
  167. if not field:
  168. field = message_descriptor.fields_by_name.get(name.lower(), None)
  169. if field and field.type != descriptor.FieldDescriptor.TYPE_GROUP:
  170. field = None
  171. if (field and field.type == descriptor.FieldDescriptor.TYPE_GROUP and
  172. field.message_type.name != name):
  173. field = None
  174. if not field:
  175. raise tokenizer.ParseErrorPreviousToken(
  176. 'Message type "%s" has no field named "%s".' % (
  177. message_descriptor.full_name, name))
  178. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  179. tokenizer.TryConsume(':')
  180. if tokenizer.TryConsume('<'):
  181. end_token = '>'
  182. else:
  183. tokenizer.Consume('{')
  184. end_token = '}'
  185. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  186. if field.is_extension:
  187. sub_message = message.Extensions[field].add()
  188. else:
  189. sub_message = getattr(message, field.name).add()
  190. else:
  191. if field.is_extension:
  192. sub_message = message.Extensions[field]
  193. else:
  194. sub_message = getattr(message, field.name)
  195. sub_message.SetInParent()
  196. while not tokenizer.TryConsume(end_token):
  197. if tokenizer.AtEnd():
  198. raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token))
  199. _MergeField(tokenizer, sub_message)
  200. else:
  201. _MergeScalarField(tokenizer, message, field)
  202. def _MergeScalarField(tokenizer, message, field):
  203. """Merges a single protocol message scalar field into a message.
  204. Args:
  205. tokenizer: A tokenizer to parse the field value.
  206. message: A protocol message to record the data.
  207. field: The descriptor of the field to be merged.
  208. Raises:
  209. ParseError: In case of ASCII parsing problems.
  210. RuntimeError: On runtime errors.
  211. """
  212. tokenizer.Consume(':')
  213. value = None
  214. if field.type in (descriptor.FieldDescriptor.TYPE_INT32,
  215. descriptor.FieldDescriptor.TYPE_SINT32,
  216. descriptor.FieldDescriptor.TYPE_SFIXED32):
  217. value = tokenizer.ConsumeInt32()
  218. elif field.type in (descriptor.FieldDescriptor.TYPE_INT64,
  219. descriptor.FieldDescriptor.TYPE_SINT64,
  220. descriptor.FieldDescriptor.TYPE_SFIXED64):
  221. value = tokenizer.ConsumeInt64()
  222. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32,
  223. descriptor.FieldDescriptor.TYPE_FIXED32):
  224. value = tokenizer.ConsumeUint32()
  225. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64,
  226. descriptor.FieldDescriptor.TYPE_FIXED64):
  227. value = tokenizer.ConsumeUint64()
  228. elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT,
  229. descriptor.FieldDescriptor.TYPE_DOUBLE):
  230. value = tokenizer.ConsumeFloat()
  231. elif field.type == descriptor.FieldDescriptor.TYPE_BOOL:
  232. value = tokenizer.ConsumeBool()
  233. elif field.type == descriptor.FieldDescriptor.TYPE_STRING:
  234. value = tokenizer.ConsumeString()
  235. elif field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  236. value = tokenizer.ConsumeByteString()
  237. elif field.type == descriptor.FieldDescriptor.TYPE_ENUM:
  238. value = tokenizer.ConsumeEnum(field)
  239. else:
  240. raise RuntimeError('Unknown field type %d' % field.type)
  241. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  242. if field.is_extension:
  243. message.Extensions[field].append(value)
  244. else:
  245. getattr(message, field.name).append(value)
  246. else:
  247. if field.is_extension:
  248. message.Extensions[field] = value
  249. else:
  250. setattr(message, field.name, value)
  251. class _Tokenizer(object):
  252. """Protocol buffer ASCII representation tokenizer.
  253. This class handles the lower level string parsing by splitting it into
  254. meaningful tokens.
  255. It was directly ported from the Java protocol buffer API.
  256. """
  257. _WHITESPACE = re.compile('(\\s|(#.*$))+', re.MULTILINE)
  258. _TOKEN = re.compile(
  259. '[a-zA-Z_][0-9a-zA-Z_+-]*|' # an identifier
  260. '[0-9+-][0-9a-zA-Z_.+-]*|' # a number
  261. '\"([^\"\n\\\\]|\\\\.)*(\"|\\\\?$)|' # a double-quoted string
  262. '\'([^\'\n\\\\]|\\\\.)*(\'|\\\\?$)') # a single-quoted string
  263. _IDENTIFIER = re.compile('\w+')
  264. def __init__(self, text_message):
  265. self._text_message = text_message
  266. self._position = 0
  267. self._line = -1
  268. self._column = 0
  269. self._token_start = None
  270. self.token = ''
  271. self._lines = deque(text_message.split('\n'))
  272. self._current_line = ''
  273. self._previous_line = 0
  274. self._previous_column = 0
  275. self._SkipWhitespace()
  276. self.NextToken()
  277. def AtEnd(self):
  278. """Checks the end of the text was reached.
  279. Returns:
  280. True iff the end was reached.
  281. """
  282. return self.token == ''
  283. def _PopLine(self):
  284. while len(self._current_line) <= self._column:
  285. if not self._lines:
  286. self._current_line = ''
  287. return
  288. self._line += 1
  289. self._column = 0
  290. self._current_line = self._lines.popleft()
  291. def _SkipWhitespace(self):
  292. while True:
  293. self._PopLine()
  294. match = self._WHITESPACE.match(self._current_line, self._column)
  295. if not match:
  296. break
  297. length = len(match.group(0))
  298. self._column += length
  299. def TryConsume(self, token):
  300. """Tries to consume a given piece of text.
  301. Args:
  302. token: Text to consume.
  303. Returns:
  304. True iff the text was consumed.
  305. """
  306. if self.token == token:
  307. self.NextToken()
  308. return True
  309. return False
  310. def Consume(self, token):
  311. """Consumes a piece of text.
  312. Args:
  313. token: Text to consume.
  314. Raises:
  315. ParseError: If the text couldn't be consumed.
  316. """
  317. if not self.TryConsume(token):
  318. raise self._ParseError('Expected "%s".' % token)
  319. def ConsumeIdentifier(self):
  320. """Consumes protocol message field identifier.
  321. Returns:
  322. Identifier string.
  323. Raises:
  324. ParseError: If an identifier couldn't be consumed.
  325. """
  326. result = self.token
  327. if not self._IDENTIFIER.match(result):
  328. raise self._ParseError('Expected identifier.')
  329. self.NextToken()
  330. return result
  331. def ConsumeInt32(self):
  332. """Consumes a signed 32bit integer number.
  333. Returns:
  334. The integer parsed.
  335. Raises:
  336. ParseError: If a signed 32bit integer couldn't be consumed.
  337. """
  338. try:
  339. result = ParseInteger(self.token, is_signed=True, is_long=False)
  340. except ValueError, e:
  341. raise self._ParseError(str(e))
  342. self.NextToken()
  343. return result
  344. def ConsumeUint32(self):
  345. """Consumes an unsigned 32bit integer number.
  346. Returns:
  347. The integer parsed.
  348. Raises:
  349. ParseError: If an unsigned 32bit integer couldn't be consumed.
  350. """
  351. try:
  352. result = ParseInteger(self.token, is_signed=False, is_long=False)
  353. except ValueError, e:
  354. raise self._ParseError(str(e))
  355. self.NextToken()
  356. return result
  357. def ConsumeInt64(self):
  358. """Consumes a signed 64bit integer number.
  359. Returns:
  360. The integer parsed.
  361. Raises:
  362. ParseError: If a signed 64bit integer couldn't be consumed.
  363. """
  364. try:
  365. result = ParseInteger(self.token, is_signed=True, is_long=True)
  366. except ValueError, e:
  367. raise self._ParseError(str(e))
  368. self.NextToken()
  369. return result
  370. def ConsumeUint64(self):
  371. """Consumes an unsigned 64bit integer number.
  372. Returns:
  373. The integer parsed.
  374. Raises:
  375. ParseError: If an unsigned 64bit integer couldn't be consumed.
  376. """
  377. try:
  378. result = ParseInteger(self.token, is_signed=False, is_long=True)
  379. except ValueError, e:
  380. raise self._ParseError(str(e))
  381. self.NextToken()
  382. return result
  383. def ConsumeFloat(self):
  384. """Consumes an floating point number.
  385. Returns:
  386. The number parsed.
  387. Raises:
  388. ParseError: If a floating point number couldn't be consumed.
  389. """
  390. try:
  391. result = ParseFloat(self.token)
  392. except ValueError, e:
  393. raise self._ParseError(str(e))
  394. self.NextToken()
  395. return result
  396. def ConsumeBool(self):
  397. """Consumes a boolean value.
  398. Returns:
  399. The bool parsed.
  400. Raises:
  401. ParseError: If a boolean value couldn't be consumed.
  402. """
  403. try:
  404. result = ParseBool(self.token)
  405. except ValueError, e:
  406. raise self._ParseError(str(e))
  407. self.NextToken()
  408. return result
  409. def ConsumeString(self):
  410. """Consumes a string value.
  411. Returns:
  412. The string parsed.
  413. Raises:
  414. ParseError: If a string value couldn't be consumed.
  415. """
  416. bytes = self.ConsumeByteString()
  417. try:
  418. return unicode(bytes, 'utf-8')
  419. except UnicodeDecodeError, e:
  420. raise self._StringParseError(e)
  421. def ConsumeByteString(self):
  422. """Consumes a byte array value.
  423. Returns:
  424. The array parsed (as a string).
  425. Raises:
  426. ParseError: If a byte array value couldn't be consumed.
  427. """
  428. list = [self._ConsumeSingleByteString()]
  429. while len(self.token) > 0 and self.token[0] in ('\'', '"'):
  430. list.append(self._ConsumeSingleByteString())
  431. return "".join(list)
  432. def _ConsumeSingleByteString(self):
  433. """Consume one token of a string literal.
  434. String literals (whether bytes or text) can come in multiple adjacent
  435. tokens which are automatically concatenated, like in C or Python. This
  436. method only consumes one token.
  437. """
  438. text = self.token
  439. if len(text) < 1 or text[0] not in ('\'', '"'):
  440. raise self._ParseError('Expected string.')
  441. if len(text) < 2 or text[-1] != text[0]:
  442. raise self._ParseError('String missing ending quote.')
  443. try:
  444. result = _CUnescape(text[1:-1])
  445. except ValueError, e:
  446. raise self._ParseError(str(e))
  447. self.NextToken()
  448. return result
  449. def ConsumeEnum(self, field):
  450. try:
  451. result = ParseEnum(field, self.token)
  452. except ValueError, e:
  453. raise self._ParseError(str(e))
  454. self.NextToken()
  455. return result
  456. def ParseErrorPreviousToken(self, message):
  457. """Creates and *returns* a ParseError for the previously read token.
  458. Args:
  459. message: A message to set for the exception.
  460. Returns:
  461. A ParseError instance.
  462. """
  463. return ParseError('%d:%d : %s' % (
  464. self._previous_line + 1, self._previous_column + 1, message))
  465. def _ParseError(self, message):
  466. """Creates and *returns* a ParseError for the current token."""
  467. return ParseError('%d:%d : %s' % (
  468. self._line + 1, self._column + 1, message))
  469. def _StringParseError(self, e):
  470. return self._ParseError('Couldn\'t parse string: ' + str(e))
  471. def NextToken(self):
  472. """Reads the next meaningful token."""
  473. self._previous_line = self._line
  474. self._previous_column = self._column
  475. self._column += len(self.token)
  476. self._SkipWhitespace()
  477. if not self._lines and len(self._current_line) <= self._column:
  478. self.token = ''
  479. return
  480. match = self._TOKEN.match(self._current_line, self._column)
  481. if match:
  482. token = match.group(0)
  483. self.token = token
  484. else:
  485. self.token = self._current_line[self._column]
  486. # text.encode('string_escape') does not seem to satisfy our needs as it
  487. # encodes unprintable characters using two-digit hex escapes whereas our
  488. # C++ unescaping function allows hex escapes to be any length. So,
  489. # "\0011".encode('string_escape') ends up being "\\x011", which will be
  490. # decoded in C++ as a single-character string with char code 0x11.
  491. def _CEscape(text, as_utf8):
  492. def escape(c):
  493. o = ord(c)
  494. if o == 10: return r"\n" # optional escape
  495. if o == 13: return r"\r" # optional escape
  496. if o == 9: return r"\t" # optional escape
  497. if o == 39: return r"\'" # optional escape
  498. if o == 34: return r'\"' # necessary escape
  499. if o == 92: return r"\\" # necessary escape
  500. # necessary escapes
  501. if not as_utf8 and (o >= 127 or o < 32): return "\\%03o" % o
  502. return c
  503. return "".join([escape(c) for c in text])
  504. _CUNESCAPE_HEX = re.compile('\\\\x([0-9a-fA-F]{2}|[0-9a-fA-F])')
  505. def _CUnescape(text):
  506. def ReplaceHex(m):
  507. return chr(int(m.group(0)[2:], 16))
  508. # This is required because the 'string_escape' encoding doesn't
  509. # allow single-digit hex escapes (like '\xf').
  510. result = _CUNESCAPE_HEX.sub(ReplaceHex, text)
  511. return result.decode('string_escape')
  512. def ParseInteger(text, is_signed=False, is_long=False):
  513. """Parses an integer.
  514. Args:
  515. text: The text to parse.
  516. is_signed: True if a signed integer must be parsed.
  517. is_long: True if a long integer must be parsed.
  518. Returns:
  519. The integer value.
  520. Raises:
  521. ValueError: Thrown Iff the text is not a valid integer.
  522. """
  523. # Do the actual parsing. Exception handling is propagated to caller.
  524. try:
  525. result = int(text, 0)
  526. except ValueError:
  527. raise ValueError('Couldn\'t parse integer: %s' % text)
  528. # Check if the integer is sane. Exceptions handled by callers.
  529. checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
  530. checker.CheckValue(result)
  531. return result
  532. def ParseFloat(text):
  533. """Parse a floating point number.
  534. Args:
  535. text: Text to parse.
  536. Returns:
  537. The number parsed.
  538. Raises:
  539. ValueError: If a floating point number couldn't be parsed.
  540. """
  541. try:
  542. # Assume Python compatible syntax.
  543. return float(text)
  544. except ValueError:
  545. # Check alternative spellings.
  546. if _FLOAT_INFINITY.match(text):
  547. if text[0] == '-':
  548. return float('-inf')
  549. else:
  550. return float('inf')
  551. elif _FLOAT_NAN.match(text):
  552. return float('nan')
  553. else:
  554. # assume '1.0f' format
  555. try:
  556. return float(text.rstrip('f'))
  557. except ValueError:
  558. raise ValueError('Couldn\'t parse float: %s' % text)
  559. def ParseBool(text):
  560. """Parse a boolean value.
  561. Args:
  562. text: Text to parse.
  563. Returns:
  564. Boolean values parsed
  565. Raises:
  566. ValueError: If text is not a valid boolean.
  567. """
  568. if text in ('true', 't', '1'):
  569. return True
  570. elif text in ('false', 'f', '0'):
  571. return False
  572. else:
  573. raise ValueError('Expected "true" or "false".')
  574. def ParseEnum(field, value):
  575. """Parse an enum value.
  576. The value can be specified by a number (the enum value), or by
  577. a string literal (the enum name).
  578. Args:
  579. field: Enum field descriptor.
  580. value: String value.
  581. Returns:
  582. Enum value number.
  583. Raises:
  584. ValueError: If the enum value could not be parsed.
  585. """
  586. enum_descriptor = field.enum_type
  587. try:
  588. number = int(value, 0)
  589. except ValueError:
  590. # Identifier.
  591. enum_value = enum_descriptor.values_by_name.get(value, None)
  592. if enum_value is None:
  593. raise ValueError(
  594. 'Enum type "%s" has no value named %s.' % (
  595. enum_descriptor.full_name, value))
  596. else:
  597. # Numeric value.
  598. enum_value = enum_descriptor.values_by_number.get(number, None)
  599. if enum_value is None:
  600. raise ValueError(
  601. 'Enum type "%s" has no value with number %d.' % (
  602. enum_descriptor.full_name, number))
  603. return enum_value.number