text_format.py 49 KB

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