text_format.py 61 KB

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