text_format.py 58 KB

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