text_format.py 50 KB

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