text_format.py 62 KB

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