sexp.nim 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf, Dominik Picheta
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## **Note:** Import ``nimsuggest/sexp`` to use this module
  10. import
  11. hashes, strutils, lexbase, streams, unicode, macros
  12. type
  13. SexpEventKind* = enum ## enumeration of all events that may occur when parsing
  14. sexpError, ## an error occurred during parsing
  15. sexpEof, ## end of file reached
  16. sexpString, ## a string literal
  17. sexpSymbol, ## a symbol
  18. sexpInt, ## an integer literal
  19. sexpFloat, ## a float literal
  20. sexpNil, ## the value ``nil``
  21. sexpDot, ## the dot to separate car/cdr
  22. sexpListStart, ## start of a list: the ``(`` token
  23. sexpListEnd, ## end of a list: the ``)`` token
  24. TTokKind = enum # must be synchronized with SexpEventKind!
  25. tkError,
  26. tkEof,
  27. tkString,
  28. tkSymbol,
  29. tkInt,
  30. tkFloat,
  31. tkNil,
  32. tkDot,
  33. tkParensLe,
  34. tkParensRi
  35. tkSpace
  36. SexpError* = enum ## enumeration that lists all errors that can occur
  37. errNone, ## no error
  38. errInvalidToken, ## invalid token
  39. errParensRiExpected, ## ``)`` expected
  40. errQuoteExpected, ## ``"`` expected
  41. errEofExpected, ## EOF expected
  42. SexpParser* = object of BaseLexer ## the parser object.
  43. a: string
  44. tok: TTokKind
  45. kind: SexpEventKind
  46. err: SexpError
  47. const
  48. errorMessages: array[SexpError, string] = [
  49. "no error",
  50. "invalid token",
  51. "')' expected",
  52. "'\"' or \"'\" expected",
  53. "EOF expected",
  54. ]
  55. tokToStr: array[TTokKind, string] = [
  56. "invalid token",
  57. "EOF",
  58. "string literal",
  59. "symbol",
  60. "int literal",
  61. "float literal",
  62. "nil",
  63. ".",
  64. "(", ")", "space"
  65. ]
  66. proc close*(my: var SexpParser) {.inline.} =
  67. ## closes the parser `my` and its associated input stream.
  68. lexbase.close(my)
  69. proc str*(my: SexpParser): string {.inline.} =
  70. ## returns the character data for the events: ``sexpInt``, ``sexpFloat``,
  71. ## ``sexpString``
  72. assert(my.kind in {sexpInt, sexpFloat, sexpString})
  73. result = my.a
  74. proc getInt*(my: SexpParser): BiggestInt {.inline.} =
  75. ## returns the number for the event: ``sexpInt``
  76. assert(my.kind == sexpInt)
  77. result = parseBiggestInt(my.a)
  78. proc getFloat*(my: SexpParser): float {.inline.} =
  79. ## returns the number for the event: ``sexpFloat``
  80. assert(my.kind == sexpFloat)
  81. result = parseFloat(my.a)
  82. proc kind*(my: SexpParser): SexpEventKind {.inline.} =
  83. ## returns the current event type for the SEXP parser
  84. result = my.kind
  85. proc getColumn*(my: SexpParser): int {.inline.} =
  86. ## get the current column the parser has arrived at.
  87. result = getColNumber(my, my.bufpos)
  88. proc getLine*(my: SexpParser): int {.inline.} =
  89. ## get the current line the parser has arrived at.
  90. result = my.lineNumber
  91. proc errorMsg*(my: SexpParser): string =
  92. ## returns a helpful error message for the event ``sexpError``
  93. assert(my.kind == sexpError)
  94. result = "($1, $2) Error: $3" % [$getLine(my), $getColumn(my), errorMessages[my.err]]
  95. proc errorMsgExpected*(my: SexpParser, e: string): string =
  96. ## returns an error message "`e` expected" in the same format as the
  97. ## other error messages
  98. result = "($1, $2) Error: $3" % [$getLine(my), $getColumn(my), e & " expected"]
  99. proc handleHexChar(c: char, x: var int): bool =
  100. result = true # Success
  101. case c
  102. of '0'..'9': x = (x shl 4) or (ord(c) - ord('0'))
  103. of 'a'..'f': x = (x shl 4) or (ord(c) - ord('a') + 10)
  104. of 'A'..'F': x = (x shl 4) or (ord(c) - ord('A') + 10)
  105. else: result = false # error
  106. proc parseString(my: var SexpParser): TTokKind =
  107. result = tkString
  108. var pos = my.bufpos + 1
  109. while true:
  110. case my.buf[pos]
  111. of '\0':
  112. my.err = errQuoteExpected
  113. result = tkError
  114. break
  115. of '"':
  116. inc(pos)
  117. break
  118. of '\\':
  119. case my.buf[pos+1]
  120. of '\\', '"', '\'', '/':
  121. add(my.a, my.buf[pos+1])
  122. inc(pos, 2)
  123. of 'b':
  124. add(my.a, '\b')
  125. inc(pos, 2)
  126. of 'f':
  127. add(my.a, '\f')
  128. inc(pos, 2)
  129. of 'n':
  130. add(my.a, '\L')
  131. inc(pos, 2)
  132. of 'r':
  133. add(my.a, '\C')
  134. inc(pos, 2)
  135. of 't':
  136. add(my.a, '\t')
  137. inc(pos, 2)
  138. of 'u':
  139. inc(pos, 2)
  140. var r: int
  141. if handleHexChar(my.buf[pos], r): inc(pos)
  142. if handleHexChar(my.buf[pos], r): inc(pos)
  143. if handleHexChar(my.buf[pos], r): inc(pos)
  144. if handleHexChar(my.buf[pos], r): inc(pos)
  145. add(my.a, toUTF8(Rune(r)))
  146. else:
  147. # don't bother with the error
  148. add(my.a, my.buf[pos])
  149. inc(pos)
  150. of '\c':
  151. pos = lexbase.handleCR(my, pos)
  152. add(my.a, '\c')
  153. of '\L':
  154. pos = lexbase.handleLF(my, pos)
  155. add(my.a, '\L')
  156. else:
  157. add(my.a, my.buf[pos])
  158. inc(pos)
  159. my.bufpos = pos # store back
  160. proc parseNumber(my: var SexpParser) =
  161. var pos = my.bufpos
  162. if my.buf[pos] == '-':
  163. add(my.a, '-')
  164. inc(pos)
  165. if my.buf[pos] == '.':
  166. add(my.a, "0.")
  167. inc(pos)
  168. else:
  169. while my.buf[pos] in Digits:
  170. add(my.a, my.buf[pos])
  171. inc(pos)
  172. if my.buf[pos] == '.':
  173. add(my.a, '.')
  174. inc(pos)
  175. # digits after the dot:
  176. while my.buf[pos] in Digits:
  177. add(my.a, my.buf[pos])
  178. inc(pos)
  179. if my.buf[pos] in {'E', 'e'}:
  180. add(my.a, my.buf[pos])
  181. inc(pos)
  182. if my.buf[pos] in {'+', '-'}:
  183. add(my.a, my.buf[pos])
  184. inc(pos)
  185. while my.buf[pos] in Digits:
  186. add(my.a, my.buf[pos])
  187. inc(pos)
  188. my.bufpos = pos
  189. proc parseSymbol(my: var SexpParser) =
  190. var pos = my.bufpos
  191. if my.buf[pos] in IdentStartChars:
  192. while my.buf[pos] in IdentChars:
  193. add(my.a, my.buf[pos])
  194. inc(pos)
  195. my.bufpos = pos
  196. proc getTok(my: var SexpParser): TTokKind =
  197. setLen(my.a, 0)
  198. case my.buf[my.bufpos]
  199. of '-', '0'..'9': # numbers that start with a . are not parsed
  200. # correctly.
  201. parseNumber(my)
  202. if {'.', 'e', 'E'} in my.a:
  203. result = tkFloat
  204. else:
  205. result = tkInt
  206. of '"': #" # gotta fix nim-mode
  207. result = parseString(my)
  208. of '(':
  209. inc(my.bufpos)
  210. result = tkParensLe
  211. of ')':
  212. inc(my.bufpos)
  213. result = tkParensRi
  214. of '\0':
  215. result = tkEof
  216. of 'a'..'z', 'A'..'Z', '_':
  217. parseSymbol(my)
  218. if my.a == "nil":
  219. result = tkNil
  220. else:
  221. result = tkSymbol
  222. of ' ':
  223. result = tkSpace
  224. inc(my.bufpos)
  225. of '.':
  226. result = tkDot
  227. inc(my.bufpos)
  228. else:
  229. inc(my.bufpos)
  230. result = tkError
  231. my.tok = result
  232. # ------------- higher level interface ---------------------------------------
  233. type
  234. SexpNodeKind* = enum ## possible SEXP node types
  235. SNil,
  236. SInt,
  237. SFloat,
  238. SString,
  239. SSymbol,
  240. SList,
  241. SCons
  242. SexpNode* = ref SexpNodeObj ## SEXP node
  243. SexpNodeObj* {.acyclic.} = object
  244. case kind*: SexpNodeKind
  245. of SString:
  246. str*: string
  247. of SSymbol:
  248. symbol*: string
  249. of SInt:
  250. num*: BiggestInt
  251. of SFloat:
  252. fnum*: float
  253. of SList:
  254. elems*: seq[SexpNode]
  255. of SCons:
  256. car: SexpNode
  257. cdr: SexpNode
  258. of SNil:
  259. discard
  260. Cons = tuple[car: SexpNode, cdr: SexpNode]
  261. SexpParsingError* = object of ValueError ## is raised for a SEXP error
  262. proc raiseParseErr*(p: SexpParser, msg: string) {.noinline, noreturn.} =
  263. ## raises an `ESexpParsingError` exception.
  264. raise newException(SexpParsingError, errorMsgExpected(p, msg))
  265. proc newSString*(s: string): SexpNode =
  266. ## Creates a new `SString SexpNode`.
  267. result = SexpNode(kind: SString, str: s)
  268. proc newSStringMove(s: string): SexpNode =
  269. result = SexpNode(kind: SString)
  270. shallowCopy(result.str, s)
  271. proc newSInt*(n: BiggestInt): SexpNode =
  272. ## Creates a new `SInt SexpNode`.
  273. result = SexpNode(kind: SInt, num: n)
  274. proc newSFloat*(n: float): SexpNode =
  275. ## Creates a new `SFloat SexpNode`.
  276. result = SexpNode(kind: SFloat, fnum: n)
  277. proc newSNil*(): SexpNode =
  278. ## Creates a new `SNil SexpNode`.
  279. result = SexpNode(kind: SNil)
  280. proc newSCons*(car, cdr: SexpNode): SexpNode =
  281. ## Creates a new `SCons SexpNode`
  282. result = SexpNode(kind: SCons, car: car, cdr: cdr)
  283. proc newSList*(): SexpNode =
  284. ## Creates a new `SList SexpNode`
  285. result = SexpNode(kind: SList, elems: @[])
  286. proc newSSymbol*(s: string): SexpNode =
  287. result = SexpNode(kind: SSymbol, symbol: s)
  288. proc newSSymbolMove(s: string): SexpNode =
  289. result = SexpNode(kind: SSymbol)
  290. shallowCopy(result.symbol, s)
  291. proc getStr*(n: SexpNode, default: string = ""): string =
  292. ## Retrieves the string value of a `SString SexpNode`.
  293. ##
  294. ## Returns ``default`` if ``n`` is not a ``SString``.
  295. if n.kind != SString: return default
  296. else: return n.str
  297. proc getNum*(n: SexpNode, default: BiggestInt = 0): BiggestInt =
  298. ## Retrieves the int value of a `SInt SexpNode`.
  299. ##
  300. ## Returns ``default`` if ``n`` is not a ``SInt``.
  301. if n.kind != SInt: return default
  302. else: return n.num
  303. proc getFNum*(n: SexpNode, default: float = 0.0): float =
  304. ## Retrieves the float value of a `SFloat SexpNode`.
  305. ##
  306. ## Returns ``default`` if ``n`` is not a ``SFloat``.
  307. if n.kind != SFloat: return default
  308. else: return n.fnum
  309. proc getSymbol*(n: SexpNode, default: string = ""): string =
  310. ## Retrieves the int value of a `SList SexpNode`.
  311. ##
  312. ## Returns ``default`` if ``n`` is not a ``SList``.
  313. if n.kind != SSymbol: return default
  314. else: return n.symbol
  315. proc getElems*(n: SexpNode, default: seq[SexpNode] = @[]): seq[SexpNode] =
  316. ## Retrieves the int value of a `SList SexpNode`.
  317. ##
  318. ## Returns ``default`` if ``n`` is not a ``SList``.
  319. if n.kind == SNil: return @[]
  320. elif n.kind != SList: return default
  321. else: return n.elems
  322. proc getCons*(n: SexpNode, defaults: Cons = (newSNil(), newSNil())): Cons =
  323. ## Retrieves the cons value of a `SList SexpNode`.
  324. ##
  325. ## Returns ``default`` if ``n`` is not a ``SList``.
  326. if n.kind == SCons: return (n.car, n.cdr)
  327. elif n.kind == SList: return (n.elems[0], n.elems[1])
  328. else: return defaults
  329. proc sexp*(s: string): SexpNode =
  330. ## Generic constructor for SEXP data. Creates a new `SString SexpNode`.
  331. result = SexpNode(kind: SString, str: s)
  332. proc sexp*(n: BiggestInt): SexpNode =
  333. ## Generic constructor for SEXP data. Creates a new `SInt SexpNode`.
  334. result = SexpNode(kind: SInt, num: n)
  335. proc sexp*(n: float): SexpNode =
  336. ## Generic constructor for SEXP data. Creates a new `SFloat SexpNode`.
  337. result = SexpNode(kind: SFloat, fnum: n)
  338. proc sexp*(b: bool): SexpNode =
  339. ## Generic constructor for SEXP data. Creates a new `SSymbol
  340. ## SexpNode` with value t or `SNil SexpNode`.
  341. if b:
  342. result = SexpNode(kind: SSymbol, symbol: "t")
  343. else:
  344. result = SexpNode(kind: SNil)
  345. proc sexp*(elements: openArray[SexpNode]): SexpNode =
  346. ## Generic constructor for SEXP data. Creates a new `SList SexpNode`
  347. result = SexpNode(kind: SList)
  348. newSeq(result.elems, elements.len)
  349. for i, p in pairs(elements): result.elems[i] = p
  350. proc sexp*(s: SexpNode): SexpNode =
  351. result = s
  352. proc toSexp(x: NimNode): NimNode {.compileTime.} =
  353. case x.kind
  354. of nnkBracket:
  355. result = newNimNode(nnkBracket)
  356. for i in 0 ..< x.len:
  357. result.add(toSexp(x[i]))
  358. else:
  359. result = x
  360. result = prefix(result, "sexp")
  361. macro convertSexp*(x: untyped): untyped =
  362. ## Convert an expression to a SexpNode directly, without having to specify
  363. ## `%` for every element.
  364. result = toSexp(x)
  365. proc `==`* (a,b: SexpNode): bool =
  366. ## Check two nodes for equality
  367. if a.isNil:
  368. if b.isNil: return true
  369. return false
  370. elif b.isNil or a.kind != b.kind:
  371. return false
  372. else:
  373. return case a.kind
  374. of SString:
  375. a.str == b.str
  376. of SInt:
  377. a.num == b.num
  378. of SFloat:
  379. a.fnum == b.fnum
  380. of SNil:
  381. true
  382. of SList:
  383. a.elems == b.elems
  384. of SSymbol:
  385. a.symbol == b.symbol
  386. of SCons:
  387. a.car == b.car and a.cdr == b.cdr
  388. proc hash* (n:SexpNode): Hash =
  389. ## Compute the hash for a SEXP node
  390. case n.kind
  391. of SList:
  392. result = hash(n.elems)
  393. of SInt:
  394. result = hash(n.num)
  395. of SFloat:
  396. result = hash(n.fnum)
  397. of SString:
  398. result = hash(n.str)
  399. of SNil:
  400. result = hash(0)
  401. of SSymbol:
  402. result = hash(n.symbol)
  403. of SCons:
  404. result = hash(n.car) !& hash(n.cdr)
  405. proc len*(n: SexpNode): int =
  406. ## If `n` is a `SList`, it returns the number of elements.
  407. ## If `n` is a `JObject`, it returns the number of pairs.
  408. ## Else it returns 0.
  409. case n.kind
  410. of SList: result = n.elems.len
  411. else: discard
  412. proc `[]`*(node: SexpNode, index: int): SexpNode =
  413. ## Gets the node at `index` in a List. Result is undefined if `index`
  414. ## is out of bounds
  415. assert(not isNil(node))
  416. assert(node.kind == SList)
  417. return node.elems[index]
  418. proc add*(father, child: SexpNode) =
  419. ## Adds `child` to a SList node `father`.
  420. assert father.kind == SList
  421. father.elems.add(child)
  422. # ------------- pretty printing ----------------------------------------------
  423. proc indent(s: var string, i: int) =
  424. s.add(spaces(i))
  425. proc newIndent(curr, indent: int, ml: bool): int =
  426. if ml: return curr + indent
  427. else: return indent
  428. proc nl(s: var string, ml: bool) =
  429. if ml: s.add("\n")
  430. proc escapeJson*(s: string): string =
  431. ## Converts a string `s` to its JSON representation.
  432. result = newStringOfCap(s.len + s.len shr 3)
  433. result.add("\"")
  434. for x in runes(s):
  435. var r = int(x)
  436. if r >= 32 and r <= 127:
  437. var c = chr(r)
  438. case c
  439. of '"': result.add("\\\"") #" # gotta fix nim-mode
  440. of '\\': result.add("\\\\")
  441. else: result.add(c)
  442. else:
  443. result.add("\\u")
  444. result.add(toHex(r, 4))
  445. result.add("\"")
  446. proc copy*(p: SexpNode): SexpNode =
  447. ## Performs a deep copy of `a`.
  448. case p.kind
  449. of SString:
  450. result = newSString(p.str)
  451. of SInt:
  452. result = newSInt(p.num)
  453. of SFloat:
  454. result = newSFloat(p.fnum)
  455. of SNil:
  456. result = newSNil()
  457. of SSymbol:
  458. result = newSSymbol(p.symbol)
  459. of SList:
  460. result = newSList()
  461. for i in items(p.elems):
  462. result.elems.add(copy(i))
  463. of SCons:
  464. result = newSCons(copy(p.car), copy(p.cdr))
  465. proc toPretty(result: var string, node: SexpNode, indent = 2, ml = true,
  466. lstArr = false, currIndent = 0) =
  467. case node.kind
  468. of SString:
  469. if lstArr: result.indent(currIndent)
  470. result.add(escapeJson(node.str))
  471. of SInt:
  472. if lstArr: result.indent(currIndent)
  473. result.addInt(node.num)
  474. of SFloat:
  475. if lstArr: result.indent(currIndent)
  476. result.addFloat(node.fnum)
  477. of SNil:
  478. if lstArr: result.indent(currIndent)
  479. result.add("nil")
  480. of SSymbol:
  481. if lstArr: result.indent(currIndent)
  482. result.add(node.symbol)
  483. of SList:
  484. if lstArr: result.indent(currIndent)
  485. if len(node.elems) != 0:
  486. result.add("(")
  487. result.nl(ml)
  488. for i in 0..len(node.elems)-1:
  489. if i > 0:
  490. result.add(" ")
  491. result.nl(ml) # New Line
  492. toPretty(result, node.elems[i], indent, ml,
  493. true, newIndent(currIndent, indent, ml))
  494. result.nl(ml)
  495. result.indent(currIndent)
  496. result.add(")")
  497. else: result.add("nil")
  498. of SCons:
  499. if lstArr: result.indent(currIndent)
  500. result.add("(")
  501. toPretty(result, node.car, indent, ml,
  502. true, newIndent(currIndent, indent, ml))
  503. result.add(" . ")
  504. toPretty(result, node.cdr, indent, ml,
  505. true, newIndent(currIndent, indent, ml))
  506. result.add(")")
  507. proc pretty*(node: SexpNode, indent = 2): string =
  508. ## Converts `node` to its Sexp Representation, with indentation and
  509. ## on multiple lines.
  510. result = ""
  511. toPretty(result, node, indent)
  512. proc `$`*(node: SexpNode): string =
  513. ## Converts `node` to its SEXP Representation on one line.
  514. result = ""
  515. toPretty(result, node, 0, false)
  516. iterator items*(node: SexpNode): SexpNode =
  517. ## Iterator for the items of `node`. `node` has to be a SList.
  518. assert node.kind == SList
  519. for i in items(node.elems):
  520. yield i
  521. iterator mitems*(node: var SexpNode): var SexpNode =
  522. ## Iterator for the items of `node`. `node` has to be a SList. Items can be
  523. ## modified.
  524. assert node.kind == SList
  525. for i in mitems(node.elems):
  526. yield i
  527. proc eat(p: var SexpParser, tok: TTokKind) =
  528. if p.tok == tok: discard getTok(p)
  529. else: raiseParseErr(p, tokToStr[tok])
  530. proc parseSexp(p: var SexpParser): SexpNode =
  531. ## Parses SEXP from a SEXP Parser `p`.
  532. case p.tok
  533. of tkString:
  534. # we capture 'p.a' here, so we need to give it a fresh buffer afterwards:
  535. result = newSStringMove(p.a)
  536. p.a = ""
  537. discard getTok(p)
  538. of tkInt:
  539. result = newSInt(parseBiggestInt(p.a))
  540. discard getTok(p)
  541. of tkFloat:
  542. result = newSFloat(parseFloat(p.a))
  543. discard getTok(p)
  544. of tkNil:
  545. result = newSNil()
  546. discard getTok(p)
  547. of tkSymbol:
  548. result = newSSymbolMove(p.a)
  549. p.a = ""
  550. discard getTok(p)
  551. of tkParensLe:
  552. result = newSList()
  553. discard getTok(p)
  554. while p.tok notin {tkParensRi, tkDot}:
  555. result.add(parseSexp(p))
  556. if p.tok != tkSpace: break
  557. discard getTok(p)
  558. if p.tok == tkDot:
  559. eat(p, tkDot)
  560. eat(p, tkSpace)
  561. result.add(parseSexp(p))
  562. result = newSCons(result[0], result[1])
  563. eat(p, tkParensRi)
  564. of tkSpace, tkDot, tkError, tkParensRi, tkEof:
  565. raiseParseErr(p, "(")
  566. proc open*(my: var SexpParser, input: Stream) =
  567. ## initializes the parser with an input stream.
  568. lexbase.open(my, input)
  569. my.kind = sexpError
  570. my.a = ""
  571. proc parseSexp*(s: Stream): SexpNode =
  572. ## Parses from a buffer `s` into a `SexpNode`.
  573. var p: SexpParser
  574. p.open(s)
  575. discard getTok(p) # read first token
  576. result = p.parseSexp()
  577. p.close()
  578. proc parseSexp*(buffer: string): SexpNode =
  579. ## Parses Sexp from `buffer`.
  580. result = parseSexp(newStringStream(buffer))
  581. when isMainModule:
  582. let testSexp = parseSexp("""(1 (98 2) nil (2) foobar "foo" 9.234)""")
  583. assert(testSexp[0].getNum == 1)
  584. assert(testSexp[1][0].getNum == 98)
  585. assert(testSexp[2].getElems == @[])
  586. assert(testSexp[4].getSymbol == "foobar")
  587. assert(testSexp[5].getStr == "foo")
  588. let alist = parseSexp("""((1 . 2) (2 . "foo"))""")
  589. assert(alist[0].getCons.car.getNum == 1)
  590. assert(alist[0].getCons.cdr.getNum == 2)
  591. assert(alist[1].getCons.cdr.getStr == "foo")
  592. # Generator:
  593. var j = convertSexp([true, false, "foobar", [1, 2, "baz"]])
  594. assert($j == """(t nil "foobar" (1 2 "baz"))""")