text_format.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # https://developers.google.com/protocol-buffers/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Contains routines for printing protocol messages in text format.
  31. Simple usage example:
  32. # Create a proto object and serialize it to a text proto string.
  33. message = my_proto_pb2.MyMessage(foo='bar')
  34. text_proto = text_format.MessageToString(message)
  35. # Parse a text proto string.
  36. message = text_format.Parse(text_proto, my_proto_pb2.MyMessage())
  37. """
  38. __author__ = 'kenton@google.com (Kenton Varda)'
  39. import io
  40. import re
  41. import six
  42. if six.PY3:
  43. long = int # pylint: disable=redefined-builtin,invalid-name
  44. # pylint: disable=g-import-not-at-top
  45. from google.protobuf.internal import type_checkers
  46. from google.protobuf import descriptor
  47. from google.protobuf import text_encoding
  48. __all__ = ['MessageToString', 'PrintMessage', 'PrintField', 'PrintFieldValue',
  49. 'Merge']
  50. _INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(),
  51. type_checkers.Int32ValueChecker(),
  52. type_checkers.Uint64ValueChecker(),
  53. type_checkers.Int64ValueChecker())
  54. _FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?', re.IGNORECASE)
  55. _FLOAT_NAN = re.compile('nanf?', re.IGNORECASE)
  56. _FLOAT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_FLOAT,
  57. descriptor.FieldDescriptor.CPPTYPE_DOUBLE])
  58. _QUOTES = frozenset(("'", '"'))
  59. _ANY_FULL_TYPE_NAME = 'google.protobuf.Any'
  60. class Error(Exception):
  61. """Top-level module error for text_format."""
  62. class ParseError(Error):
  63. """Thrown in case of text parsing or tokenizing error."""
  64. def __init__(self, message=None, line=None, column=None):
  65. if message is not None and line is not None:
  66. loc = str(line)
  67. if column is not None:
  68. loc += ':{0}'.format(column)
  69. message = '{0} : {1}'.format(loc, message)
  70. if message is not None:
  71. super(ParseError, self).__init__(message)
  72. else:
  73. super(ParseError, self).__init__()
  74. self._line = line
  75. self._column = column
  76. def GetLine(self):
  77. return self._line
  78. def GetColumn(self):
  79. return self._column
  80. class TextWriter(object):
  81. def __init__(self, as_utf8):
  82. if six.PY2:
  83. self._writer = io.BytesIO()
  84. else:
  85. self._writer = io.StringIO()
  86. def write(self, val):
  87. if six.PY2:
  88. if isinstance(val, six.text_type):
  89. val = val.encode('utf-8')
  90. return self._writer.write(val)
  91. def close(self):
  92. return self._writer.close()
  93. def getvalue(self):
  94. return self._writer.getvalue()
  95. def MessageToString(message,
  96. as_utf8=False,
  97. as_one_line=False,
  98. pointy_brackets=False,
  99. use_index_order=False,
  100. float_format=None,
  101. use_field_number=False,
  102. descriptor_pool=None,
  103. indent=0):
  104. """Convert protobuf message to text format.
  105. Floating point values can be formatted compactly with 15 digits of
  106. precision (which is the most that IEEE 754 "double" can guarantee)
  107. using float_format='.15g'. To ensure that converting to text and back to a
  108. proto will result in an identical value, float_format='.17g' should be used.
  109. Args:
  110. message: The protocol buffers message.
  111. as_utf8: Produce text output in UTF8 format.
  112. as_one_line: Don't introduce newlines between fields.
  113. pointy_brackets: If True, use angle brackets instead of curly braces for
  114. nesting.
  115. use_index_order: If True, print fields of a proto message using the order
  116. defined in source code instead of the field number. By default, use the
  117. field number order.
  118. float_format: If set, use this to specify floating point number formatting
  119. (per the "Format Specification Mini-Language"); otherwise, str() is used.
  120. use_field_number: If True, print field numbers instead of names.
  121. descriptor_pool: A DescriptorPool used to resolve Any types.
  122. indent: The indent level, in terms of spaces, for pretty print.
  123. Returns:
  124. A string of the text formatted protocol buffer message.
  125. """
  126. out = TextWriter(as_utf8)
  127. printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
  128. use_index_order, float_format, use_field_number,
  129. descriptor_pool)
  130. printer.PrintMessage(message)
  131. result = out.getvalue()
  132. out.close()
  133. if as_one_line:
  134. return result.rstrip()
  135. return result
  136. def _IsMapEntry(field):
  137. return (field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  138. field.message_type.has_options and
  139. field.message_type.GetOptions().map_entry)
  140. def PrintMessage(message,
  141. out,
  142. indent=0,
  143. as_utf8=False,
  144. as_one_line=False,
  145. pointy_brackets=False,
  146. use_index_order=False,
  147. float_format=None,
  148. use_field_number=False,
  149. descriptor_pool=None):
  150. printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
  151. use_index_order, float_format, use_field_number,
  152. descriptor_pool)
  153. printer.PrintMessage(message)
  154. def PrintField(field,
  155. value,
  156. out,
  157. indent=0,
  158. as_utf8=False,
  159. as_one_line=False,
  160. pointy_brackets=False,
  161. use_index_order=False,
  162. float_format=None):
  163. """Print a single field name/value pair."""
  164. printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
  165. use_index_order, float_format)
  166. printer.PrintField(field, value)
  167. def PrintFieldValue(field,
  168. value,
  169. out,
  170. indent=0,
  171. as_utf8=False,
  172. as_one_line=False,
  173. pointy_brackets=False,
  174. use_index_order=False,
  175. float_format=None):
  176. """Print a single field value (not including name)."""
  177. printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
  178. use_index_order, float_format)
  179. printer.PrintFieldValue(field, value)
  180. def _BuildMessageFromTypeName(type_name, descriptor_pool):
  181. """Returns a protobuf message instance.
  182. Args:
  183. type_name: Fully-qualified protobuf message type name string.
  184. descriptor_pool: DescriptorPool instance.
  185. Returns:
  186. A Message instance of type matching type_name, or None if the a Descriptor
  187. wasn't found matching type_name.
  188. """
  189. # pylint: disable=g-import-not-at-top
  190. from google.protobuf import message_factory
  191. factory = message_factory.MessageFactory(descriptor_pool)
  192. try:
  193. message_descriptor = descriptor_pool.FindMessageTypeByName(type_name)
  194. except KeyError:
  195. return None
  196. message_type = factory.GetPrototype(message_descriptor)
  197. return message_type()
  198. class _Printer(object):
  199. """Text format printer for protocol message."""
  200. def __init__(self,
  201. out,
  202. indent=0,
  203. as_utf8=False,
  204. as_one_line=False,
  205. pointy_brackets=False,
  206. use_index_order=False,
  207. float_format=None,
  208. use_field_number=False,
  209. descriptor_pool=None):
  210. """Initialize the Printer.
  211. Floating point values can be formatted compactly with 15 digits of
  212. precision (which is the most that IEEE 754 "double" can guarantee)
  213. using float_format='.15g'. To ensure that converting to text and back to a
  214. proto will result in an identical value, float_format='.17g' should be used.
  215. Args:
  216. out: To record the text format result.
  217. indent: The indent level for pretty print.
  218. as_utf8: Produce text output in UTF8 format.
  219. as_one_line: Don't introduce newlines between fields.
  220. pointy_brackets: If True, use angle brackets instead of curly braces for
  221. nesting.
  222. use_index_order: If True, print fields of a proto message using the order
  223. defined in source code instead of the field number. By default, use the
  224. field number order.
  225. float_format: If set, use this to specify floating point number formatting
  226. (per the "Format Specification Mini-Language"); otherwise, str() is
  227. used.
  228. use_field_number: If True, print field numbers instead of names.
  229. descriptor_pool: A DescriptorPool used to resolve Any types.
  230. """
  231. self.out = out
  232. self.indent = indent
  233. self.as_utf8 = as_utf8
  234. self.as_one_line = as_one_line
  235. self.pointy_brackets = pointy_brackets
  236. self.use_index_order = use_index_order
  237. self.float_format = float_format
  238. self.use_field_number = use_field_number
  239. self.descriptor_pool = descriptor_pool
  240. def _TryPrintAsAnyMessage(self, message):
  241. """Serializes if message is a google.protobuf.Any field."""
  242. packed_message = _BuildMessageFromTypeName(message.TypeName(),
  243. self.descriptor_pool)
  244. if packed_message:
  245. packed_message.MergeFromString(message.value)
  246. self.out.write('%s[%s]' % (self.indent * ' ', message.type_url))
  247. self._PrintMessageFieldValue(packed_message)
  248. self.out.write(' ' if self.as_one_line else '\n')
  249. return True
  250. else:
  251. return False
  252. def PrintMessage(self, message):
  253. """Convert protobuf message to text format.
  254. Args:
  255. message: The protocol buffers message.
  256. """
  257. if (message.DESCRIPTOR.full_name == _ANY_FULL_TYPE_NAME and
  258. self.descriptor_pool and self._TryPrintAsAnyMessage(message)):
  259. return
  260. fields = message.ListFields()
  261. if self.use_index_order:
  262. fields.sort(key=lambda x: x[0].index)
  263. for field, value in fields:
  264. if _IsMapEntry(field):
  265. for key in sorted(value):
  266. # This is slow for maps with submessage entires because it copies the
  267. # entire tree. Unfortunately this would take significant refactoring
  268. # of this file to work around.
  269. #
  270. # TODO(haberman): refactor and optimize if this becomes an issue.
  271. entry_submsg = field.message_type._concrete_class(key=key,
  272. value=value[key])
  273. self.PrintField(field, entry_submsg)
  274. elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  275. for element in value:
  276. self.PrintField(field, element)
  277. else:
  278. self.PrintField(field, value)
  279. def PrintField(self, field, value):
  280. """Print a single field name/value pair."""
  281. out = self.out
  282. out.write(' ' * self.indent)
  283. if self.use_field_number:
  284. out.write(str(field.number))
  285. else:
  286. if field.is_extension:
  287. out.write('[')
  288. if (field.containing_type.GetOptions().message_set_wire_format and
  289. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  290. field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL):
  291. out.write(field.message_type.full_name)
  292. else:
  293. out.write(field.full_name)
  294. out.write(']')
  295. elif field.type == descriptor.FieldDescriptor.TYPE_GROUP:
  296. # For groups, use the capitalized name.
  297. out.write(field.message_type.name)
  298. else:
  299. out.write(field.name)
  300. if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  301. # The colon is optional in this case, but our cross-language golden files
  302. # don't include it.
  303. out.write(': ')
  304. self.PrintFieldValue(field, value)
  305. if self.as_one_line:
  306. out.write(' ')
  307. else:
  308. out.write('\n')
  309. def _PrintMessageFieldValue(self, value):
  310. if self.pointy_brackets:
  311. openb = '<'
  312. closeb = '>'
  313. else:
  314. openb = '{'
  315. closeb = '}'
  316. if self.as_one_line:
  317. self.out.write(' %s ' % openb)
  318. self.PrintMessage(value)
  319. self.out.write(closeb)
  320. else:
  321. self.out.write(' %s\n' % openb)
  322. self.indent += 2
  323. self.PrintMessage(value)
  324. self.indent -= 2
  325. self.out.write(' ' * self.indent + closeb)
  326. def PrintFieldValue(self, field, value):
  327. """Print a single field value (not including name).
  328. For repeated fields, the value should be a single element.
  329. Args:
  330. field: The descriptor of the field to be printed.
  331. value: The value of the field.
  332. """
  333. out = self.out
  334. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  335. self._PrintMessageFieldValue(value)
  336. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
  337. enum_value = field.enum_type.values_by_number.get(value, None)
  338. if enum_value is not None:
  339. out.write(enum_value.name)
  340. else:
  341. out.write(str(value))
  342. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
  343. out.write('\"')
  344. if isinstance(value, six.text_type):
  345. out_value = value.encode('utf-8')
  346. else:
  347. out_value = value
  348. if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  349. # We need to escape non-UTF8 chars in TYPE_BYTES field.
  350. out_as_utf8 = False
  351. else:
  352. out_as_utf8 = self.as_utf8
  353. out.write(text_encoding.CEscape(out_value, out_as_utf8))
  354. out.write('\"')
  355. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
  356. if value:
  357. out.write('true')
  358. else:
  359. out.write('false')
  360. elif field.cpp_type in _FLOAT_TYPES and self.float_format is not None:
  361. out.write('{1:{0}}'.format(self.float_format, value))
  362. else:
  363. out.write(str(value))
  364. def Parse(text,
  365. message,
  366. allow_unknown_extension=False,
  367. allow_field_number=False):
  368. """Parses a text representation of a protocol message into a message.
  369. Args:
  370. text: Message text representation.
  371. message: A protocol buffer message to merge into.
  372. allow_unknown_extension: if True, skip over missing extensions and keep
  373. parsing
  374. allow_field_number: if True, both field number and field name are allowed.
  375. Returns:
  376. The same message passed as argument.
  377. Raises:
  378. ParseError: On text parsing problems.
  379. """
  380. if not isinstance(text, str):
  381. text = text.decode('utf-8')
  382. return ParseLines(
  383. text.split('\n'), message, allow_unknown_extension, allow_field_number)
  384. def Merge(text,
  385. message,
  386. allow_unknown_extension=False,
  387. allow_field_number=False,
  388. descriptor_pool=None):
  389. """Parses a text representation of a protocol message into a message.
  390. Like Parse(), but allows repeated values for a non-repeated field, and uses
  391. the last one.
  392. Args:
  393. text: Message text representation.
  394. message: A protocol buffer message to merge into.
  395. allow_unknown_extension: if True, skip over missing extensions and keep
  396. parsing
  397. allow_field_number: if True, both field number and field name are allowed.
  398. descriptor_pool: A DescriptorPool used to resolve Any types.
  399. Returns:
  400. The same message passed as argument.
  401. Raises:
  402. ParseError: On text parsing problems.
  403. """
  404. return MergeLines(
  405. text.split('\n'),
  406. message,
  407. allow_unknown_extension,
  408. allow_field_number,
  409. descriptor_pool=descriptor_pool)
  410. def ParseLines(lines,
  411. message,
  412. allow_unknown_extension=False,
  413. allow_field_number=False):
  414. """Parses a text representation of a protocol message into a message.
  415. Args:
  416. lines: An iterable of lines of a message's text representation.
  417. message: A protocol buffer message to merge into.
  418. allow_unknown_extension: if True, skip over missing extensions and keep
  419. parsing
  420. allow_field_number: if True, both field number and field name are allowed.
  421. descriptor_pool: A DescriptorPool used to resolve Any types.
  422. Returns:
  423. The same message passed as argument.
  424. Raises:
  425. ParseError: On text parsing problems.
  426. """
  427. parser = _Parser(allow_unknown_extension, allow_field_number)
  428. return parser.ParseLines(lines, message)
  429. def MergeLines(lines,
  430. message,
  431. allow_unknown_extension=False,
  432. allow_field_number=False,
  433. descriptor_pool=None):
  434. """Parses a text representation of a protocol message into a message.
  435. Args:
  436. lines: An iterable of lines of a message's text representation.
  437. message: A protocol buffer message to merge into.
  438. allow_unknown_extension: if True, skip over missing extensions and keep
  439. parsing
  440. allow_field_number: if True, both field number and field name are allowed.
  441. Returns:
  442. The same message passed as argument.
  443. Raises:
  444. ParseError: On text parsing problems.
  445. """
  446. parser = _Parser(allow_unknown_extension,
  447. allow_field_number,
  448. descriptor_pool=descriptor_pool)
  449. return parser.MergeLines(lines, message)
  450. class _Parser(object):
  451. """Text format parser for protocol message."""
  452. def __init__(self,
  453. allow_unknown_extension=False,
  454. allow_field_number=False,
  455. descriptor_pool=None):
  456. self.allow_unknown_extension = allow_unknown_extension
  457. self.allow_field_number = allow_field_number
  458. self.descriptor_pool = descriptor_pool
  459. def ParseFromString(self, text, message):
  460. """Parses a text representation of a protocol message into a message."""
  461. if not isinstance(text, str):
  462. text = text.decode('utf-8')
  463. return self.ParseLines(text.split('\n'), message)
  464. def ParseLines(self, lines, message):
  465. """Parses a text representation of a protocol message into a message."""
  466. self._allow_multiple_scalars = False
  467. self._ParseOrMerge(lines, message)
  468. return message
  469. def MergeFromString(self, text, message):
  470. """Merges a text representation of a protocol message into a message."""
  471. return self._MergeLines(text.split('\n'), message)
  472. def MergeLines(self, lines, message):
  473. """Merges a text representation of a protocol message into a message."""
  474. self._allow_multiple_scalars = True
  475. self._ParseOrMerge(lines, message)
  476. return message
  477. def _ParseOrMerge(self, lines, message):
  478. """Converts a text representation of a protocol message into a message.
  479. Args:
  480. lines: Lines of a message's text representation.
  481. message: A protocol buffer message to merge into.
  482. Raises:
  483. ParseError: On text parsing problems.
  484. """
  485. tokenizer = Tokenizer(lines)
  486. while not tokenizer.AtEnd():
  487. self._MergeField(tokenizer, message)
  488. def _MergeField(self, tokenizer, message):
  489. """Merges a single protocol message field into a message.
  490. Args:
  491. tokenizer: A tokenizer to parse the field name and values.
  492. message: A protocol message to record the data.
  493. Raises:
  494. ParseError: In case of text parsing problems.
  495. """
  496. message_descriptor = message.DESCRIPTOR
  497. if (hasattr(message_descriptor, 'syntax') and
  498. message_descriptor.syntax == 'proto3'):
  499. # Proto3 doesn't represent presence so we can't test if multiple
  500. # scalars have occurred. We have to allow them.
  501. self._allow_multiple_scalars = True
  502. if tokenizer.TryConsume('['):
  503. name = [tokenizer.ConsumeIdentifier()]
  504. while tokenizer.TryConsume('.'):
  505. name.append(tokenizer.ConsumeIdentifier())
  506. name = '.'.join(name)
  507. if not message_descriptor.is_extendable:
  508. raise tokenizer.ParseErrorPreviousToken(
  509. 'Message type "%s" does not have extensions.' %
  510. message_descriptor.full_name)
  511. # pylint: disable=protected-access
  512. field = message.Extensions._FindExtensionByName(name)
  513. # pylint: enable=protected-access
  514. if not field:
  515. if self.allow_unknown_extension:
  516. field = None
  517. else:
  518. raise tokenizer.ParseErrorPreviousToken(
  519. 'Extension "%s" not registered.' % name)
  520. elif message_descriptor != field.containing_type:
  521. raise tokenizer.ParseErrorPreviousToken(
  522. 'Extension "%s" does not extend message type "%s".' %
  523. (name, message_descriptor.full_name))
  524. tokenizer.Consume(']')
  525. else:
  526. name = tokenizer.ConsumeIdentifierOrNumber()
  527. if self.allow_field_number and name.isdigit():
  528. number = ParseInteger(name, True, True)
  529. field = message_descriptor.fields_by_number.get(number, None)
  530. if not field and message_descriptor.is_extendable:
  531. field = message.Extensions._FindExtensionByNumber(number)
  532. else:
  533. field = message_descriptor.fields_by_name.get(name, None)
  534. # Group names are expected to be capitalized as they appear in the
  535. # .proto file, which actually matches their type names, not their field
  536. # names.
  537. if not field:
  538. field = message_descriptor.fields_by_name.get(name.lower(), None)
  539. if field and field.type != descriptor.FieldDescriptor.TYPE_GROUP:
  540. field = None
  541. if (field and field.type == descriptor.FieldDescriptor.TYPE_GROUP and
  542. field.message_type.name != name):
  543. field = None
  544. if not field:
  545. raise tokenizer.ParseErrorPreviousToken(
  546. 'Message type "%s" has no field named "%s".' %
  547. (message_descriptor.full_name, name))
  548. if field:
  549. if not self._allow_multiple_scalars and field.containing_oneof:
  550. # Check if there's a different field set in this oneof.
  551. # Note that we ignore the case if the same field was set before, and we
  552. # apply _allow_multiple_scalars to non-scalar fields as well.
  553. which_oneof = message.WhichOneof(field.containing_oneof.name)
  554. if which_oneof is not None and which_oneof != field.name:
  555. raise tokenizer.ParseErrorPreviousToken(
  556. 'Field "%s" is specified along with field "%s", another member '
  557. 'of oneof "%s" for message type "%s".' %
  558. (field.name, which_oneof, field.containing_oneof.name,
  559. message_descriptor.full_name))
  560. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  561. tokenizer.TryConsume(':')
  562. merger = self._MergeMessageField
  563. else:
  564. tokenizer.Consume(':')
  565. merger = self._MergeScalarField
  566. if (field.label == descriptor.FieldDescriptor.LABEL_REPEATED and
  567. tokenizer.TryConsume('[')):
  568. # Short repeated format, e.g. "foo: [1, 2, 3]"
  569. while True:
  570. merger(tokenizer, message, field)
  571. if tokenizer.TryConsume(']'):
  572. break
  573. tokenizer.Consume(',')
  574. else:
  575. merger(tokenizer, message, field)
  576. else: # Proto field is unknown.
  577. assert self.allow_unknown_extension
  578. _SkipFieldContents(tokenizer)
  579. # For historical reasons, fields may optionally be separated by commas or
  580. # semicolons.
  581. if not tokenizer.TryConsume(','):
  582. tokenizer.TryConsume(';')
  583. def _ConsumeAnyTypeUrl(self, tokenizer):
  584. """Consumes a google.protobuf.Any type URL and returns the type name."""
  585. # Consume "type.googleapis.com/".
  586. tokenizer.ConsumeIdentifier()
  587. tokenizer.Consume('.')
  588. tokenizer.ConsumeIdentifier()
  589. tokenizer.Consume('.')
  590. tokenizer.ConsumeIdentifier()
  591. tokenizer.Consume('/')
  592. # Consume the fully-qualified type name.
  593. name = [tokenizer.ConsumeIdentifier()]
  594. while tokenizer.TryConsume('.'):
  595. name.append(tokenizer.ConsumeIdentifier())
  596. return '.'.join(name)
  597. def _MergeMessageField(self, tokenizer, message, field):
  598. """Merges a single scalar field into a message.
  599. Args:
  600. tokenizer: A tokenizer to parse the field value.
  601. message: The message of which field is a member.
  602. field: The descriptor of the field to be merged.
  603. Raises:
  604. ParseError: In case of text parsing problems.
  605. """
  606. is_map_entry = _IsMapEntry(field)
  607. if tokenizer.TryConsume('<'):
  608. end_token = '>'
  609. else:
  610. tokenizer.Consume('{')
  611. end_token = '}'
  612. if (field.message_type.full_name == _ANY_FULL_TYPE_NAME and
  613. tokenizer.TryConsume('[')):
  614. packed_type_name = self._ConsumeAnyTypeUrl(tokenizer)
  615. tokenizer.Consume(']')
  616. tokenizer.TryConsume(':')
  617. if tokenizer.TryConsume('<'):
  618. expanded_any_end_token = '>'
  619. else:
  620. tokenizer.Consume('{')
  621. expanded_any_end_token = '}'
  622. if not self.descriptor_pool:
  623. raise ParseError('Descriptor pool required to parse expanded Any field')
  624. expanded_any_sub_message = _BuildMessageFromTypeName(packed_type_name,
  625. self.descriptor_pool)
  626. if not expanded_any_sub_message:
  627. raise ParseError('Type %s not found in descriptor pool' %
  628. packed_type_name)
  629. while not tokenizer.TryConsume(expanded_any_end_token):
  630. if tokenizer.AtEnd():
  631. raise tokenizer.ParseErrorPreviousToken('Expected "%s".' %
  632. (expanded_any_end_token,))
  633. self._MergeField(tokenizer, expanded_any_sub_message)
  634. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  635. any_message = getattr(message, field.name).add()
  636. else:
  637. any_message = getattr(message, field.name)
  638. any_message.Pack(expanded_any_sub_message)
  639. elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  640. if field.is_extension:
  641. sub_message = message.Extensions[field].add()
  642. elif is_map_entry:
  643. # pylint: disable=protected-access
  644. sub_message = field.message_type._concrete_class()
  645. else:
  646. sub_message = getattr(message, field.name).add()
  647. else:
  648. if field.is_extension:
  649. sub_message = message.Extensions[field]
  650. else:
  651. sub_message = getattr(message, field.name)
  652. sub_message.SetInParent()
  653. while not tokenizer.TryConsume(end_token):
  654. if tokenizer.AtEnd():
  655. raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token,))
  656. self._MergeField(tokenizer, sub_message)
  657. if is_map_entry:
  658. value_cpptype = field.message_type.fields_by_name['value'].cpp_type
  659. if value_cpptype == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  660. value = getattr(message, field.name)[sub_message.key]
  661. value.MergeFrom(sub_message.value)
  662. else:
  663. getattr(message, field.name)[sub_message.key] = sub_message.value
  664. def _MergeScalarField(self, tokenizer, message, field):
  665. """Merges a single scalar field into a message.
  666. Args:
  667. tokenizer: A tokenizer to parse the field value.
  668. message: A protocol message to record the data.
  669. field: The descriptor of the field to be merged.
  670. Raises:
  671. ParseError: In case of text parsing problems.
  672. RuntimeError: On runtime errors.
  673. """
  674. _ = self.allow_unknown_extension
  675. value = None
  676. if field.type in (descriptor.FieldDescriptor.TYPE_INT32,
  677. descriptor.FieldDescriptor.TYPE_SINT32,
  678. descriptor.FieldDescriptor.TYPE_SFIXED32):
  679. value = _ConsumeInt32(tokenizer)
  680. elif field.type in (descriptor.FieldDescriptor.TYPE_INT64,
  681. descriptor.FieldDescriptor.TYPE_SINT64,
  682. descriptor.FieldDescriptor.TYPE_SFIXED64):
  683. value = _ConsumeInt64(tokenizer)
  684. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32,
  685. descriptor.FieldDescriptor.TYPE_FIXED32):
  686. value = _ConsumeUint32(tokenizer)
  687. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64,
  688. descriptor.FieldDescriptor.TYPE_FIXED64):
  689. value = _ConsumeUint64(tokenizer)
  690. elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT,
  691. descriptor.FieldDescriptor.TYPE_DOUBLE):
  692. value = tokenizer.ConsumeFloat()
  693. elif field.type == descriptor.FieldDescriptor.TYPE_BOOL:
  694. value = tokenizer.ConsumeBool()
  695. elif field.type == descriptor.FieldDescriptor.TYPE_STRING:
  696. value = tokenizer.ConsumeString()
  697. elif field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  698. value = tokenizer.ConsumeByteString()
  699. elif field.type == descriptor.FieldDescriptor.TYPE_ENUM:
  700. value = tokenizer.ConsumeEnum(field)
  701. else:
  702. raise RuntimeError('Unknown field type %d' % field.type)
  703. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  704. if field.is_extension:
  705. message.Extensions[field].append(value)
  706. else:
  707. getattr(message, field.name).append(value)
  708. else:
  709. if field.is_extension:
  710. if not self._allow_multiple_scalars and message.HasExtension(field):
  711. raise tokenizer.ParseErrorPreviousToken(
  712. 'Message type "%s" should not have multiple "%s" extensions.' %
  713. (message.DESCRIPTOR.full_name, field.full_name))
  714. else:
  715. message.Extensions[field] = value
  716. else:
  717. if not self._allow_multiple_scalars and message.HasField(field.name):
  718. raise tokenizer.ParseErrorPreviousToken(
  719. 'Message type "%s" should not have multiple "%s" fields.' %
  720. (message.DESCRIPTOR.full_name, field.name))
  721. else:
  722. setattr(message, field.name, value)
  723. def _SkipFieldContents(tokenizer):
  724. """Skips over contents (value or message) of a field.
  725. Args:
  726. tokenizer: A tokenizer to parse the field name and values.
  727. """
  728. # Try to guess the type of this field.
  729. # If this field is not a message, there should be a ":" between the
  730. # field name and the field value and also the field value should not
  731. # start with "{" or "<" which indicates the beginning of a message body.
  732. # If there is no ":" or there is a "{" or "<" after ":", this field has
  733. # to be a message or the input is ill-formed.
  734. if tokenizer.TryConsume(':') and not tokenizer.LookingAt(
  735. '{') and not tokenizer.LookingAt('<'):
  736. _SkipFieldValue(tokenizer)
  737. else:
  738. _SkipFieldMessage(tokenizer)
  739. def _SkipField(tokenizer):
  740. """Skips over a complete field (name and value/message).
  741. Args:
  742. tokenizer: A tokenizer to parse the field name and values.
  743. """
  744. if tokenizer.TryConsume('['):
  745. # Consume extension name.
  746. tokenizer.ConsumeIdentifier()
  747. while tokenizer.TryConsume('.'):
  748. tokenizer.ConsumeIdentifier()
  749. tokenizer.Consume(']')
  750. else:
  751. tokenizer.ConsumeIdentifier()
  752. _SkipFieldContents(tokenizer)
  753. # For historical reasons, fields may optionally be separated by commas or
  754. # semicolons.
  755. if not tokenizer.TryConsume(','):
  756. tokenizer.TryConsume(';')
  757. def _SkipFieldMessage(tokenizer):
  758. """Skips over a field message.
  759. Args:
  760. tokenizer: A tokenizer to parse the field name and values.
  761. """
  762. if tokenizer.TryConsume('<'):
  763. delimiter = '>'
  764. else:
  765. tokenizer.Consume('{')
  766. delimiter = '}'
  767. while not tokenizer.LookingAt('>') and not tokenizer.LookingAt('}'):
  768. _SkipField(tokenizer)
  769. tokenizer.Consume(delimiter)
  770. def _SkipFieldValue(tokenizer):
  771. """Skips over a field value.
  772. Args:
  773. tokenizer: A tokenizer to parse the field name and values.
  774. Raises:
  775. ParseError: In case an invalid field value is found.
  776. """
  777. # String/bytes tokens can come in multiple adjacent string literals.
  778. # If we can consume one, consume as many as we can.
  779. if tokenizer.TryConsumeByteString():
  780. while tokenizer.TryConsumeByteString():
  781. pass
  782. return
  783. if (not tokenizer.TryConsumeIdentifier() and
  784. not _TryConsumeInt64(tokenizer) and not _TryConsumeUint64(tokenizer) and
  785. not tokenizer.TryConsumeFloat()):
  786. raise ParseError('Invalid field value: ' + tokenizer.token)
  787. class Tokenizer(object):
  788. """Protocol buffer text representation tokenizer.
  789. This class handles the lower level string parsing by splitting it into
  790. meaningful tokens.
  791. It was directly ported from the Java protocol buffer API.
  792. """
  793. _WHITESPACE = re.compile(r'\s+')
  794. _COMMENT = re.compile(r'(\s*#.*$)', re.MULTILINE)
  795. _WHITESPACE_OR_COMMENT = re.compile(r'(\s|(#.*$))+', re.MULTILINE)
  796. _TOKEN = re.compile('|'.join([
  797. r'[a-zA-Z_][0-9a-zA-Z_+-]*', # an identifier
  798. r'([0-9+-]|(\.[0-9]))[0-9a-zA-Z_.+-]*', # a number
  799. ] + [ # quoted str for each quote mark
  800. r'{qt}([^{qt}\n\\]|\\.)*({qt}|\\?$)'.format(qt=mark) for mark in _QUOTES
  801. ]))
  802. _IDENTIFIER = re.compile(r'[^\d\W]\w*')
  803. _IDENTIFIER_OR_NUMBER = re.compile(r'\w+')
  804. def __init__(self, lines, skip_comments=True):
  805. self._position = 0
  806. self._line = -1
  807. self._column = 0
  808. self._token_start = None
  809. self.token = ''
  810. self._lines = iter(lines)
  811. self._current_line = ''
  812. self._previous_line = 0
  813. self._previous_column = 0
  814. self._more_lines = True
  815. self._skip_comments = skip_comments
  816. self._whitespace_pattern = (skip_comments and self._WHITESPACE_OR_COMMENT
  817. or self._WHITESPACE)
  818. self._SkipWhitespace()
  819. self.NextToken()
  820. def LookingAt(self, token):
  821. return self.token == token
  822. def AtEnd(self):
  823. """Checks the end of the text was reached.
  824. Returns:
  825. True iff the end was reached.
  826. """
  827. return not self.token
  828. def _PopLine(self):
  829. while len(self._current_line) <= self._column:
  830. try:
  831. self._current_line = next(self._lines)
  832. except StopIteration:
  833. self._current_line = ''
  834. self._more_lines = False
  835. return
  836. else:
  837. self._line += 1
  838. self._column = 0
  839. def _SkipWhitespace(self):
  840. while True:
  841. self._PopLine()
  842. match = self._whitespace_pattern.match(self._current_line, self._column)
  843. if not match:
  844. break
  845. length = len(match.group(0))
  846. self._column += length
  847. def TryConsume(self, token):
  848. """Tries to consume a given piece of text.
  849. Args:
  850. token: Text to consume.
  851. Returns:
  852. True iff the text was consumed.
  853. """
  854. if self.token == token:
  855. self.NextToken()
  856. return True
  857. return False
  858. def Consume(self, token):
  859. """Consumes a piece of text.
  860. Args:
  861. token: Text to consume.
  862. Raises:
  863. ParseError: If the text couldn't be consumed.
  864. """
  865. if not self.TryConsume(token):
  866. raise self.ParseError('Expected "%s".' % token)
  867. def ConsumeComment(self):
  868. result = self.token
  869. if not self._COMMENT.match(result):
  870. raise self.ParseError('Expected comment.')
  871. self.NextToken()
  872. return result
  873. def TryConsumeIdentifier(self):
  874. try:
  875. self.ConsumeIdentifier()
  876. return True
  877. except ParseError:
  878. return False
  879. def ConsumeIdentifier(self):
  880. """Consumes protocol message field identifier.
  881. Returns:
  882. Identifier string.
  883. Raises:
  884. ParseError: If an identifier couldn't be consumed.
  885. """
  886. result = self.token
  887. if not self._IDENTIFIER.match(result):
  888. raise self.ParseError('Expected identifier.')
  889. self.NextToken()
  890. return result
  891. def TryConsumeIdentifierOrNumber(self):
  892. try:
  893. self.ConsumeIdentifierOrNumber()
  894. return True
  895. except ParseError:
  896. return False
  897. def ConsumeIdentifierOrNumber(self):
  898. """Consumes protocol message field identifier.
  899. Returns:
  900. Identifier string.
  901. Raises:
  902. ParseError: If an identifier couldn't be consumed.
  903. """
  904. result = self.token
  905. if not self._IDENTIFIER_OR_NUMBER.match(result):
  906. raise self.ParseError('Expected identifier or number.')
  907. self.NextToken()
  908. return result
  909. def TryConsumeInteger(self):
  910. try:
  911. # Note: is_long only affects value type, not whether an error is raised.
  912. self.ConsumeInteger()
  913. return True
  914. except ParseError:
  915. return False
  916. def ConsumeInteger(self, is_long=False):
  917. """Consumes an integer number.
  918. Args:
  919. is_long: True if the value should be returned as a long integer.
  920. Returns:
  921. The integer parsed.
  922. Raises:
  923. ParseError: If an integer couldn't be consumed.
  924. """
  925. try:
  926. result = _ParseAbstractInteger(self.token, is_long=is_long)
  927. except ValueError as e:
  928. raise self.ParseError(str(e))
  929. self.NextToken()
  930. return result
  931. def TryConsumeFloat(self):
  932. try:
  933. self.ConsumeFloat()
  934. return True
  935. except ParseError:
  936. return False
  937. def ConsumeFloat(self):
  938. """Consumes an floating point number.
  939. Returns:
  940. The number parsed.
  941. Raises:
  942. ParseError: If a floating point number couldn't be consumed.
  943. """
  944. try:
  945. result = ParseFloat(self.token)
  946. except ValueError as e:
  947. raise self.ParseError(str(e))
  948. self.NextToken()
  949. return result
  950. def ConsumeBool(self):
  951. """Consumes a boolean value.
  952. Returns:
  953. The bool parsed.
  954. Raises:
  955. ParseError: If a boolean value couldn't be consumed.
  956. """
  957. try:
  958. result = ParseBool(self.token)
  959. except ValueError as e:
  960. raise self.ParseError(str(e))
  961. self.NextToken()
  962. return result
  963. def TryConsumeByteString(self):
  964. try:
  965. self.ConsumeByteString()
  966. return True
  967. except ParseError:
  968. return False
  969. def ConsumeString(self):
  970. """Consumes a string value.
  971. Returns:
  972. The string parsed.
  973. Raises:
  974. ParseError: If a string value couldn't be consumed.
  975. """
  976. the_bytes = self.ConsumeByteString()
  977. try:
  978. return six.text_type(the_bytes, 'utf-8')
  979. except UnicodeDecodeError as e:
  980. raise self._StringParseError(e)
  981. def ConsumeByteString(self):
  982. """Consumes a byte array value.
  983. Returns:
  984. The array parsed (as a string).
  985. Raises:
  986. ParseError: If a byte array value couldn't be consumed.
  987. """
  988. the_list = [self._ConsumeSingleByteString()]
  989. while self.token and self.token[0] in _QUOTES:
  990. the_list.append(self._ConsumeSingleByteString())
  991. return b''.join(the_list)
  992. def _ConsumeSingleByteString(self):
  993. """Consume one token of a string literal.
  994. String literals (whether bytes or text) can come in multiple adjacent
  995. tokens which are automatically concatenated, like in C or Python. This
  996. method only consumes one token.
  997. Returns:
  998. The token parsed.
  999. Raises:
  1000. ParseError: When the wrong format data is found.
  1001. """
  1002. text = self.token
  1003. if len(text) < 1 or text[0] not in _QUOTES:
  1004. raise self.ParseError('Expected string but found: %r' % (text,))
  1005. if len(text) < 2 or text[-1] != text[0]:
  1006. raise self.ParseError('String missing ending quote: %r' % (text,))
  1007. try:
  1008. result = text_encoding.CUnescape(text[1:-1])
  1009. except ValueError as e:
  1010. raise self.ParseError(str(e))
  1011. self.NextToken()
  1012. return result
  1013. def ConsumeEnum(self, field):
  1014. try:
  1015. result = ParseEnum(field, self.token)
  1016. except ValueError as e:
  1017. raise self.ParseError(str(e))
  1018. self.NextToken()
  1019. return result
  1020. def ParseErrorPreviousToken(self, message):
  1021. """Creates and *returns* a ParseError for the previously read token.
  1022. Args:
  1023. message: A message to set for the exception.
  1024. Returns:
  1025. A ParseError instance.
  1026. """
  1027. return ParseError(message, self._previous_line + 1,
  1028. self._previous_column + 1)
  1029. def ParseError(self, message):
  1030. """Creates and *returns* a ParseError for the current token."""
  1031. return ParseError(message, self._line + 1, self._column + 1)
  1032. def _StringParseError(self, e):
  1033. return self.ParseError('Couldn\'t parse string: ' + str(e))
  1034. def NextToken(self):
  1035. """Reads the next meaningful token."""
  1036. self._previous_line = self._line
  1037. self._previous_column = self._column
  1038. self._column += len(self.token)
  1039. self._SkipWhitespace()
  1040. if not self._more_lines:
  1041. self.token = ''
  1042. return
  1043. match = self._TOKEN.match(self._current_line, self._column)
  1044. if not match and not self._skip_comments:
  1045. match = self._COMMENT.match(self._current_line, self._column)
  1046. if match:
  1047. token = match.group(0)
  1048. self.token = token
  1049. else:
  1050. self.token = self._current_line[self._column]
  1051. # Aliased so it can still be accessed by current visibility violators.
  1052. # TODO(dbarnett): Migrate violators to textformat_tokenizer.
  1053. _Tokenizer = Tokenizer # pylint: disable=invalid-name
  1054. def _ConsumeInt32(tokenizer):
  1055. """Consumes a signed 32bit integer number from tokenizer.
  1056. Args:
  1057. tokenizer: A tokenizer used to parse the number.
  1058. Returns:
  1059. The integer parsed.
  1060. Raises:
  1061. ParseError: If a signed 32bit integer couldn't be consumed.
  1062. """
  1063. return _ConsumeInteger(tokenizer, is_signed=True, is_long=False)
  1064. def _ConsumeUint32(tokenizer):
  1065. """Consumes an unsigned 32bit integer number from tokenizer.
  1066. Args:
  1067. tokenizer: A tokenizer used to parse the number.
  1068. Returns:
  1069. The integer parsed.
  1070. Raises:
  1071. ParseError: If an unsigned 32bit integer couldn't be consumed.
  1072. """
  1073. return _ConsumeInteger(tokenizer, is_signed=False, is_long=False)
  1074. def _TryConsumeInt64(tokenizer):
  1075. try:
  1076. _ConsumeInt64(tokenizer)
  1077. return True
  1078. except ParseError:
  1079. return False
  1080. def _ConsumeInt64(tokenizer):
  1081. """Consumes a signed 32bit integer number from tokenizer.
  1082. Args:
  1083. tokenizer: A tokenizer used to parse the number.
  1084. Returns:
  1085. The integer parsed.
  1086. Raises:
  1087. ParseError: If a signed 32bit integer couldn't be consumed.
  1088. """
  1089. return _ConsumeInteger(tokenizer, is_signed=True, is_long=True)
  1090. def _TryConsumeUint64(tokenizer):
  1091. try:
  1092. _ConsumeUint64(tokenizer)
  1093. return True
  1094. except ParseError:
  1095. return False
  1096. def _ConsumeUint64(tokenizer):
  1097. """Consumes an unsigned 64bit integer number from tokenizer.
  1098. Args:
  1099. tokenizer: A tokenizer used to parse the number.
  1100. Returns:
  1101. The integer parsed.
  1102. Raises:
  1103. ParseError: If an unsigned 64bit integer couldn't be consumed.
  1104. """
  1105. return _ConsumeInteger(tokenizer, is_signed=False, is_long=True)
  1106. def _TryConsumeInteger(tokenizer, is_signed=False, is_long=False):
  1107. try:
  1108. _ConsumeInteger(tokenizer, is_signed=is_signed, is_long=is_long)
  1109. return True
  1110. except ParseError:
  1111. return False
  1112. def _ConsumeInteger(tokenizer, is_signed=False, is_long=False):
  1113. """Consumes an integer number from tokenizer.
  1114. Args:
  1115. tokenizer: A tokenizer used to parse the number.
  1116. is_signed: True if a signed integer must be parsed.
  1117. is_long: True if a long integer must be parsed.
  1118. Returns:
  1119. The integer parsed.
  1120. Raises:
  1121. ParseError: If an integer with given characteristics couldn't be consumed.
  1122. """
  1123. try:
  1124. result = ParseInteger(tokenizer.token, is_signed=is_signed, is_long=is_long)
  1125. except ValueError as e:
  1126. raise tokenizer.ParseError(str(e))
  1127. tokenizer.NextToken()
  1128. return result
  1129. def ParseInteger(text, is_signed=False, is_long=False):
  1130. """Parses an integer.
  1131. Args:
  1132. text: The text to parse.
  1133. is_signed: True if a signed integer must be parsed.
  1134. is_long: True if a long integer must be parsed.
  1135. Returns:
  1136. The integer value.
  1137. Raises:
  1138. ValueError: Thrown Iff the text is not a valid integer.
  1139. """
  1140. # Do the actual parsing. Exception handling is propagated to caller.
  1141. result = _ParseAbstractInteger(text, is_long=is_long)
  1142. # Check if the integer is sane. Exceptions handled by callers.
  1143. checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
  1144. checker.CheckValue(result)
  1145. return result
  1146. def _ParseAbstractInteger(text, is_long=False):
  1147. """Parses an integer without checking size/signedness.
  1148. Args:
  1149. text: The text to parse.
  1150. is_long: True if the value should be returned as a long integer.
  1151. Returns:
  1152. The integer value.
  1153. Raises:
  1154. ValueError: Thrown Iff the text is not a valid integer.
  1155. """
  1156. # Do the actual parsing. Exception handling is propagated to caller.
  1157. try:
  1158. # We force 32-bit values to int and 64-bit values to long to make
  1159. # alternate implementations where the distinction is more significant
  1160. # (e.g. the C++ implementation) simpler.
  1161. if is_long:
  1162. return long(text, 0)
  1163. else:
  1164. return int(text, 0)
  1165. except ValueError:
  1166. raise ValueError('Couldn\'t parse integer: %s' % text)
  1167. def ParseFloat(text):
  1168. """Parse a floating point number.
  1169. Args:
  1170. text: Text to parse.
  1171. Returns:
  1172. The number parsed.
  1173. Raises:
  1174. ValueError: If a floating point number couldn't be parsed.
  1175. """
  1176. try:
  1177. # Assume Python compatible syntax.
  1178. return float(text)
  1179. except ValueError:
  1180. # Check alternative spellings.
  1181. if _FLOAT_INFINITY.match(text):
  1182. if text[0] == '-':
  1183. return float('-inf')
  1184. else:
  1185. return float('inf')
  1186. elif _FLOAT_NAN.match(text):
  1187. return float('nan')
  1188. else:
  1189. # assume '1.0f' format
  1190. try:
  1191. return float(text.rstrip('f'))
  1192. except ValueError:
  1193. raise ValueError('Couldn\'t parse float: %s' % text)
  1194. def ParseBool(text):
  1195. """Parse a boolean value.
  1196. Args:
  1197. text: Text to parse.
  1198. Returns:
  1199. Boolean values parsed
  1200. Raises:
  1201. ValueError: If text is not a valid boolean.
  1202. """
  1203. if text in ('true', 't', '1'):
  1204. return True
  1205. elif text in ('false', 'f', '0'):
  1206. return False
  1207. else:
  1208. raise ValueError('Expected "true" or "false".')
  1209. def ParseEnum(field, value):
  1210. """Parse an enum value.
  1211. The value can be specified by a number (the enum value), or by
  1212. a string literal (the enum name).
  1213. Args:
  1214. field: Enum field descriptor.
  1215. value: String value.
  1216. Returns:
  1217. Enum value number.
  1218. Raises:
  1219. ValueError: If the enum value could not be parsed.
  1220. """
  1221. enum_descriptor = field.enum_type
  1222. try:
  1223. number = int(value, 0)
  1224. except ValueError:
  1225. # Identifier.
  1226. enum_value = enum_descriptor.values_by_name.get(value, None)
  1227. if enum_value is None:
  1228. raise ValueError('Enum type "%s" has no value named %s.' %
  1229. (enum_descriptor.full_name, value))
  1230. else:
  1231. # Numeric value.
  1232. enum_value = enum_descriptor.values_by_number.get(number, None)
  1233. if enum_value is None:
  1234. raise ValueError('Enum type "%s" has no value with number %d.' %
  1235. (enum_descriptor.full_name, number))
  1236. return enum_value.number