sexp.nim 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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 {.procvar.}=
  266. ## Creates a new `SString SexpNode`.
  267. new(result)
  268. result.kind = SString
  269. result.str = s
  270. proc newSStringMove(s: string): SexpNode =
  271. new(result)
  272. result.kind = SString
  273. shallowCopy(result.str, s)
  274. proc newSInt*(n: BiggestInt): SexpNode {.procvar.} =
  275. ## Creates a new `SInt SexpNode`.
  276. new(result)
  277. result.kind = SInt
  278. result.num = n
  279. proc newSFloat*(n: float): SexpNode {.procvar.} =
  280. ## Creates a new `SFloat SexpNode`.
  281. new(result)
  282. result.kind = SFloat
  283. result.fnum = n
  284. proc newSNil*(): SexpNode {.procvar.} =
  285. ## Creates a new `SNil SexpNode`.
  286. new(result)
  287. proc newSCons*(car, cdr: SexpNode): SexpNode {.procvar.} =
  288. ## Creates a new `SCons SexpNode`
  289. new(result)
  290. result.kind = SCons
  291. result.car = car
  292. result.cdr = cdr
  293. proc newSList*(): SexpNode {.procvar.} =
  294. ## Creates a new `SList SexpNode`
  295. new(result)
  296. result.kind = SList
  297. result.elems = @[]
  298. proc newSSymbol*(s: string): SexpNode {.procvar.} =
  299. new(result)
  300. result.kind = SSymbol
  301. result.symbol = s
  302. proc newSSymbolMove(s: string): SexpNode =
  303. new(result)
  304. result.kind = SSymbol
  305. shallowCopy(result.symbol, s)
  306. proc getStr*(n: SexpNode, default: string = ""): string =
  307. ## Retrieves the string value of a `SString SexpNode`.
  308. ##
  309. ## Returns ``default`` if ``n`` is not a ``SString``.
  310. if n.kind != SString: return default
  311. else: return n.str
  312. proc getNum*(n: SexpNode, default: BiggestInt = 0): BiggestInt =
  313. ## Retrieves the int value of a `SInt SexpNode`.
  314. ##
  315. ## Returns ``default`` if ``n`` is not a ``SInt``.
  316. if n.kind != SInt: return default
  317. else: return n.num
  318. proc getFNum*(n: SexpNode, default: float = 0.0): float =
  319. ## Retrieves the float value of a `SFloat SexpNode`.
  320. ##
  321. ## Returns ``default`` if ``n`` is not a ``SFloat``.
  322. if n.kind != SFloat: return default
  323. else: return n.fnum
  324. proc getSymbol*(n: SexpNode, default: string = ""): string =
  325. ## Retrieves the int value of a `SList SexpNode`.
  326. ##
  327. ## Returns ``default`` if ``n`` is not a ``SList``.
  328. if n.kind != SSymbol: return default
  329. else: return n.symbol
  330. proc getElems*(n: SexpNode, default: seq[SexpNode] = @[]): seq[SexpNode] =
  331. ## Retrieves the int value of a `SList SexpNode`.
  332. ##
  333. ## Returns ``default`` if ``n`` is not a ``SList``.
  334. if n.kind == SNil: return @[]
  335. elif n.kind != SList: return default
  336. else: return n.elems
  337. proc getCons*(n: SexpNode, defaults: Cons = (newSNil(), newSNil())): Cons =
  338. ## Retrieves the cons value of a `SList SexpNode`.
  339. ##
  340. ## Returns ``default`` if ``n`` is not a ``SList``.
  341. if n.kind == SCons: return (n.car, n.cdr)
  342. elif n.kind == SList: return (n.elems[0], n.elems[1])
  343. else: return defaults
  344. proc sexp*(s: string): SexpNode =
  345. ## Generic constructor for SEXP data. Creates a new `SString SexpNode`.
  346. new(result)
  347. result.kind = SString
  348. result.str = s
  349. proc sexp*(n: BiggestInt): SexpNode =
  350. ## Generic constructor for SEXP data. Creates a new `SInt SexpNode`.
  351. new(result)
  352. result.kind = SInt
  353. result.num = n
  354. proc sexp*(n: float): SexpNode =
  355. ## Generic constructor for SEXP data. Creates a new `SFloat SexpNode`.
  356. new(result)
  357. result.kind = SFloat
  358. result.fnum = n
  359. proc sexp*(b: bool): SexpNode =
  360. ## Generic constructor for SEXP data. Creates a new `SSymbol
  361. ## SexpNode` with value t or `SNil SexpNode`.
  362. new(result)
  363. if b:
  364. result.kind = SSymbol
  365. result.symbol = "t"
  366. else:
  367. result.kind = SNil
  368. proc sexp*(elements: openArray[SexpNode]): SexpNode =
  369. ## Generic constructor for SEXP data. Creates a new `SList SexpNode`
  370. new(result)
  371. result.kind = SList
  372. newSeq(result.elems, elements.len)
  373. for i, p in pairs(elements): result.elems[i] = p
  374. proc sexp*(s: SexpNode): SexpNode =
  375. result = s
  376. proc toSexp(x: NimNode): NimNode {.compiletime.} =
  377. case x.kind
  378. of nnkBracket:
  379. result = newNimNode(nnkBracket)
  380. for i in 0 ..< x.len:
  381. result.add(toSexp(x[i]))
  382. else:
  383. result = x
  384. result = prefix(result, "sexp")
  385. macro convertSexp*(x: untyped): untyped =
  386. ## Convert an expression to a SexpNode directly, without having to specify
  387. ## `%` for every element.
  388. result = toSexp(x)
  389. proc `==`* (a,b: SexpNode): bool =
  390. ## Check two nodes for equality
  391. if a.isNil:
  392. if b.isNil: return true
  393. return false
  394. elif b.isNil or a.kind != b.kind:
  395. return false
  396. else:
  397. return case a.kind
  398. of SString:
  399. a.str == b.str
  400. of SInt:
  401. a.num == b.num
  402. of SFloat:
  403. a.fnum == b.fnum
  404. of SNil:
  405. true
  406. of SList:
  407. a.elems == b.elems
  408. of SSymbol:
  409. a.symbol == b.symbol
  410. of SCons:
  411. a.car == b.car and a.cdr == b.cdr
  412. proc hash* (n:SexpNode): Hash =
  413. ## Compute the hash for a SEXP node
  414. case n.kind
  415. of SList:
  416. result = hash(n.elems)
  417. of SInt:
  418. result = hash(n.num)
  419. of SFloat:
  420. result = hash(n.fnum)
  421. of SString:
  422. result = hash(n.str)
  423. of SNil:
  424. result = hash(0)
  425. of SSymbol:
  426. result = hash(n.symbol)
  427. of SCons:
  428. result = hash(n.car) !& hash(n.cdr)
  429. proc len*(n: SexpNode): int =
  430. ## If `n` is a `SList`, it returns the number of elements.
  431. ## If `n` is a `JObject`, it returns the number of pairs.
  432. ## Else it returns 0.
  433. case n.kind
  434. of SList: result = n.elems.len
  435. else: discard
  436. proc `[]`*(node: SexpNode, index: int): SexpNode =
  437. ## Gets the node at `index` in a List. Result is undefined if `index`
  438. ## is out of bounds
  439. assert(not isNil(node))
  440. assert(node.kind == SList)
  441. return node.elems[index]
  442. proc add*(father, child: SexpNode) =
  443. ## Adds `child` to a SList node `father`.
  444. assert father.kind == SList
  445. father.elems.add(child)
  446. # ------------- pretty printing ----------------------------------------------
  447. proc indent(s: var string, i: int) =
  448. s.add(spaces(i))
  449. proc newIndent(curr, indent: int, ml: bool): int =
  450. if ml: return curr + indent
  451. else: return indent
  452. proc nl(s: var string, ml: bool) =
  453. if ml: s.add("\n")
  454. proc escapeJson*(s: string): string =
  455. ## Converts a string `s` to its JSON representation.
  456. result = newStringOfCap(s.len + s.len shr 3)
  457. result.add("\"")
  458. for x in runes(s):
  459. var r = int(x)
  460. if r >= 32 and r <= 127:
  461. var c = chr(r)
  462. case c
  463. of '"': result.add("\\\"") #" # gotta fix nim-mode
  464. of '\\': result.add("\\\\")
  465. else: result.add(c)
  466. else:
  467. result.add("\\u")
  468. result.add(toHex(r, 4))
  469. result.add("\"")
  470. proc copy*(p: SexpNode): SexpNode =
  471. ## Performs a deep copy of `a`.
  472. case p.kind
  473. of SString:
  474. result = newSString(p.str)
  475. of SInt:
  476. result = newSInt(p.num)
  477. of SFloat:
  478. result = newSFloat(p.fnum)
  479. of SNil:
  480. result = newSNil()
  481. of SSymbol:
  482. result = newSSymbol(p.symbol)
  483. of SList:
  484. result = newSList()
  485. for i in items(p.elems):
  486. result.elems.add(copy(i))
  487. of SCons:
  488. result = newSCons(copy(p.car), copy(p.cdr))
  489. proc toPretty(result: var string, node: SexpNode, indent = 2, ml = true,
  490. lstArr = false, currIndent = 0) =
  491. case node.kind
  492. of SString:
  493. if lstArr: result.indent(currIndent)
  494. result.add(escapeJson(node.str))
  495. of SInt:
  496. if lstArr: result.indent(currIndent)
  497. result.add(node.num)
  498. of SFloat:
  499. if lstArr: result.indent(currIndent)
  500. result.add(node.fnum)
  501. of SNil:
  502. if lstArr: result.indent(currIndent)
  503. result.add("nil")
  504. of SSymbol:
  505. if lstArr: result.indent(currIndent)
  506. result.add(node.symbol)
  507. of SList:
  508. if lstArr: result.indent(currIndent)
  509. if len(node.elems) != 0:
  510. result.add("(")
  511. result.nl(ml)
  512. for i in 0..len(node.elems)-1:
  513. if i > 0:
  514. result.add(" ")
  515. result.nl(ml) # New Line
  516. toPretty(result, node.elems[i], indent, ml,
  517. true, newIndent(currIndent, indent, ml))
  518. result.nl(ml)
  519. result.indent(currIndent)
  520. result.add(")")
  521. else: result.add("nil")
  522. of SCons:
  523. if lstArr: result.indent(currIndent)
  524. result.add("(")
  525. toPretty(result, node.car, indent, ml,
  526. true, newIndent(currIndent, indent, ml))
  527. result.add(" . ")
  528. toPretty(result, node.cdr, indent, ml,
  529. true, newIndent(currIndent, indent, ml))
  530. result.add(")")
  531. proc pretty*(node: SexpNode, indent = 2): string =
  532. ## Converts `node` to its Sexp Representation, with indentation and
  533. ## on multiple lines.
  534. result = ""
  535. toPretty(result, node, indent)
  536. proc `$`*(node: SexpNode): string =
  537. ## Converts `node` to its SEXP Representation on one line.
  538. result = ""
  539. toPretty(result, node, 0, false)
  540. iterator items*(node: SexpNode): SexpNode =
  541. ## Iterator for the items of `node`. `node` has to be a SList.
  542. assert node.kind == SList
  543. for i in items(node.elems):
  544. yield i
  545. iterator mitems*(node: var SexpNode): var SexpNode =
  546. ## Iterator for the items of `node`. `node` has to be a SList. Items can be
  547. ## modified.
  548. assert node.kind == SList
  549. for i in mitems(node.elems):
  550. yield i
  551. proc eat(p: var SexpParser, tok: TTokKind) =
  552. if p.tok == tok: discard getTok(p)
  553. else: raiseParseErr(p, tokToStr[tok])
  554. proc parseSexp(p: var SexpParser): SexpNode =
  555. ## Parses SEXP from a SEXP Parser `p`.
  556. case p.tok
  557. of tkString:
  558. # we capture 'p.a' here, so we need to give it a fresh buffer afterwards:
  559. result = newSStringMove(p.a)
  560. p.a = ""
  561. discard getTok(p)
  562. of tkInt:
  563. result = newSInt(parseBiggestInt(p.a))
  564. discard getTok(p)
  565. of tkFloat:
  566. result = newSFloat(parseFloat(p.a))
  567. discard getTok(p)
  568. of tkNil:
  569. result = newSNil()
  570. discard getTok(p)
  571. of tkSymbol:
  572. result = newSSymbolMove(p.a)
  573. p.a = ""
  574. discard getTok(p)
  575. of tkParensLe:
  576. result = newSList()
  577. discard getTok(p)
  578. while p.tok notin {tkParensRi, tkDot}:
  579. result.add(parseSexp(p))
  580. if p.tok != tkSpace: break
  581. discard getTok(p)
  582. if p.tok == tkDot:
  583. eat(p, tkDot)
  584. eat(p, tkSpace)
  585. result.add(parseSexp(p))
  586. result = newSCons(result[0], result[1])
  587. eat(p, tkParensRi)
  588. of tkSpace, tkDot, tkError, tkParensRi, tkEof:
  589. raiseParseErr(p, "(")
  590. proc open*(my: var SexpParser, input: Stream) =
  591. ## initializes the parser with an input stream.
  592. lexbase.open(my, input)
  593. my.kind = sexpError
  594. my.a = ""
  595. proc parseSexp*(s: Stream): SexpNode =
  596. ## Parses from a buffer `s` into a `SexpNode`.
  597. var p: SexpParser
  598. p.open(s)
  599. discard getTok(p) # read first token
  600. result = p.parseSexp()
  601. p.close()
  602. proc parseSexp*(buffer: string): SexpNode =
  603. ## Parses Sexp from `buffer`.
  604. result = parseSexp(newStringStream(buffer))
  605. when isMainModule:
  606. let testSexp = parseSexp("""(1 (98 2) nil (2) foobar "foo" 9.234)""")
  607. assert(testSexp[0].getNum == 1)
  608. assert(testSexp[1][0].getNum == 98)
  609. assert(testSexp[2].getElems == @[])
  610. assert(testSexp[4].getSymbol == "foobar")
  611. assert(testSexp[5].getStr == "foo")
  612. let alist = parseSexp("""((1 . 2) (2 . "foo"))""")
  613. assert(alist[0].getCons.car.getNum == 1)
  614. assert(alist[0].getCons.cdr.getNum == 2)
  615. assert(alist[1].getCons.cdr.getStr == "foo")
  616. # Generator:
  617. var j = convertSexp([true, false, "foobar", [1, 2, "baz"]])
  618. assert($j == """(t nil "foobar" (1 2 "baz"))""")