text_format.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style
  5. # license that can be found in the LICENSE file or at
  6. # https://developers.google.com/open-source/licenses/bsd
  7. """Contains routines for printing protocol messages in text format.
  8. Simple usage example::
  9. # Create a proto object and serialize it to a text proto string.
  10. message = my_proto_pb2.MyMessage(foo='bar')
  11. text_proto = text_format.MessageToString(message)
  12. # Parse a text proto string.
  13. message = text_format.Parse(text_proto, my_proto_pb2.MyMessage())
  14. """
  15. __author__ = 'kenton@google.com (Kenton Varda)'
  16. # TODO Import thread contention leads to test failures.
  17. import encodings.raw_unicode_escape # pylint: disable=unused-import
  18. import encodings.unicode_escape # pylint: disable=unused-import
  19. import io
  20. import math
  21. import re
  22. import warnings
  23. from google.protobuf.internal import decoder
  24. from google.protobuf.internal import type_checkers
  25. from google.protobuf import descriptor
  26. from google.protobuf import text_encoding
  27. from google.protobuf import unknown_fields
  28. # pylint: disable=g-import-not-at-top
  29. __all__ = ['MessageToString', 'Parse', 'PrintMessage', 'PrintField',
  30. 'PrintFieldValue', 'Merge', 'MessageToBytes']
  31. _INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(),
  32. type_checkers.Int32ValueChecker(),
  33. type_checkers.Uint64ValueChecker(),
  34. type_checkers.Int64ValueChecker())
  35. _FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?$', re.IGNORECASE)
  36. _FLOAT_NAN = re.compile('nanf?$', re.IGNORECASE)
  37. _FLOAT_OCTAL_PREFIX = re.compile('-?0[0-9]+')
  38. _QUOTES = frozenset(("'", '"'))
  39. _ANY_FULL_TYPE_NAME = 'google.protobuf.Any'
  40. _DEBUG_STRING_SILENT_MARKER = '\t '
  41. _as_utf8_default = True
  42. class Error(Exception):
  43. """Top-level module error for text_format."""
  44. class ParseError(Error):
  45. """Thrown in case of text parsing or tokenizing error."""
  46. def __init__(self, message=None, line=None, column=None):
  47. if message is not None and line is not None:
  48. loc = str(line)
  49. if column is not None:
  50. loc += ':{0}'.format(column)
  51. message = '{0} : {1}'.format(loc, message)
  52. if message is not None:
  53. super(ParseError, self).__init__(message)
  54. else:
  55. super(ParseError, self).__init__()
  56. self._line = line
  57. self._column = column
  58. def GetLine(self):
  59. return self._line
  60. def GetColumn(self):
  61. return self._column
  62. class TextWriter(object):
  63. def __init__(self, as_utf8):
  64. self._writer = io.StringIO()
  65. def write(self, val):
  66. return self._writer.write(val)
  67. def close(self):
  68. return self._writer.close()
  69. def getvalue(self):
  70. return self._writer.getvalue()
  71. def MessageToString(
  72. message,
  73. as_utf8=_as_utf8_default,
  74. as_one_line=False,
  75. use_short_repeated_primitives=False,
  76. pointy_brackets=False,
  77. use_index_order=False,
  78. float_format=None,
  79. double_format=None,
  80. use_field_number=False,
  81. descriptor_pool=None,
  82. indent=0,
  83. message_formatter=None,
  84. print_unknown_fields=False,
  85. force_colon=False) -> str:
  86. """Convert protobuf message to text format.
  87. Double values can be formatted compactly with 15 digits of
  88. precision (which is the most that IEEE 754 "double" can guarantee)
  89. using double_format='.15g'. To ensure that converting to text and back to a
  90. proto will result in an identical value, double_format='.17g' should be used.
  91. Args:
  92. message: The protocol buffers message.
  93. as_utf8: Return unescaped Unicode for non-ASCII characters.
  94. as_one_line: Don't introduce newlines between fields.
  95. use_short_repeated_primitives: Use short repeated format for primitives.
  96. pointy_brackets: If True, use angle brackets instead of curly braces for
  97. nesting.
  98. use_index_order: If True, fields of a proto message will be printed using
  99. the order defined in source code instead of the field number, extensions
  100. will be printed at the end of the message and their relative order is
  101. determined by the extension number. By default, use the field number
  102. order.
  103. float_format (str): Deprecated. If set, use this to specify float field
  104. formatting (per the "Format Specification Mini-Language"); otherwise,
  105. shortest float that has same value in wire will be printed. Also affect
  106. double field if double_format is not set but float_format is set.
  107. double_format (str): Deprecated. If set, use this to specify double field
  108. formatting (per the "Format Specification Mini-Language"); if it is not
  109. set but float_format is set, use float_format. Otherwise, use ``str()``
  110. use_field_number: If True, print field numbers instead of names.
  111. descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types.
  112. indent (int): The initial indent level, in terms of spaces, for pretty
  113. print.
  114. message_formatter (function(message, indent, as_one_line) -> unicode|None):
  115. Custom formatter for selected sub-messages (usually based on message
  116. type). Use to pretty print parts of the protobuf for easier diffing.
  117. print_unknown_fields: If True, unknown fields will be printed.
  118. force_colon: If set, a colon will be added after the field name even if the
  119. field is a proto message.
  120. Returns:
  121. str: A string of the text formatted protocol buffer message.
  122. """
  123. out = TextWriter(as_utf8)
  124. printer = _Printer(
  125. out,
  126. indent,
  127. as_utf8,
  128. as_one_line,
  129. use_short_repeated_primitives,
  130. pointy_brackets,
  131. use_index_order,
  132. float_format,
  133. double_format,
  134. use_field_number,
  135. descriptor_pool,
  136. message_formatter,
  137. print_unknown_fields=print_unknown_fields,
  138. force_colon=force_colon)
  139. printer.PrintMessage(message)
  140. result = out.getvalue()
  141. out.close()
  142. if as_one_line:
  143. return result.rstrip()
  144. return result
  145. def MessageToBytes(message, **kwargs) -> bytes:
  146. """Convert protobuf message to encoded text format. See MessageToString."""
  147. text = MessageToString(message, **kwargs)
  148. if isinstance(text, bytes):
  149. return text
  150. codec = 'utf-8' if kwargs.get('as_utf8') else 'ascii'
  151. return text.encode(codec)
  152. def _IsMapEntry(field):
  153. return (field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  154. field.message_type.has_options and
  155. field.message_type.GetOptions().map_entry)
  156. def _IsGroupLike(field):
  157. """Determines if a field is consistent with a proto2 group.
  158. Args:
  159. field: The field descriptor.
  160. Returns:
  161. True if this field is group-like, false otherwise.
  162. """
  163. # Groups are always tag-delimited.
  164. if field.type != descriptor.FieldDescriptor.TYPE_GROUP:
  165. return False
  166. # Group fields always are always the lowercase type name.
  167. if field.name != field.message_type.name.lower():
  168. return False
  169. if field.message_type.file != field.file:
  170. return False
  171. # Group messages are always defined in the same scope as the field. File
  172. # level extensions will compare NULL == NULL here, which is why the file
  173. # comparison above is necessary to ensure both come from the same file.
  174. return (
  175. field.message_type.containing_type == field.extension_scope
  176. if field.is_extension
  177. else field.message_type.containing_type == field.containing_type
  178. )
  179. def PrintMessage(message,
  180. out,
  181. indent=0,
  182. as_utf8=_as_utf8_default,
  183. as_one_line=False,
  184. use_short_repeated_primitives=False,
  185. pointy_brackets=False,
  186. use_index_order=False,
  187. float_format=None,
  188. double_format=None,
  189. use_field_number=False,
  190. descriptor_pool=None,
  191. message_formatter=None,
  192. print_unknown_fields=False,
  193. force_colon=False):
  194. """Convert the message to text format and write it to the out stream.
  195. Args:
  196. message: The Message object to convert to text format.
  197. out: A file handle to write the message to.
  198. indent: The initial indent level for pretty print.
  199. as_utf8: Return unescaped Unicode for non-ASCII characters.
  200. as_one_line: Don't introduce newlines between fields.
  201. use_short_repeated_primitives: Use short repeated format for primitives.
  202. pointy_brackets: If True, use angle brackets instead of curly braces for
  203. nesting.
  204. use_index_order: If True, print fields of a proto message using the order
  205. defined in source code instead of the field number. By default, use the
  206. field number order.
  207. float_format: If set, use this to specify float field formatting
  208. (per the "Format Specification Mini-Language"); otherwise, shortest
  209. float that has same value in wire will be printed. Also affect double
  210. field if double_format is not set but float_format is set.
  211. double_format: If set, use this to specify double field formatting
  212. (per the "Format Specification Mini-Language"); if it is not set but
  213. float_format is set, use float_format. Otherwise, str() is used.
  214. use_field_number: If True, print field numbers instead of names.
  215. descriptor_pool: A DescriptorPool used to resolve Any types.
  216. message_formatter: A function(message, indent, as_one_line): unicode|None
  217. to custom format selected sub-messages (usually based on message type).
  218. Use to pretty print parts of the protobuf for easier diffing.
  219. print_unknown_fields: If True, unknown fields will be printed.
  220. force_colon: If set, a colon will be added after the field name even if
  221. the field is a proto message.
  222. """
  223. printer = _Printer(
  224. out=out, indent=indent, as_utf8=as_utf8,
  225. as_one_line=as_one_line,
  226. use_short_repeated_primitives=use_short_repeated_primitives,
  227. pointy_brackets=pointy_brackets,
  228. use_index_order=use_index_order,
  229. float_format=float_format,
  230. double_format=double_format,
  231. use_field_number=use_field_number,
  232. descriptor_pool=descriptor_pool,
  233. message_formatter=message_formatter,
  234. print_unknown_fields=print_unknown_fields,
  235. force_colon=force_colon)
  236. printer.PrintMessage(message)
  237. def PrintField(field,
  238. value,
  239. out,
  240. indent=0,
  241. as_utf8=_as_utf8_default,
  242. as_one_line=False,
  243. use_short_repeated_primitives=False,
  244. pointy_brackets=False,
  245. use_index_order=False,
  246. float_format=None,
  247. double_format=None,
  248. message_formatter=None,
  249. print_unknown_fields=False,
  250. force_colon=False):
  251. """Print a single field name/value pair."""
  252. printer = _Printer(out, indent, as_utf8, as_one_line,
  253. use_short_repeated_primitives, pointy_brackets,
  254. use_index_order, float_format, double_format,
  255. message_formatter=message_formatter,
  256. print_unknown_fields=print_unknown_fields,
  257. force_colon=force_colon)
  258. printer.PrintField(field, value)
  259. def PrintFieldValue(field,
  260. value,
  261. out,
  262. indent=0,
  263. as_utf8=_as_utf8_default,
  264. as_one_line=False,
  265. use_short_repeated_primitives=False,
  266. pointy_brackets=False,
  267. use_index_order=False,
  268. float_format=None,
  269. double_format=None,
  270. message_formatter=None,
  271. print_unknown_fields=False,
  272. force_colon=False):
  273. """Print a single field value (not including name)."""
  274. printer = _Printer(out, indent, as_utf8, as_one_line,
  275. use_short_repeated_primitives, pointy_brackets,
  276. use_index_order, float_format, double_format,
  277. message_formatter=message_formatter,
  278. print_unknown_fields=print_unknown_fields,
  279. force_colon=force_colon)
  280. printer.PrintFieldValue(field, value)
  281. def _BuildMessageFromTypeName(type_name, descriptor_pool):
  282. """Returns a protobuf message instance.
  283. Args:
  284. type_name: Fully-qualified protobuf message type name string.
  285. descriptor_pool: DescriptorPool instance.
  286. Returns:
  287. A Message instance of type matching type_name, or None if the a Descriptor
  288. wasn't found matching type_name.
  289. """
  290. # pylint: disable=g-import-not-at-top
  291. if descriptor_pool is None:
  292. from google.protobuf import descriptor_pool as pool_mod
  293. descriptor_pool = pool_mod.Default()
  294. from google.protobuf import message_factory
  295. try:
  296. message_descriptor = descriptor_pool.FindMessageTypeByName(type_name)
  297. except KeyError:
  298. return None
  299. message_type = message_factory.GetMessageClass(message_descriptor)
  300. return message_type()
  301. # These values must match WireType enum in //google/protobuf/wire_format.h.
  302. WIRETYPE_LENGTH_DELIMITED = 2
  303. WIRETYPE_START_GROUP = 3
  304. class _Printer(object):
  305. """Text format printer for protocol message."""
  306. def __init__(
  307. self,
  308. out,
  309. indent=0,
  310. as_utf8=_as_utf8_default,
  311. as_one_line=False,
  312. use_short_repeated_primitives=False,
  313. pointy_brackets=False,
  314. use_index_order=False,
  315. float_format=None,
  316. double_format=None,
  317. use_field_number=False,
  318. descriptor_pool=None,
  319. message_formatter=None,
  320. print_unknown_fields=False,
  321. force_colon=False):
  322. """Initialize the Printer.
  323. Double values can be formatted compactly with 15 digits of precision
  324. (which is the most that IEEE 754 "double" can guarantee) using
  325. double_format='.15g'. To ensure that converting to text and back to a proto
  326. will result in an identical value, double_format='.17g' should be used.
  327. Args:
  328. out: To record the text format result.
  329. indent: The initial indent level for pretty print.
  330. as_utf8: Return unescaped Unicode for non-ASCII characters.
  331. as_one_line: Don't introduce newlines between fields.
  332. use_short_repeated_primitives: Use short repeated format for primitives.
  333. pointy_brackets: If True, use angle brackets instead of curly braces for
  334. nesting.
  335. use_index_order: If True, print fields of a proto message using the order
  336. defined in source code instead of the field number. By default, use the
  337. field number order.
  338. float_format: Deprecated. If set, use this to specify float field
  339. formatting (per the "Format Specification Mini-Language"); otherwise,
  340. shortest float that has same value in wire will be printed. Also affect
  341. double field if double_format is not set but float_format is set.
  342. double_format: Deprecated. If set, use this to specify double field
  343. formatting (per the "Format Specification Mini-Language"); if it is not
  344. set but float_format is set, use float_format. Otherwise, str() is used.
  345. use_field_number: If True, print field numbers instead of names.
  346. descriptor_pool: A DescriptorPool used to resolve Any types.
  347. message_formatter: A function(message, indent, as_one_line): unicode|None
  348. to custom format selected sub-messages (usually based on message type).
  349. Use to pretty print parts of the protobuf for easier diffing.
  350. print_unknown_fields: If True, unknown fields will be printed.
  351. force_colon: If set, a colon will be added after the field name even if
  352. the field is a proto message.
  353. """
  354. self.out = out
  355. self.indent = indent
  356. self.as_utf8 = as_utf8
  357. self.as_one_line = as_one_line
  358. self.use_short_repeated_primitives = use_short_repeated_primitives
  359. self.pointy_brackets = pointy_brackets
  360. self.use_index_order = use_index_order
  361. self.float_format = float_format
  362. if double_format is not None:
  363. warnings.warn(
  364. 'double_format is deprecated for text_format. This will '
  365. 'turn into error in 7.34.0, please remove it before that.'
  366. )
  367. self.double_format = double_format
  368. else:
  369. self.double_format = float_format
  370. self.use_field_number = use_field_number
  371. self.descriptor_pool = descriptor_pool
  372. self.message_formatter = message_formatter
  373. self.print_unknown_fields = print_unknown_fields
  374. self.force_colon = force_colon
  375. def _TryPrintAsAnyMessage(self, message):
  376. """Serializes if message is a google.protobuf.Any field."""
  377. if '/' not in message.type_url:
  378. return False
  379. packed_message = _BuildMessageFromTypeName(message.TypeName(),
  380. self.descriptor_pool)
  381. if packed_message is not None:
  382. packed_message.MergeFromString(message.value)
  383. colon = ':' if self.force_colon else ''
  384. self.out.write('%s[%s]%s ' % (self.indent * ' ', message.type_url, colon))
  385. self._PrintMessageFieldValue(packed_message)
  386. self.out.write(' ' if self.as_one_line else '\n')
  387. return True
  388. else:
  389. return False
  390. def _TryCustomFormatMessage(self, message):
  391. formatted = self.message_formatter(message, self.indent, self.as_one_line)
  392. if formatted is None:
  393. return False
  394. out = self.out
  395. out.write(' ' * self.indent)
  396. out.write(formatted)
  397. out.write(' ' if self.as_one_line else '\n')
  398. return True
  399. def PrintMessage(self, message):
  400. """Convert protobuf message to text format.
  401. Args:
  402. message: The protocol buffers message.
  403. """
  404. if self.message_formatter and self._TryCustomFormatMessage(message):
  405. return
  406. if (message.DESCRIPTOR.full_name == _ANY_FULL_TYPE_NAME and
  407. self._TryPrintAsAnyMessage(message)):
  408. return
  409. fields = message.ListFields()
  410. if self.use_index_order:
  411. fields.sort(
  412. key=lambda x: x[0].number if x[0].is_extension else x[0].index)
  413. for field, value in fields:
  414. if _IsMapEntry(field):
  415. for key in sorted(value):
  416. # This is slow for maps with submessage entries because it copies the
  417. # entire tree. Unfortunately this would take significant refactoring
  418. # of this file to work around.
  419. #
  420. # TODO: refactor and optimize if this becomes an issue.
  421. entry_submsg = value.GetEntryClass()(key=key, value=value[key])
  422. self.PrintField(field, entry_submsg)
  423. elif field.is_repeated:
  424. if (self.use_short_repeated_primitives
  425. and field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE
  426. and field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_STRING):
  427. self._PrintShortRepeatedPrimitivesValue(field, value)
  428. else:
  429. for element in value:
  430. self.PrintField(field, element)
  431. else:
  432. self.PrintField(field, value)
  433. if self.print_unknown_fields:
  434. self._PrintUnknownFields(unknown_fields.UnknownFieldSet(message))
  435. def _PrintUnknownFields(self, unknown_field_set):
  436. """Print unknown fields."""
  437. out = self.out
  438. for field in unknown_field_set:
  439. out.write(' ' * self.indent)
  440. out.write(str(field.field_number))
  441. if field.wire_type == WIRETYPE_START_GROUP:
  442. if self.as_one_line:
  443. out.write(' { ')
  444. else:
  445. out.write(' {\n')
  446. self.indent += 2
  447. self._PrintUnknownFields(field.data)
  448. if self.as_one_line:
  449. out.write('} ')
  450. else:
  451. self.indent -= 2
  452. out.write(' ' * self.indent + '}\n')
  453. elif field.wire_type == WIRETYPE_LENGTH_DELIMITED:
  454. try:
  455. # If this field is parseable as a Message, it is probably
  456. # an embedded message.
  457. # pylint: disable=protected-access
  458. (embedded_unknown_message, pos) = decoder._DecodeUnknownFieldSet(
  459. memoryview(field.data), 0, len(field.data))
  460. except Exception: # pylint: disable=broad-except
  461. pos = 0
  462. if pos == len(field.data):
  463. if self.as_one_line:
  464. out.write(' { ')
  465. else:
  466. out.write(' {\n')
  467. self.indent += 2
  468. self._PrintUnknownFields(embedded_unknown_message)
  469. if self.as_one_line:
  470. out.write('} ')
  471. else:
  472. self.indent -= 2
  473. out.write(' ' * self.indent + '}\n')
  474. else:
  475. # A string or bytes field. self.as_utf8 may not work.
  476. out.write(': \"')
  477. out.write(text_encoding.CEscape(field.data, False))
  478. out.write('\" ' if self.as_one_line else '\"\n')
  479. else:
  480. # varint, fixed32, fixed64
  481. out.write(': ')
  482. out.write(str(field.data))
  483. out.write(' ' if self.as_one_line else '\n')
  484. def _PrintFieldName(self, field):
  485. """Print field name."""
  486. out = self.out
  487. out.write(' ' * self.indent)
  488. if self.use_field_number:
  489. out.write(str(field.number))
  490. else:
  491. if field.is_extension:
  492. out.write('[')
  493. if (field.containing_type.GetOptions().message_set_wire_format and
  494. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  495. not field.is_required and
  496. not field.is_repeated):
  497. out.write(field.message_type.full_name)
  498. else:
  499. out.write(field.full_name)
  500. out.write(']')
  501. elif _IsGroupLike(field):
  502. # For groups, use the capitalized name.
  503. out.write(field.message_type.name)
  504. else:
  505. out.write(field.name)
  506. if (self.force_colon or
  507. field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE):
  508. # The colon is optional in this case, but our cross-language golden files
  509. # don't include it. Here, the colon is only included if force_colon is
  510. # set to True
  511. out.write(':')
  512. def PrintField(self, field, value):
  513. """Print a single field name/value pair."""
  514. self._PrintFieldName(field)
  515. self.out.write(' ')
  516. self.PrintFieldValue(field, value)
  517. self.out.write(' ' if self.as_one_line else '\n')
  518. def _PrintShortRepeatedPrimitivesValue(self, field, value):
  519. """"Prints short repeated primitives value."""
  520. # Note: this is called only when value has at least one element.
  521. self._PrintFieldName(field)
  522. self.out.write(' [')
  523. for i in range(len(value) - 1):
  524. self.PrintFieldValue(field, value[i])
  525. self.out.write(', ')
  526. self.PrintFieldValue(field, value[-1])
  527. self.out.write(']')
  528. self.out.write(' ' if self.as_one_line else '\n')
  529. def _PrintMessageFieldValue(self, value):
  530. if self.pointy_brackets:
  531. openb = '<'
  532. closeb = '>'
  533. else:
  534. openb = '{'
  535. closeb = '}'
  536. if self.as_one_line:
  537. self.out.write('%s ' % openb)
  538. self.PrintMessage(value)
  539. self.out.write(closeb)
  540. else:
  541. self.out.write('%s\n' % openb)
  542. self.indent += 2
  543. self.PrintMessage(value)
  544. self.indent -= 2
  545. self.out.write(' ' * self.indent + closeb)
  546. def PrintFieldValue(self, field, value):
  547. """Print a single field value (not including name).
  548. For repeated fields, the value should be a single element.
  549. Args:
  550. field: The descriptor of the field to be printed.
  551. value: The value of the field.
  552. """
  553. out = self.out
  554. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  555. self._PrintMessageFieldValue(value)
  556. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
  557. enum_value = field.enum_type.values_by_number.get(value, None)
  558. if enum_value is not None:
  559. out.write(enum_value.name)
  560. else:
  561. out.write(str(value))
  562. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
  563. out.write('\"')
  564. if isinstance(value, str) and not self.as_utf8:
  565. out_value = value.encode('utf-8')
  566. else:
  567. out_value = value
  568. if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  569. # We always need to escape all binary data in TYPE_BYTES fields.
  570. out_as_utf8 = False
  571. else:
  572. out_as_utf8 = self.as_utf8
  573. out.write(text_encoding.CEscape(out_value, out_as_utf8))
  574. out.write('\"')
  575. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
  576. if value:
  577. out.write('true')
  578. else:
  579. out.write('false')
  580. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_FLOAT:
  581. if self.float_format is not None:
  582. warnings.warn(
  583. 'float_format is deprecated for text_format. This '
  584. 'will turn into error in 7.34.0, please remove it '
  585. 'before that.'
  586. )
  587. out.write('{1:{0}}'.format(self.float_format, value))
  588. else:
  589. if math.isnan(value):
  590. out.write(str(value))
  591. else:
  592. out.write(str(type_checkers.ToShortestFloat(value)))
  593. elif (field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_DOUBLE and
  594. self.double_format is not None):
  595. out.write('{1:{0}}'.format(self.double_format, value))
  596. else:
  597. out.write(str(value))
  598. def Parse(text,
  599. message,
  600. allow_unknown_extension=False,
  601. allow_field_number=False,
  602. descriptor_pool=None,
  603. allow_unknown_field=False):
  604. """Parses a text representation of a protocol message into a message.
  605. NOTE: for historical reasons this function does not clear the input
  606. message. This is different from what the binary msg.ParseFrom(...) does.
  607. If text contains a field already set in message, the value is appended if the
  608. field is repeated. Otherwise, an error is raised.
  609. Example::
  610. a = MyProto()
  611. a.repeated_field.append('test')
  612. b = MyProto()
  613. # Repeated fields are combined
  614. text_format.Parse(repr(a), b)
  615. text_format.Parse(repr(a), b) # repeated_field contains ["test", "test"]
  616. # Non-repeated fields cannot be overwritten
  617. a.singular_field = 1
  618. b.singular_field = 2
  619. text_format.Parse(repr(a), b) # ParseError
  620. # Binary version:
  621. b.ParseFromString(a.SerializeToString()) # repeated_field is now "test"
  622. Caller is responsible for clearing the message as needed.
  623. Args:
  624. text (str): Message text representation.
  625. message (Message): A protocol buffer message to merge into.
  626. allow_unknown_extension: if True, skip over missing extensions and keep
  627. parsing
  628. allow_field_number: if True, both field number and field name are allowed.
  629. descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types.
  630. allow_unknown_field: if True, skip over unknown field and keep
  631. parsing. Avoid to use this option if possible. It may hide some
  632. errors (e.g. spelling error on field name)
  633. Returns:
  634. Message: The same message passed as argument.
  635. Raises:
  636. ParseError: On text parsing problems.
  637. """
  638. return ParseLines(text.split(b'\n' if isinstance(text, bytes) else u'\n'),
  639. message,
  640. allow_unknown_extension,
  641. allow_field_number,
  642. descriptor_pool=descriptor_pool,
  643. allow_unknown_field=allow_unknown_field)
  644. def Merge(text,
  645. message,
  646. allow_unknown_extension=False,
  647. allow_field_number=False,
  648. descriptor_pool=None,
  649. allow_unknown_field=False):
  650. """Parses a text representation of a protocol message into a message.
  651. Like Parse(), but allows repeated values for a non-repeated field, and uses
  652. the last one. This means any non-repeated, top-level fields specified in text
  653. replace those in the message.
  654. Args:
  655. text (str): Message text representation.
  656. message (Message): A protocol buffer message to merge into.
  657. allow_unknown_extension: if True, skip over missing extensions and keep
  658. parsing
  659. allow_field_number: if True, both field number and field name are allowed.
  660. descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types.
  661. allow_unknown_field: if True, skip over unknown field and keep
  662. parsing. Avoid to use this option if possible. It may hide some
  663. errors (e.g. spelling error on field name)
  664. Returns:
  665. Message: The same message passed as argument.
  666. Raises:
  667. ParseError: On text parsing problems.
  668. """
  669. return MergeLines(
  670. text.split(b'\n' if isinstance(text, bytes) else u'\n'),
  671. message,
  672. allow_unknown_extension,
  673. allow_field_number,
  674. descriptor_pool=descriptor_pool,
  675. allow_unknown_field=allow_unknown_field)
  676. def ParseLines(lines,
  677. message,
  678. allow_unknown_extension=False,
  679. allow_field_number=False,
  680. descriptor_pool=None,
  681. allow_unknown_field=False):
  682. """Parses a text representation of a protocol message into a message.
  683. See Parse() for caveats.
  684. Args:
  685. lines: An iterable of lines of a message's text representation.
  686. message: A protocol buffer message to merge into.
  687. allow_unknown_extension: if True, skip over missing extensions and keep
  688. parsing
  689. allow_field_number: if True, both field number and field name are allowed.
  690. descriptor_pool: A DescriptorPool used to resolve Any types.
  691. allow_unknown_field: if True, skip over unknown field and keep
  692. parsing. Avoid to use this option if possible. It may hide some
  693. errors (e.g. spelling error on field name)
  694. Returns:
  695. The same message passed as argument.
  696. Raises:
  697. ParseError: On text parsing problems.
  698. """
  699. parser = _Parser(allow_unknown_extension,
  700. allow_field_number,
  701. descriptor_pool=descriptor_pool,
  702. allow_unknown_field=allow_unknown_field)
  703. return parser.ParseLines(lines, message)
  704. def MergeLines(lines,
  705. message,
  706. allow_unknown_extension=False,
  707. allow_field_number=False,
  708. descriptor_pool=None,
  709. allow_unknown_field=False):
  710. """Parses a text representation of a protocol message into a message.
  711. See Merge() for more details.
  712. Args:
  713. lines: An iterable of lines of a message's text representation.
  714. message: A protocol buffer message to merge into.
  715. allow_unknown_extension: if True, skip over missing extensions and keep
  716. parsing
  717. allow_field_number: if True, both field number and field name are allowed.
  718. descriptor_pool: A DescriptorPool used to resolve Any types.
  719. allow_unknown_field: if True, skip over unknown field and keep
  720. parsing. Avoid to use this option if possible. It may hide some
  721. errors (e.g. spelling error on field name)
  722. Returns:
  723. The same message passed as argument.
  724. Raises:
  725. ParseError: On text parsing problems.
  726. """
  727. parser = _Parser(allow_unknown_extension,
  728. allow_field_number,
  729. descriptor_pool=descriptor_pool,
  730. allow_unknown_field=allow_unknown_field)
  731. return parser.MergeLines(lines, message)
  732. class _Parser(object):
  733. """Text format parser for protocol message."""
  734. def __init__(self,
  735. allow_unknown_extension=False,
  736. allow_field_number=False,
  737. descriptor_pool=None,
  738. allow_unknown_field=False):
  739. self.allow_unknown_extension = allow_unknown_extension
  740. self.allow_field_number = allow_field_number
  741. self.descriptor_pool = descriptor_pool
  742. self.allow_unknown_field = allow_unknown_field
  743. def ParseLines(self, lines, message):
  744. """Parses a text representation of a protocol message into a message."""
  745. self._allow_multiple_scalars = False
  746. self._ParseOrMerge(lines, message)
  747. return message
  748. def MergeLines(self, lines, message):
  749. """Merges a text representation of a protocol message into a message."""
  750. self._allow_multiple_scalars = True
  751. self._ParseOrMerge(lines, message)
  752. return message
  753. def _ParseOrMerge(self, lines, message):
  754. """Converts a text representation of a protocol message into a message.
  755. Args:
  756. lines: Lines of a message's text representation.
  757. message: A protocol buffer message to merge into.
  758. Raises:
  759. ParseError: On text parsing problems.
  760. """
  761. # Tokenize expects native str lines.
  762. try:
  763. str_lines = (
  764. line if isinstance(line, str) else line.decode('utf-8')
  765. for line in lines)
  766. tokenizer = Tokenizer(str_lines)
  767. except UnicodeDecodeError as e:
  768. raise ParseError from e
  769. if message:
  770. self.root_type = message.DESCRIPTOR.full_name
  771. while not tokenizer.AtEnd():
  772. self._MergeField(tokenizer, message)
  773. def _MergeField(self, tokenizer, message):
  774. """Merges a single protocol message field into a message.
  775. Args:
  776. tokenizer: A tokenizer to parse the field name and values.
  777. message: A protocol message to record the data.
  778. Raises:
  779. ParseError: In case of text parsing problems.
  780. """
  781. message_descriptor = message.DESCRIPTOR
  782. if (message_descriptor.full_name == _ANY_FULL_TYPE_NAME and
  783. tokenizer.TryConsume('[')):
  784. type_url_prefix, packed_type_name = self._ConsumeAnyTypeUrl(tokenizer)
  785. tokenizer.Consume(']')
  786. tokenizer.TryConsume(':')
  787. self._DetectSilentMarker(tokenizer, message_descriptor.full_name,
  788. type_url_prefix + '/' + packed_type_name)
  789. if tokenizer.TryConsume('<'):
  790. expanded_any_end_token = '>'
  791. else:
  792. tokenizer.Consume('{')
  793. expanded_any_end_token = '}'
  794. expanded_any_sub_message = _BuildMessageFromTypeName(packed_type_name,
  795. self.descriptor_pool)
  796. # Direct comparison with None is used instead of implicit bool conversion
  797. # to avoid false positives with falsy initial values, e.g. for
  798. # google.protobuf.ListValue.
  799. if expanded_any_sub_message is None:
  800. raise ParseError('Type %s not found in descriptor pool' %
  801. packed_type_name)
  802. while not tokenizer.TryConsume(expanded_any_end_token):
  803. if tokenizer.AtEnd():
  804. raise tokenizer.ParseErrorPreviousToken('Expected "%s".' %
  805. (expanded_any_end_token,))
  806. self._MergeField(tokenizer, expanded_any_sub_message)
  807. deterministic = False
  808. message.Pack(expanded_any_sub_message,
  809. type_url_prefix=type_url_prefix,
  810. deterministic=deterministic)
  811. return
  812. if tokenizer.TryConsume('['):
  813. name = [tokenizer.ConsumeIdentifier()]
  814. while tokenizer.TryConsume('.'):
  815. name.append(tokenizer.ConsumeIdentifier())
  816. name = '.'.join(name)
  817. if not message_descriptor.is_extendable:
  818. raise tokenizer.ParseErrorPreviousToken(
  819. 'Message type "%s" does not have extensions.' %
  820. message_descriptor.full_name)
  821. # pylint: disable=protected-access
  822. field = message.Extensions._FindExtensionByName(name)
  823. # pylint: enable=protected-access
  824. if not field:
  825. if self.allow_unknown_extension:
  826. field = None
  827. else:
  828. raise tokenizer.ParseErrorPreviousToken(
  829. 'Extension "%s" not registered. '
  830. 'Did you import the _pb2 module which defines it? '
  831. 'If you are trying to place the extension in the MessageSet '
  832. 'field of another message that is in an Any or MessageSet field, '
  833. 'that message\'s _pb2 module must be imported as well' % name)
  834. elif message_descriptor != field.containing_type:
  835. raise tokenizer.ParseErrorPreviousToken(
  836. 'Extension "%s" does not extend message type "%s".' %
  837. (name, message_descriptor.full_name))
  838. tokenizer.Consume(']')
  839. else:
  840. name = tokenizer.ConsumeIdentifierOrNumber()
  841. if self.allow_field_number and name.isdigit():
  842. number = ParseInteger(name, True, True)
  843. field = message_descriptor.fields_by_number.get(number, None)
  844. if not field and message_descriptor.is_extendable:
  845. field = message.Extensions._FindExtensionByNumber(number)
  846. else:
  847. field = message_descriptor.fields_by_name.get(name, None)
  848. # Group names are expected to be capitalized as they appear in the
  849. # .proto file, which actually matches their type names, not their field
  850. # names.
  851. if not field:
  852. field = message_descriptor.fields_by_name.get(name.lower(), None)
  853. if field and not _IsGroupLike(field):
  854. field = None
  855. if field and field.message_type.name != name:
  856. field = None
  857. if not field and not self.allow_unknown_field:
  858. raise tokenizer.ParseErrorPreviousToken(
  859. 'Message type "%s" has no field named "%s".' %
  860. (message_descriptor.full_name, name))
  861. if field:
  862. if not self._allow_multiple_scalars and field.containing_oneof:
  863. # Check if there's a different field set in this oneof.
  864. # Note that we ignore the case if the same field was set before, and we
  865. # apply _allow_multiple_scalars to non-scalar fields as well.
  866. which_oneof = message.WhichOneof(field.containing_oneof.name)
  867. if which_oneof is not None and which_oneof != field.name:
  868. raise tokenizer.ParseErrorPreviousToken(
  869. 'Field "%s" is specified along with field "%s", another member '
  870. 'of oneof "%s" for message type "%s".' %
  871. (field.name, which_oneof, field.containing_oneof.name,
  872. message_descriptor.full_name))
  873. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  874. tokenizer.TryConsume(':')
  875. self._DetectSilentMarker(tokenizer, message_descriptor.full_name,
  876. field.full_name)
  877. merger = self._MergeMessageField
  878. else:
  879. tokenizer.Consume(':')
  880. self._DetectSilentMarker(tokenizer, message_descriptor.full_name,
  881. field.full_name)
  882. merger = self._MergeScalarField
  883. if (field.is_repeated and
  884. tokenizer.TryConsume('[')):
  885. # Short repeated format, e.g. "foo: [1, 2, 3]"
  886. if not tokenizer.TryConsume(']'):
  887. while True:
  888. merger(tokenizer, message, field)
  889. if tokenizer.TryConsume(']'):
  890. break
  891. tokenizer.Consume(',')
  892. else:
  893. merger(tokenizer, message, field)
  894. else: # Proto field is unknown.
  895. assert (self.allow_unknown_extension or self.allow_unknown_field)
  896. self._SkipFieldContents(tokenizer, name, message_descriptor.full_name)
  897. # For historical reasons, fields may optionally be separated by commas or
  898. # semicolons.
  899. if not tokenizer.TryConsume(','):
  900. tokenizer.TryConsume(';')
  901. def _LogSilentMarker(self, immediate_message_type, field_name):
  902. pass
  903. def _DetectSilentMarker(self, tokenizer, immediate_message_type, field_name):
  904. if tokenizer.contains_silent_marker_before_current_token:
  905. self._LogSilentMarker(immediate_message_type, field_name)
  906. def _ConsumeAnyTypeUrl(self, tokenizer):
  907. """Consumes a google.protobuf.Any type URL and returns the type name."""
  908. # Consume "type.googleapis.com/".
  909. prefix = [tokenizer.ConsumeIdentifier()]
  910. tokenizer.Consume('.')
  911. prefix.append(tokenizer.ConsumeIdentifier())
  912. tokenizer.Consume('.')
  913. prefix.append(tokenizer.ConsumeIdentifier())
  914. tokenizer.Consume('/')
  915. # Consume the fully-qualified type name.
  916. name = [tokenizer.ConsumeIdentifier()]
  917. while tokenizer.TryConsume('.'):
  918. name.append(tokenizer.ConsumeIdentifier())
  919. return '.'.join(prefix), '.'.join(name)
  920. def _MergeMessageField(self, tokenizer, message, field):
  921. """Merges a single scalar field into a message.
  922. Args:
  923. tokenizer: A tokenizer to parse the field value.
  924. message: The message of which field is a member.
  925. field: The descriptor of the field to be merged.
  926. Raises:
  927. ParseError: In case of text parsing problems.
  928. """
  929. is_map_entry = _IsMapEntry(field)
  930. if tokenizer.TryConsume('<'):
  931. end_token = '>'
  932. else:
  933. tokenizer.Consume('{')
  934. end_token = '}'
  935. if field.is_repeated:
  936. if field.is_extension:
  937. sub_message = message.Extensions[field].add()
  938. elif is_map_entry:
  939. sub_message = getattr(message, field.name).GetEntryClass()()
  940. else:
  941. sub_message = getattr(message, field.name).add()
  942. else:
  943. if field.is_extension:
  944. if (not self._allow_multiple_scalars and
  945. message.HasExtension(field)):
  946. raise tokenizer.ParseErrorPreviousToken(
  947. 'Message type "%s" should not have multiple "%s" extensions.' %
  948. (message.DESCRIPTOR.full_name, field.full_name))
  949. sub_message = message.Extensions[field]
  950. else:
  951. # Also apply _allow_multiple_scalars to message field.
  952. # TODO: Change to _allow_singular_overwrites.
  953. if (not self._allow_multiple_scalars and
  954. message.HasField(field.name)):
  955. raise tokenizer.ParseErrorPreviousToken(
  956. 'Message type "%s" should not have multiple "%s" fields.' %
  957. (message.DESCRIPTOR.full_name, field.name))
  958. sub_message = getattr(message, field.name)
  959. sub_message.SetInParent()
  960. while not tokenizer.TryConsume(end_token):
  961. if tokenizer.AtEnd():
  962. raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token,))
  963. self._MergeField(tokenizer, sub_message)
  964. if is_map_entry:
  965. value_cpptype = field.message_type.fields_by_name['value'].cpp_type
  966. if value_cpptype == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  967. value = getattr(message, field.name)[sub_message.key]
  968. value.CopyFrom(sub_message.value)
  969. else:
  970. getattr(message, field.name)[sub_message.key] = sub_message.value
  971. def _MergeScalarField(self, tokenizer, message, field):
  972. """Merges a single scalar field into a message.
  973. Args:
  974. tokenizer: A tokenizer to parse the field value.
  975. message: A protocol message to record the data.
  976. field: The descriptor of the field to be merged.
  977. Raises:
  978. ParseError: In case of text parsing problems.
  979. RuntimeError: On runtime errors.
  980. """
  981. _ = self.allow_unknown_extension
  982. value = None
  983. if field.type in (descriptor.FieldDescriptor.TYPE_INT32,
  984. descriptor.FieldDescriptor.TYPE_SINT32,
  985. descriptor.FieldDescriptor.TYPE_SFIXED32):
  986. value = _ConsumeInt32(tokenizer)
  987. elif field.type in (descriptor.FieldDescriptor.TYPE_INT64,
  988. descriptor.FieldDescriptor.TYPE_SINT64,
  989. descriptor.FieldDescriptor.TYPE_SFIXED64):
  990. value = _ConsumeInt64(tokenizer)
  991. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32,
  992. descriptor.FieldDescriptor.TYPE_FIXED32):
  993. value = _ConsumeUint32(tokenizer)
  994. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64,
  995. descriptor.FieldDescriptor.TYPE_FIXED64):
  996. value = _ConsumeUint64(tokenizer)
  997. elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT,
  998. descriptor.FieldDescriptor.TYPE_DOUBLE):
  999. value = tokenizer.ConsumeFloat()
  1000. elif field.type == descriptor.FieldDescriptor.TYPE_BOOL:
  1001. value = tokenizer.ConsumeBool()
  1002. elif field.type == descriptor.FieldDescriptor.TYPE_STRING:
  1003. value = tokenizer.ConsumeString()
  1004. elif field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  1005. value = tokenizer.ConsumeByteString()
  1006. elif field.type == descriptor.FieldDescriptor.TYPE_ENUM:
  1007. value = tokenizer.ConsumeEnum(field)
  1008. else:
  1009. raise RuntimeError('Unknown field type %d' % field.type)
  1010. if field.is_repeated:
  1011. if field.is_extension:
  1012. message.Extensions[field].append(value)
  1013. else:
  1014. getattr(message, field.name).append(value)
  1015. else:
  1016. if field.is_extension:
  1017. if (not self._allow_multiple_scalars and
  1018. field.has_presence and
  1019. message.HasExtension(field)):
  1020. raise tokenizer.ParseErrorPreviousToken(
  1021. 'Message type "%s" should not have multiple "%s" extensions.' %
  1022. (message.DESCRIPTOR.full_name, field.full_name))
  1023. else:
  1024. message.Extensions[field] = value
  1025. else:
  1026. duplicate_error = False
  1027. if not self._allow_multiple_scalars:
  1028. if field.has_presence:
  1029. duplicate_error = message.HasField(field.name)
  1030. else:
  1031. # For field that doesn't represent presence, try best effort to
  1032. # check multiple scalars by compare to default values.
  1033. duplicate_error = not decoder.IsDefaultScalarValue(
  1034. getattr(message, field.name)
  1035. )
  1036. if duplicate_error:
  1037. raise tokenizer.ParseErrorPreviousToken(
  1038. 'Message type "%s" should not have multiple "%s" fields.' %
  1039. (message.DESCRIPTOR.full_name, field.name))
  1040. else:
  1041. setattr(message, field.name, value)
  1042. def _SkipFieldContents(self, tokenizer, field_name, immediate_message_type):
  1043. """Skips over contents (value or message) of a field.
  1044. Args:
  1045. tokenizer: A tokenizer to parse the field name and values.
  1046. field_name: The field name currently being parsed.
  1047. immediate_message_type: The type of the message immediately containing
  1048. the silent marker.
  1049. """
  1050. # Try to guess the type of this field.
  1051. # If this field is not a message, there should be a ":" between the
  1052. # field name and the field value and also the field value should not
  1053. # start with "{" or "<" which indicates the beginning of a message body.
  1054. # If there is no ":" or there is a "{" or "<" after ":", this field has
  1055. # to be a message or the input is ill-formed.
  1056. if tokenizer.TryConsume(
  1057. ':') and not tokenizer.LookingAt('{') and not tokenizer.LookingAt('<'):
  1058. self._DetectSilentMarker(tokenizer, immediate_message_type, field_name)
  1059. if tokenizer.LookingAt('['):
  1060. self._SkipRepeatedFieldValue(tokenizer, immediate_message_type)
  1061. else:
  1062. self._SkipFieldValue(tokenizer)
  1063. else:
  1064. self._DetectSilentMarker(tokenizer, immediate_message_type, field_name)
  1065. self._SkipFieldMessage(tokenizer, immediate_message_type)
  1066. def _SkipField(self, tokenizer, immediate_message_type):
  1067. """Skips over a complete field (name and value/message).
  1068. Args:
  1069. tokenizer: A tokenizer to parse the field name and values.
  1070. immediate_message_type: The type of the message immediately containing
  1071. the silent marker.
  1072. """
  1073. field_name = ''
  1074. if tokenizer.TryConsume('['):
  1075. # Consume extension or google.protobuf.Any type URL
  1076. field_name += '[' + tokenizer.ConsumeIdentifier()
  1077. num_identifiers = 1
  1078. while tokenizer.TryConsume('.'):
  1079. field_name += '.' + tokenizer.ConsumeIdentifier()
  1080. num_identifiers += 1
  1081. # This is possibly a type URL for an Any message.
  1082. if num_identifiers == 3 and tokenizer.TryConsume('/'):
  1083. field_name += '/' + tokenizer.ConsumeIdentifier()
  1084. while tokenizer.TryConsume('.'):
  1085. field_name += '.' + tokenizer.ConsumeIdentifier()
  1086. tokenizer.Consume(']')
  1087. field_name += ']'
  1088. else:
  1089. field_name += tokenizer.ConsumeIdentifierOrNumber()
  1090. self._SkipFieldContents(tokenizer, field_name, immediate_message_type)
  1091. # For historical reasons, fields may optionally be separated by commas or
  1092. # semicolons.
  1093. if not tokenizer.TryConsume(','):
  1094. tokenizer.TryConsume(';')
  1095. def _SkipFieldMessage(self, tokenizer, immediate_message_type):
  1096. """Skips over a field message.
  1097. Args:
  1098. tokenizer: A tokenizer to parse the field name and values.
  1099. immediate_message_type: The type of the message immediately containing
  1100. the silent marker
  1101. """
  1102. if tokenizer.TryConsume('<'):
  1103. delimiter = '>'
  1104. else:
  1105. tokenizer.Consume('{')
  1106. delimiter = '}'
  1107. while not tokenizer.LookingAt('>') and not tokenizer.LookingAt('}'):
  1108. self._SkipField(tokenizer, immediate_message_type)
  1109. tokenizer.Consume(delimiter)
  1110. def _SkipFieldValue(self, tokenizer):
  1111. """Skips over a field value.
  1112. Args:
  1113. tokenizer: A tokenizer to parse the field name and values.
  1114. Raises:
  1115. ParseError: In case an invalid field value is found.
  1116. """
  1117. if (not tokenizer.TryConsumeByteString()and
  1118. not tokenizer.TryConsumeIdentifier() and
  1119. not _TryConsumeInt64(tokenizer) and
  1120. not _TryConsumeUint64(tokenizer) and
  1121. not tokenizer.TryConsumeFloat()):
  1122. raise ParseError('Invalid field value: ' + tokenizer.token)
  1123. def _SkipRepeatedFieldValue(self, tokenizer, immediate_message_type):
  1124. """Skips over a repeated field value.
  1125. Args:
  1126. tokenizer: A tokenizer to parse the field value.
  1127. """
  1128. tokenizer.Consume('[')
  1129. if not tokenizer.TryConsume(']'):
  1130. while True:
  1131. if tokenizer.LookingAt('<') or tokenizer.LookingAt('{'):
  1132. self._SkipFieldMessage(tokenizer, immediate_message_type)
  1133. else:
  1134. self._SkipFieldValue(tokenizer)
  1135. if tokenizer.TryConsume(']'):
  1136. break
  1137. tokenizer.Consume(',')
  1138. class Tokenizer(object):
  1139. """Protocol buffer text representation tokenizer.
  1140. This class handles the lower level string parsing by splitting it into
  1141. meaningful tokens.
  1142. It was directly ported from the Java protocol buffer API.
  1143. """
  1144. _WHITESPACE = re.compile(r'\s+')
  1145. _COMMENT = re.compile(r'(\s*#.*$)', re.MULTILINE)
  1146. _WHITESPACE_OR_COMMENT = re.compile(r'(\s|(#.*$))+', re.MULTILINE)
  1147. _TOKEN = re.compile('|'.join([
  1148. r'[a-zA-Z_][0-9a-zA-Z_+-]*', # an identifier
  1149. r'([0-9+-]|(\.[0-9]))[0-9a-zA-Z_.+-]*', # a number
  1150. ] + [ # quoted str for each quote mark
  1151. # Avoid backtracking! https://stackoverflow.com/a/844267
  1152. r'{qt}[^{qt}\n\\]*((\\.)+[^{qt}\n\\]*)*({qt}|\\?$)'.format(qt=mark)
  1153. for mark in _QUOTES
  1154. ]))
  1155. _IDENTIFIER = re.compile(r'[^\d\W]\w*')
  1156. _IDENTIFIER_OR_NUMBER = re.compile(r'\w+')
  1157. def __init__(self, lines, skip_comments=True):
  1158. self._position = 0
  1159. self._line = -1
  1160. self._column = 0
  1161. self._token_start = None
  1162. self.token = ''
  1163. self._lines = iter(lines)
  1164. self._current_line = ''
  1165. self._previous_line = 0
  1166. self._previous_column = 0
  1167. self._more_lines = True
  1168. self._skip_comments = skip_comments
  1169. self._whitespace_pattern = (skip_comments and self._WHITESPACE_OR_COMMENT
  1170. or self._WHITESPACE)
  1171. self.contains_silent_marker_before_current_token = False
  1172. self._SkipWhitespace()
  1173. self.NextToken()
  1174. def LookingAt(self, token):
  1175. return self.token == token
  1176. def AtEnd(self):
  1177. """Checks the end of the text was reached.
  1178. Returns:
  1179. True iff the end was reached.
  1180. """
  1181. return not self.token
  1182. def _PopLine(self):
  1183. while len(self._current_line) <= self._column:
  1184. try:
  1185. self._current_line = next(self._lines)
  1186. except StopIteration:
  1187. self._current_line = ''
  1188. self._more_lines = False
  1189. return
  1190. else:
  1191. self._line += 1
  1192. self._column = 0
  1193. def _SkipWhitespace(self):
  1194. while True:
  1195. self._PopLine()
  1196. match = self._whitespace_pattern.match(self._current_line, self._column)
  1197. if not match:
  1198. break
  1199. self.contains_silent_marker_before_current_token = match.group(0) == (
  1200. ' ' + _DEBUG_STRING_SILENT_MARKER)
  1201. length = len(match.group(0))
  1202. self._column += length
  1203. def TryConsume(self, token):
  1204. """Tries to consume a given piece of text.
  1205. Args:
  1206. token: Text to consume.
  1207. Returns:
  1208. True iff the text was consumed.
  1209. """
  1210. if self.token == token:
  1211. self.NextToken()
  1212. return True
  1213. return False
  1214. def Consume(self, token):
  1215. """Consumes a piece of text.
  1216. Args:
  1217. token: Text to consume.
  1218. Raises:
  1219. ParseError: If the text couldn't be consumed.
  1220. """
  1221. if not self.TryConsume(token):
  1222. raise self.ParseError('Expected "%s".' % token)
  1223. def ConsumeComment(self):
  1224. result = self.token
  1225. if not self._COMMENT.match(result):
  1226. raise self.ParseError('Expected comment.')
  1227. self.NextToken()
  1228. return result
  1229. def ConsumeCommentOrTrailingComment(self):
  1230. """Consumes a comment, returns a 2-tuple (trailing bool, comment str)."""
  1231. # Tokenizer initializes _previous_line and _previous_column to 0. As the
  1232. # tokenizer starts, it looks like there is a previous token on the line.
  1233. just_started = self._line == 0 and self._column == 0
  1234. before_parsing = self._previous_line
  1235. comment = self.ConsumeComment()
  1236. # A trailing comment is a comment on the same line than the previous token.
  1237. trailing = (self._previous_line == before_parsing
  1238. and not just_started)
  1239. return trailing, comment
  1240. def TryConsumeIdentifier(self):
  1241. try:
  1242. self.ConsumeIdentifier()
  1243. return True
  1244. except ParseError:
  1245. return False
  1246. def ConsumeIdentifier(self):
  1247. """Consumes protocol message field identifier.
  1248. Returns:
  1249. Identifier string.
  1250. Raises:
  1251. ParseError: If an identifier couldn't be consumed.
  1252. """
  1253. result = self.token
  1254. if not self._IDENTIFIER.match(result):
  1255. raise self.ParseError('Expected identifier.')
  1256. self.NextToken()
  1257. return result
  1258. def TryConsumeIdentifierOrNumber(self):
  1259. try:
  1260. self.ConsumeIdentifierOrNumber()
  1261. return True
  1262. except ParseError:
  1263. return False
  1264. def ConsumeIdentifierOrNumber(self):
  1265. """Consumes protocol message field identifier.
  1266. Returns:
  1267. Identifier string.
  1268. Raises:
  1269. ParseError: If an identifier couldn't be consumed.
  1270. """
  1271. result = self.token
  1272. if not self._IDENTIFIER_OR_NUMBER.match(result):
  1273. raise self.ParseError('Expected identifier or number, got %s.' % result)
  1274. self.NextToken()
  1275. return result
  1276. def TryConsumeInteger(self):
  1277. try:
  1278. self.ConsumeInteger()
  1279. return True
  1280. except ParseError:
  1281. return False
  1282. def ConsumeInteger(self):
  1283. """Consumes an integer number.
  1284. Returns:
  1285. The integer parsed.
  1286. Raises:
  1287. ParseError: If an integer couldn't be consumed.
  1288. """
  1289. try:
  1290. result = _ParseAbstractInteger(self.token)
  1291. except ValueError as e:
  1292. raise self.ParseError(str(e))
  1293. self.NextToken()
  1294. return result
  1295. def TryConsumeFloat(self):
  1296. try:
  1297. self.ConsumeFloat()
  1298. return True
  1299. except ParseError:
  1300. return False
  1301. def ConsumeFloat(self):
  1302. """Consumes an floating point number.
  1303. Returns:
  1304. The number parsed.
  1305. Raises:
  1306. ParseError: If a floating point number couldn't be consumed.
  1307. """
  1308. try:
  1309. result = ParseFloat(self.token)
  1310. except ValueError as e:
  1311. raise self.ParseError(str(e))
  1312. self.NextToken()
  1313. return result
  1314. def ConsumeBool(self):
  1315. """Consumes a boolean value.
  1316. Returns:
  1317. The bool parsed.
  1318. Raises:
  1319. ParseError: If a boolean value couldn't be consumed.
  1320. """
  1321. try:
  1322. result = ParseBool(self.token)
  1323. except ValueError as e:
  1324. raise self.ParseError(str(e))
  1325. self.NextToken()
  1326. return result
  1327. def TryConsumeByteString(self):
  1328. try:
  1329. self.ConsumeByteString()
  1330. return True
  1331. except ParseError:
  1332. return False
  1333. def ConsumeString(self):
  1334. """Consumes a string value.
  1335. Returns:
  1336. The string parsed.
  1337. Raises:
  1338. ParseError: If a string value couldn't be consumed.
  1339. """
  1340. the_bytes = self.ConsumeByteString()
  1341. try:
  1342. return str(the_bytes, 'utf-8')
  1343. except UnicodeDecodeError as e:
  1344. raise self._StringParseError(e)
  1345. def ConsumeByteString(self):
  1346. """Consumes a byte array value.
  1347. Returns:
  1348. The array parsed (as a string).
  1349. Raises:
  1350. ParseError: If a byte array value couldn't be consumed.
  1351. """
  1352. the_list = [self._ConsumeSingleByteString()]
  1353. while self.token and self.token[0] in _QUOTES:
  1354. the_list.append(self._ConsumeSingleByteString())
  1355. return b''.join(the_list)
  1356. def _ConsumeSingleByteString(self):
  1357. """Consume one token of a string literal.
  1358. String literals (whether bytes or text) can come in multiple adjacent
  1359. tokens which are automatically concatenated, like in C or Python. This
  1360. method only consumes one token.
  1361. Returns:
  1362. The token parsed.
  1363. Raises:
  1364. ParseError: When the wrong format data is found.
  1365. """
  1366. text = self.token
  1367. if len(text) < 1 or text[0] not in _QUOTES:
  1368. raise self.ParseError('Expected string but found: %r' % (text,))
  1369. if len(text) < 2 or text[-1] != text[0]:
  1370. raise self.ParseError('String missing ending quote: %r' % (text,))
  1371. try:
  1372. result = text_encoding.CUnescape(text[1:-1])
  1373. except ValueError as e:
  1374. raise self.ParseError(str(e))
  1375. self.NextToken()
  1376. return result
  1377. def ConsumeEnum(self, field):
  1378. try:
  1379. result = ParseEnum(field, self.token)
  1380. except ValueError as e:
  1381. raise self.ParseError(str(e))
  1382. self.NextToken()
  1383. return result
  1384. def ParseErrorPreviousToken(self, message):
  1385. """Creates and *returns* a ParseError for the previously read token.
  1386. Args:
  1387. message: A message to set for the exception.
  1388. Returns:
  1389. A ParseError instance.
  1390. """
  1391. return ParseError(message, self._previous_line + 1,
  1392. self._previous_column + 1)
  1393. def ParseError(self, message):
  1394. """Creates and *returns* a ParseError for the current token."""
  1395. return ParseError('\'' + self._current_line + '\': ' + message,
  1396. self._line + 1, self._column + 1)
  1397. def _StringParseError(self, e):
  1398. return self.ParseError('Couldn\'t parse string: ' + str(e))
  1399. def NextToken(self):
  1400. """Reads the next meaningful token."""
  1401. self._previous_line = self._line
  1402. self._previous_column = self._column
  1403. self.contains_silent_marker_before_current_token = False
  1404. self._column += len(self.token)
  1405. self._SkipWhitespace()
  1406. if not self._more_lines:
  1407. self.token = ''
  1408. return
  1409. match = self._TOKEN.match(self._current_line, self._column)
  1410. if not match and not self._skip_comments:
  1411. match = self._COMMENT.match(self._current_line, self._column)
  1412. if match:
  1413. token = match.group(0)
  1414. self.token = token
  1415. else:
  1416. self.token = self._current_line[self._column]
  1417. # Aliased so it can still be accessed by current visibility violators.
  1418. # TODO: Migrate violators to textformat_tokenizer.
  1419. _Tokenizer = Tokenizer # pylint: disable=invalid-name
  1420. def _ConsumeInt32(tokenizer):
  1421. """Consumes a signed 32bit integer number from tokenizer.
  1422. Args:
  1423. tokenizer: A tokenizer used to parse the number.
  1424. Returns:
  1425. The integer parsed.
  1426. Raises:
  1427. ParseError: If a signed 32bit integer couldn't be consumed.
  1428. """
  1429. return _ConsumeInteger(tokenizer, is_signed=True, is_long=False)
  1430. def _ConsumeUint32(tokenizer):
  1431. """Consumes an unsigned 32bit integer number from tokenizer.
  1432. Args:
  1433. tokenizer: A tokenizer used to parse the number.
  1434. Returns:
  1435. The integer parsed.
  1436. Raises:
  1437. ParseError: If an unsigned 32bit integer couldn't be consumed.
  1438. """
  1439. return _ConsumeInteger(tokenizer, is_signed=False, is_long=False)
  1440. def _TryConsumeInt64(tokenizer):
  1441. try:
  1442. _ConsumeInt64(tokenizer)
  1443. return True
  1444. except ParseError:
  1445. return False
  1446. def _ConsumeInt64(tokenizer):
  1447. """Consumes a signed 32bit integer number from tokenizer.
  1448. Args:
  1449. tokenizer: A tokenizer used to parse the number.
  1450. Returns:
  1451. The integer parsed.
  1452. Raises:
  1453. ParseError: If a signed 32bit integer couldn't be consumed.
  1454. """
  1455. return _ConsumeInteger(tokenizer, is_signed=True, is_long=True)
  1456. def _TryConsumeUint64(tokenizer):
  1457. try:
  1458. _ConsumeUint64(tokenizer)
  1459. return True
  1460. except ParseError:
  1461. return False
  1462. def _ConsumeUint64(tokenizer):
  1463. """Consumes an unsigned 64bit integer number from tokenizer.
  1464. Args:
  1465. tokenizer: A tokenizer used to parse the number.
  1466. Returns:
  1467. The integer parsed.
  1468. Raises:
  1469. ParseError: If an unsigned 64bit integer couldn't be consumed.
  1470. """
  1471. return _ConsumeInteger(tokenizer, is_signed=False, is_long=True)
  1472. def _ConsumeInteger(tokenizer, is_signed=False, is_long=False):
  1473. """Consumes an integer number from tokenizer.
  1474. Args:
  1475. tokenizer: A tokenizer used to parse the number.
  1476. is_signed: True if a signed integer must be parsed.
  1477. is_long: True if a long integer must be parsed.
  1478. Returns:
  1479. The integer parsed.
  1480. Raises:
  1481. ParseError: If an integer with given characteristics couldn't be consumed.
  1482. """
  1483. try:
  1484. result = ParseInteger(tokenizer.token, is_signed=is_signed, is_long=is_long)
  1485. except ValueError as e:
  1486. raise tokenizer.ParseError(str(e))
  1487. tokenizer.NextToken()
  1488. return result
  1489. def ParseInteger(text, is_signed=False, is_long=False):
  1490. """Parses an integer.
  1491. Args:
  1492. text: The text to parse.
  1493. is_signed: True if a signed integer must be parsed.
  1494. is_long: True if a long integer must be parsed.
  1495. Returns:
  1496. The integer value.
  1497. Raises:
  1498. ValueError: Thrown Iff the text is not a valid integer.
  1499. """
  1500. # Do the actual parsing. Exception handling is propagated to caller.
  1501. result = _ParseAbstractInteger(text)
  1502. # Check if the integer is sane. Exceptions handled by callers.
  1503. checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
  1504. checker.CheckValue(result)
  1505. return result
  1506. def _ParseAbstractInteger(text):
  1507. """Parses an integer without checking size/signedness.
  1508. Args:
  1509. text: The text to parse.
  1510. Returns:
  1511. The integer value.
  1512. Raises:
  1513. ValueError: Thrown Iff the text is not a valid integer.
  1514. """
  1515. # Do the actual parsing. Exception handling is propagated to caller.
  1516. orig_text = text
  1517. c_octal_match = re.match(r'(-?)0(\d+)$', text)
  1518. if c_octal_match:
  1519. # Python 3 no longer supports 0755 octal syntax without the 'o', so
  1520. # we always use the '0o' prefix for multi-digit numbers starting with 0.
  1521. text = c_octal_match.group(1) + '0o' + c_octal_match.group(2)
  1522. try:
  1523. return int(text, 0)
  1524. except ValueError:
  1525. raise ValueError('Couldn\'t parse integer: %s' % orig_text)
  1526. def ParseFloat(text):
  1527. """Parse a floating point number.
  1528. Args:
  1529. text: Text to parse.
  1530. Returns:
  1531. The number parsed.
  1532. Raises:
  1533. ValueError: If a floating point number couldn't be parsed.
  1534. """
  1535. if _FLOAT_OCTAL_PREFIX.match(text):
  1536. raise ValueError('Invalid octal float: %s' % text)
  1537. try:
  1538. # Assume Python compatible syntax.
  1539. return float(text)
  1540. except ValueError:
  1541. # Check alternative spellings.
  1542. if _FLOAT_INFINITY.match(text):
  1543. if text[0] == '-':
  1544. return float('-inf')
  1545. else:
  1546. return float('inf')
  1547. elif _FLOAT_NAN.match(text):
  1548. return float('nan')
  1549. else:
  1550. # assume '1.0f' format
  1551. try:
  1552. return float(text.rstrip('fF'))
  1553. except ValueError:
  1554. raise ValueError("Couldn't parse float: %s" % text)
  1555. def ParseBool(text):
  1556. """Parse a boolean value.
  1557. Args:
  1558. text: Text to parse.
  1559. Returns:
  1560. Boolean values parsed
  1561. Raises:
  1562. ValueError: If text is not a valid boolean.
  1563. """
  1564. if text in ('true', 't', '1', 'True'):
  1565. return True
  1566. elif text in ('false', 'f', '0', 'False'):
  1567. return False
  1568. else:
  1569. raise ValueError('Expected "true" or "false".')
  1570. def ParseEnum(field, value):
  1571. """Parse an enum value.
  1572. The value can be specified by a number (the enum value), or by
  1573. a string literal (the enum name).
  1574. Args:
  1575. field: Enum field descriptor.
  1576. value: String value.
  1577. Returns:
  1578. Enum value number.
  1579. Raises:
  1580. ValueError: If the enum value could not be parsed.
  1581. """
  1582. enum_descriptor = field.enum_type
  1583. try:
  1584. number = int(value, 0)
  1585. except ValueError:
  1586. # Identifier.
  1587. enum_value = enum_descriptor.values_by_name.get(value, None)
  1588. if enum_value is None:
  1589. raise ValueError('Enum type "%s" has no value named %s.' %
  1590. (enum_descriptor.full_name, value))
  1591. else:
  1592. if not field.enum_type.is_closed:
  1593. return number
  1594. enum_value = enum_descriptor.values_by_number.get(number, None)
  1595. if enum_value is None:
  1596. raise ValueError('Enum type "%s" has no value with number %d.' %
  1597. (enum_descriptor.full_name, number))
  1598. return enum_value.number