Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_shellcomp.py 25KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. # -*- test-case-name: twisted.python.test.test_shellcomp -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. No public APIs are provided by this module. Internal use only.
  6. This module implements dynamic tab-completion for any command that uses
  7. twisted.python.usage. Currently, only zsh is supported. Bash support may
  8. be added in the future.
  9. Maintainer: Eric P. Mangold - twisted AT teratorn DOT org
  10. In order for zsh completion to take place the shell must be able to find an
  11. appropriate "stub" file ("completion function") that invokes this code and
  12. displays the results to the user.
  13. The stub used for Twisted commands is in the file C{twisted-completion.zsh},
  14. which is also included in the official Zsh distribution at
  15. C{Completion/Unix/Command/_twisted}. Use this file as a basis for completion
  16. functions for your own commands. You should only need to change the first line
  17. to something like C{#compdef mycommand}.
  18. The main public documentation exists in the L{twisted.python.usage.Options}
  19. docstring, the L{twisted.python.usage.Completions} docstring, and the
  20. Options howto.
  21. """
  22. import getopt
  23. import inspect
  24. import itertools
  25. from types import MethodType
  26. from typing import Dict, List, Set
  27. from twisted.python import reflect, usage, util
  28. from twisted.python.compat import ioType
  29. def shellComplete(config, cmdName, words, shellCompFile):
  30. """
  31. Perform shell completion.
  32. A completion function (shell script) is generated for the requested
  33. shell and written to C{shellCompFile}, typically C{stdout}. The result
  34. is then eval'd by the shell to produce the desired completions.
  35. @type config: L{twisted.python.usage.Options}
  36. @param config: The L{twisted.python.usage.Options} instance to generate
  37. completions for.
  38. @type cmdName: C{str}
  39. @param cmdName: The name of the command we're generating completions for.
  40. In the case of zsh, this is used to print an appropriate
  41. "#compdef $CMD" line at the top of the output. This is
  42. not necessary for the functionality of the system, but it
  43. helps in debugging, since the output we produce is properly
  44. formed and may be saved in a file and used as a stand-alone
  45. completion function.
  46. @type words: C{list} of C{str}
  47. @param words: The raw command-line words passed to use by the shell
  48. stub function. argv[0] has already been stripped off.
  49. @type shellCompFile: C{file}
  50. @param shellCompFile: The file to write completion data to.
  51. """
  52. # If given a file with unicode semantics, such as sys.stdout on Python 3,
  53. # we must get at the the underlying buffer which has bytes semantics.
  54. if shellCompFile and ioType(shellCompFile) == str:
  55. shellCompFile = shellCompFile.buffer
  56. # shellName is provided for forward-compatibility. It is not used,
  57. # since we currently only support zsh.
  58. shellName, position = words[-1].split(":")
  59. position = int(position)
  60. # zsh gives the completion position ($CURRENT) as a 1-based index,
  61. # and argv[0] has already been stripped off, so we subtract 2 to
  62. # get the real 0-based index.
  63. position -= 2
  64. cWord = words[position]
  65. # since the user may hit TAB at any time, we may have been called with an
  66. # incomplete command-line that would generate getopt errors if parsed
  67. # verbatim. However, we must do *some* parsing in order to determine if
  68. # there is a specific subcommand that we need to provide completion for.
  69. # So, to make the command-line more sane we work backwards from the
  70. # current completion position and strip off all words until we find one
  71. # that "looks" like a subcommand. It may in fact be the argument to a
  72. # normal command-line option, but that won't matter for our purposes.
  73. while position >= 1:
  74. if words[position - 1].startswith("-"):
  75. position -= 1
  76. else:
  77. break
  78. words = words[:position]
  79. subCommands = getattr(config, "subCommands", None)
  80. if subCommands:
  81. # OK, this command supports sub-commands, so lets see if we have been
  82. # given one.
  83. # If the command-line arguments are not valid then we won't be able to
  84. # sanely detect the sub-command, so just generate completions as if no
  85. # sub-command was found.
  86. args = None
  87. try:
  88. opts, args = getopt.getopt(words, config.shortOpt, config.longOpt)
  89. except getopt.error:
  90. pass
  91. if args:
  92. # yes, we have a subcommand. Try to find it.
  93. for (cmd, short, parser, doc) in config.subCommands:
  94. if args[0] == cmd or args[0] == short:
  95. subOptions = parser()
  96. subOptions.parent = config
  97. gen: ZshBuilder = ZshSubcommandBuilder(
  98. subOptions, config, cmdName, shellCompFile
  99. )
  100. gen.write()
  101. return
  102. # sub-command not given, or did not match any knowns sub-command names
  103. genSubs = True
  104. if cWord.startswith("-"):
  105. # optimization: if the current word being completed starts
  106. # with a hyphen then it can't be a sub-command, so skip
  107. # the expensive generation of the sub-command list
  108. genSubs = False
  109. gen = ZshBuilder(config, cmdName, shellCompFile)
  110. gen.write(genSubs=genSubs)
  111. else:
  112. gen = ZshBuilder(config, cmdName, shellCompFile)
  113. gen.write()
  114. class SubcommandAction(usage.Completer):
  115. def _shellCode(self, optName, shellType):
  116. if shellType == usage._ZSH:
  117. return "*::subcmd:->subcmd"
  118. raise NotImplementedError(f"Unknown shellType {shellType!r}")
  119. class ZshBuilder:
  120. """
  121. Constructs zsh code that will complete options for a given usage.Options
  122. instance, possibly including a list of subcommand names.
  123. Completions for options to subcommands won't be generated because this
  124. class will never be used if the user is completing options for a specific
  125. subcommand. (See L{ZshSubcommandBuilder} below)
  126. @type options: L{twisted.python.usage.Options}
  127. @ivar options: The L{twisted.python.usage.Options} instance defined for this
  128. command.
  129. @type cmdName: C{str}
  130. @ivar cmdName: The name of the command we're generating completions for.
  131. @type file: C{file}
  132. @ivar file: The C{file} to write the completion function to. The C{file}
  133. must have L{bytes} I/O semantics.
  134. """
  135. def __init__(self, options, cmdName, file):
  136. self.options = options
  137. self.cmdName = cmdName
  138. self.file = file
  139. def write(self, genSubs=True):
  140. """
  141. Generate the completion function and write it to the output file
  142. @return: L{None}
  143. @type genSubs: C{bool}
  144. @param genSubs: Flag indicating whether or not completions for the list
  145. of subcommand should be generated. Only has an effect
  146. if the C{subCommands} attribute has been defined on the
  147. L{twisted.python.usage.Options} instance.
  148. """
  149. if genSubs and getattr(self.options, "subCommands", None) is not None:
  150. gen = ZshArgumentsGenerator(self.options, self.cmdName, self.file)
  151. gen.extraActions.insert(0, SubcommandAction())
  152. gen.write()
  153. self.file.write(b"local _zsh_subcmds_array\n_zsh_subcmds_array=(\n")
  154. for (cmd, short, parser, desc) in self.options.subCommands:
  155. self.file.write(
  156. b'"' + cmd.encode("utf-8") + b":" + desc.encode("utf-8") + b'"\n'
  157. )
  158. self.file.write(b")\n\n")
  159. self.file.write(b'_describe "sub-command" _zsh_subcmds_array\n')
  160. else:
  161. gen = ZshArgumentsGenerator(self.options, self.cmdName, self.file)
  162. gen.write()
  163. class ZshSubcommandBuilder(ZshBuilder):
  164. """
  165. Constructs zsh code that will complete options for a given usage.Options
  166. instance, and also for a single sub-command. This will only be used in
  167. the case where the user is completing options for a specific subcommand.
  168. @type subOptions: L{twisted.python.usage.Options}
  169. @ivar subOptions: The L{twisted.python.usage.Options} instance defined for
  170. the sub command.
  171. """
  172. def __init__(self, subOptions, *args):
  173. self.subOptions = subOptions
  174. ZshBuilder.__init__(self, *args)
  175. def write(self):
  176. """
  177. Generate the completion function and write it to the output file
  178. @return: L{None}
  179. """
  180. gen = ZshArgumentsGenerator(self.options, self.cmdName, self.file)
  181. gen.extraActions.insert(0, SubcommandAction())
  182. gen.write()
  183. gen = ZshArgumentsGenerator(self.subOptions, self.cmdName, self.file)
  184. gen.write()
  185. class ZshArgumentsGenerator:
  186. """
  187. Generate a call to the zsh _arguments completion function
  188. based on data in a usage.Options instance
  189. The first three instance variables are populated based on constructor
  190. arguments. The remaining non-constructor variables are populated by this
  191. class with data gathered from the C{Options} instance passed in, and its
  192. base classes.
  193. @type options: L{twisted.python.usage.Options}
  194. @ivar options: The L{twisted.python.usage.Options} instance to generate for
  195. @type cmdName: C{str}
  196. @ivar cmdName: The name of the command we're generating completions for.
  197. @type file: C{file}
  198. @ivar file: The C{file} to write the completion function to. The C{file}
  199. must have L{bytes} I/O semantics.
  200. @type descriptions: C{dict}
  201. @ivar descriptions: A dict mapping long option names to alternate
  202. descriptions. When this variable is defined, the descriptions
  203. contained here will override those descriptions provided in the
  204. optFlags and optParameters variables.
  205. @type multiUse: C{list}
  206. @ivar multiUse: An iterable containing those long option names which may
  207. appear on the command line more than once. By default, options will
  208. only be completed one time.
  209. @type mutuallyExclusive: C{list} of C{tuple}
  210. @ivar mutuallyExclusive: A sequence of sequences, with each sub-sequence
  211. containing those long option names that are mutually exclusive. That is,
  212. those options that cannot appear on the command line together.
  213. @type optActions: C{dict}
  214. @ivar optActions: A dict mapping long option names to shell "actions".
  215. These actions define what may be completed as the argument to the
  216. given option, and should be given as instances of
  217. L{twisted.python.usage.Completer}.
  218. Callables may instead be given for the values in this dict. The
  219. callable should accept no arguments, and return a C{Completer}
  220. instance used as the action.
  221. @type extraActions: C{list} of C{twisted.python.usage.Completer}
  222. @ivar extraActions: Extra arguments are those arguments typically
  223. appearing at the end of the command-line, which are not associated
  224. with any particular named option. That is, the arguments that are
  225. given to the parseArgs() method of your usage.Options subclass.
  226. """
  227. def __init__(self, options, cmdName, file):
  228. self.options = options
  229. self.cmdName = cmdName
  230. self.file = file
  231. self.descriptions = {}
  232. self.multiUse = set()
  233. self.mutuallyExclusive = []
  234. self.optActions = {}
  235. self.extraActions = []
  236. for cls in reversed(inspect.getmro(options.__class__)):
  237. data = getattr(cls, "compData", None)
  238. if data:
  239. self.descriptions.update(data.descriptions)
  240. self.optActions.update(data.optActions)
  241. self.multiUse.update(data.multiUse)
  242. self.mutuallyExclusive.extend(data.mutuallyExclusive)
  243. # I don't see any sane way to aggregate extraActions, so just
  244. # take the one at the top of the MRO (nearest the `options'
  245. # instance).
  246. if data.extraActions:
  247. self.extraActions = data.extraActions
  248. aCL = reflect.accumulateClassList
  249. optFlags: List[List[object]] = []
  250. optParams: List[List[object]] = []
  251. aCL(options.__class__, "optFlags", optFlags)
  252. aCL(options.__class__, "optParameters", optParams)
  253. for i, optList in enumerate(optFlags):
  254. if len(optList) != 3:
  255. optFlags[i] = util.padTo(3, optList)
  256. for i, optList in enumerate(optParams):
  257. if len(optList) != 5:
  258. optParams[i] = util.padTo(5, optList)
  259. self.optFlags = optFlags
  260. self.optParams = optParams
  261. paramNameToDefinition = {}
  262. for optList in optParams:
  263. paramNameToDefinition[optList[0]] = optList[1:]
  264. self.paramNameToDefinition = paramNameToDefinition
  265. flagNameToDefinition = {}
  266. for optList in optFlags:
  267. flagNameToDefinition[optList[0]] = optList[1:]
  268. self.flagNameToDefinition = flagNameToDefinition
  269. allOptionsNameToDefinition = {}
  270. allOptionsNameToDefinition.update(paramNameToDefinition)
  271. allOptionsNameToDefinition.update(flagNameToDefinition)
  272. self.allOptionsNameToDefinition = allOptionsNameToDefinition
  273. self.addAdditionalOptions()
  274. # makes sure none of the Completions metadata references
  275. # option names that don't exist. (great for catching typos)
  276. self.verifyZshNames()
  277. self.excludes = self.makeExcludesDict()
  278. def write(self):
  279. """
  280. Write the zsh completion code to the file given to __init__
  281. @return: L{None}
  282. """
  283. self.writeHeader()
  284. self.writeExtras()
  285. self.writeOptions()
  286. self.writeFooter()
  287. def writeHeader(self):
  288. """
  289. This is the start of the code that calls _arguments
  290. @return: L{None}
  291. """
  292. self.file.write(
  293. b"#compdef " + self.cmdName.encode("utf-8") + b"\n\n"
  294. b'_arguments -s -A "-*" \\\n'
  295. )
  296. def writeOptions(self):
  297. """
  298. Write out zsh code for each option in this command
  299. @return: L{None}
  300. """
  301. optNames = list(self.allOptionsNameToDefinition.keys())
  302. optNames.sort()
  303. for longname in optNames:
  304. self.writeOpt(longname)
  305. def writeExtras(self):
  306. """
  307. Write out completion information for extra arguments appearing on the
  308. command-line. These are extra positional arguments not associated
  309. with a named option. That is, the stuff that gets passed to
  310. Options.parseArgs().
  311. @return: L{None}
  312. @raise ValueError: If C{Completer} with C{repeat=True} is found and
  313. is not the last item in the C{extraActions} list.
  314. """
  315. for i, action in enumerate(self.extraActions):
  316. # a repeatable action must be the last action in the list
  317. if action._repeat and i != len(self.extraActions) - 1:
  318. raise ValueError(
  319. "Completer with repeat=True must be "
  320. "last item in Options.extraActions"
  321. )
  322. self.file.write(escape(action._shellCode("", usage._ZSH)).encode("utf-8"))
  323. self.file.write(b" \\\n")
  324. def writeFooter(self):
  325. """
  326. Write the last bit of code that finishes the call to _arguments
  327. @return: L{None}
  328. """
  329. self.file.write(b"&& return 0\n")
  330. def verifyZshNames(self):
  331. """
  332. Ensure that none of the option names given in the metadata are typoed
  333. @return: L{None}
  334. @raise ValueError: If unknown option names have been found.
  335. """
  336. def err(name):
  337. raise ValueError(
  338. 'Unknown option name "%s" found while\n'
  339. "examining Completions instances on %s" % (name, self.options)
  340. )
  341. for name in itertools.chain(self.descriptions, self.optActions, self.multiUse):
  342. if name not in self.allOptionsNameToDefinition:
  343. err(name)
  344. for seq in self.mutuallyExclusive:
  345. for name in seq:
  346. if name not in self.allOptionsNameToDefinition:
  347. err(name)
  348. def excludeStr(self, longname, buildShort=False):
  349. """
  350. Generate an "exclusion string" for the given option
  351. @type longname: C{str}
  352. @param longname: The long option name (e.g. "verbose" instead of "v")
  353. @type buildShort: C{bool}
  354. @param buildShort: May be True to indicate we're building an excludes
  355. string for the short option that corresponds to the given long opt.
  356. @return: The generated C{str}
  357. """
  358. if longname in self.excludes:
  359. exclusions = self.excludes[longname].copy()
  360. else:
  361. exclusions = set()
  362. # if longname isn't a multiUse option (can't appear on the cmd line more
  363. # than once), then we have to exclude the short option if we're
  364. # building for the long option, and vice versa.
  365. if longname not in self.multiUse:
  366. if buildShort is False:
  367. short = self.getShortOption(longname)
  368. if short is not None:
  369. exclusions.add(short)
  370. else:
  371. exclusions.add(longname)
  372. if not exclusions:
  373. return ""
  374. strings = []
  375. for optName in exclusions:
  376. if len(optName) == 1:
  377. # short option
  378. strings.append("-" + optName)
  379. else:
  380. strings.append("--" + optName)
  381. strings.sort() # need deterministic order for reliable unit-tests
  382. return "(%s)" % " ".join(strings)
  383. def makeExcludesDict(self) -> Dict[str, Set[str]]:
  384. """
  385. @return: A C{dict} that maps each option name appearing in
  386. self.mutuallyExclusive to a set of those option names that is it
  387. mutually exclusive with (can't appear on the cmd line with).
  388. """
  389. # create a mapping of long option name -> single character name
  390. longToShort = {}
  391. for optList in itertools.chain(self.optParams, self.optFlags):
  392. if optList[1] != None:
  393. longToShort[optList[0]] = optList[1]
  394. excludes: Dict[str, Set[str]] = {}
  395. for lst in self.mutuallyExclusive:
  396. for i, longname in enumerate(lst):
  397. tmp = set(lst[:i] + lst[i + 1 :])
  398. for name in tmp.copy():
  399. if name in longToShort:
  400. tmp.add(longToShort[name])
  401. if longname in excludes:
  402. excludes[longname] = excludes[longname].union(tmp)
  403. else:
  404. excludes[longname] = tmp
  405. return excludes
  406. def writeOpt(self, longname):
  407. """
  408. Write out the zsh code for the given argument. This is just part of the
  409. one big call to _arguments
  410. @type longname: C{str}
  411. @param longname: The long option name (e.g. "verbose" instead of "v")
  412. @return: L{None}
  413. """
  414. if longname in self.flagNameToDefinition:
  415. # It's a flag option. Not one that takes a parameter.
  416. longField = "--%s" % longname
  417. else:
  418. longField = "--%s=" % longname
  419. short = self.getShortOption(longname)
  420. if short != None:
  421. shortField = "-" + short
  422. else:
  423. shortField = ""
  424. descr = self.getDescription(longname)
  425. descriptionField = descr.replace("[", r"\[")
  426. descriptionField = descriptionField.replace("]", r"\]")
  427. descriptionField = "[%s]" % descriptionField
  428. actionField = self.getAction(longname)
  429. if longname in self.multiUse:
  430. multiField = "*"
  431. else:
  432. multiField = ""
  433. longExclusionsField = self.excludeStr(longname)
  434. if short:
  435. # we have to write an extra line for the short option if we have one
  436. shortExclusionsField = self.excludeStr(longname, buildShort=True)
  437. self.file.write(
  438. escape(
  439. "%s%s%s%s%s"
  440. % (
  441. shortExclusionsField,
  442. multiField,
  443. shortField,
  444. descriptionField,
  445. actionField,
  446. )
  447. ).encode("utf-8")
  448. )
  449. self.file.write(b" \\\n")
  450. self.file.write(
  451. escape(
  452. "%s%s%s%s%s"
  453. % (
  454. longExclusionsField,
  455. multiField,
  456. longField,
  457. descriptionField,
  458. actionField,
  459. )
  460. ).encode("utf-8")
  461. )
  462. self.file.write(b" \\\n")
  463. def getAction(self, longname):
  464. """
  465. Return a zsh "action" string for the given argument
  466. @return: C{str}
  467. """
  468. if longname in self.optActions:
  469. if callable(self.optActions[longname]):
  470. action = self.optActions[longname]()
  471. else:
  472. action = self.optActions[longname]
  473. return action._shellCode(longname, usage._ZSH)
  474. if longname in self.paramNameToDefinition:
  475. return f":{longname}:_files"
  476. return ""
  477. def getDescription(self, longname):
  478. """
  479. Return the description to be used for this argument
  480. @return: C{str}
  481. """
  482. # check if we have an alternate descr for this arg, and if so use it
  483. if longname in self.descriptions:
  484. return self.descriptions[longname]
  485. # otherwise we have to get it from the optFlags or optParams
  486. try:
  487. descr = self.flagNameToDefinition[longname][1]
  488. except KeyError:
  489. try:
  490. descr = self.paramNameToDefinition[longname][2]
  491. except KeyError:
  492. descr = None
  493. if descr is not None:
  494. return descr
  495. # let's try to get it from the opt_foo method doc string if there is one
  496. longMangled = longname.replace("-", "_") # this is what t.p.usage does
  497. obj = getattr(self.options, "opt_%s" % longMangled, None)
  498. if obj is not None:
  499. descr = descrFromDoc(obj)
  500. if descr is not None:
  501. return descr
  502. return longname # we really ought to have a good description to use
  503. def getShortOption(self, longname):
  504. """
  505. Return the short option letter or None
  506. @return: C{str} or L{None}
  507. """
  508. optList = self.allOptionsNameToDefinition[longname]
  509. return optList[0] or None
  510. def addAdditionalOptions(self) -> None:
  511. """
  512. Add additional options to the optFlags and optParams lists.
  513. These will be defined by 'opt_foo' methods of the Options subclass
  514. @return: L{None}
  515. """
  516. methodsDict: Dict[str, MethodType] = {}
  517. reflect.accumulateMethods(self.options, methodsDict, "opt_")
  518. methodToShort = {}
  519. for name in methodsDict.copy():
  520. if len(name) == 1:
  521. methodToShort[methodsDict[name]] = name
  522. del methodsDict[name]
  523. for methodName, methodObj in methodsDict.items():
  524. longname = methodName.replace("_", "-") # t.p.usage does this
  525. # if this option is already defined by the optFlags or
  526. # optParameters then we don't want to override that data
  527. if longname in self.allOptionsNameToDefinition:
  528. continue
  529. descr = self.getDescription(longname)
  530. short = None
  531. if methodObj in methodToShort:
  532. short = methodToShort[methodObj]
  533. reqArgs = methodObj.__func__.__code__.co_argcount
  534. if reqArgs == 2:
  535. self.optParams.append([longname, short, None, descr])
  536. self.paramNameToDefinition[longname] = [short, None, descr]
  537. self.allOptionsNameToDefinition[longname] = [short, None, descr]
  538. else:
  539. # reqArgs must equal 1. self.options would have failed
  540. # to instantiate if it had opt_ methods with bad signatures.
  541. self.optFlags.append([longname, short, descr])
  542. self.flagNameToDefinition[longname] = [short, descr]
  543. self.allOptionsNameToDefinition[longname] = [short, None, descr]
  544. def descrFromDoc(obj):
  545. """
  546. Generate an appropriate description from docstring of the given object
  547. """
  548. if obj.__doc__ is None or obj.__doc__.isspace():
  549. return None
  550. lines = [x.strip() for x in obj.__doc__.split("\n") if x and not x.isspace()]
  551. return " ".join(lines)
  552. def escape(x):
  553. """
  554. Shell escape the given string
  555. Implementation borrowed from now-deprecated commands.mkarg() in the stdlib
  556. """
  557. if "'" not in x:
  558. return "'" + x + "'"
  559. s = '"'
  560. for c in x:
  561. if c in '\\$"`':
  562. s = s + "\\"
  563. s = s + c
  564. s = s + '"'
  565. return s