text_format.py 59 KB

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