text_format.py 65 KB

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