lexer.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. package muesli
  2. import (
  3. "bufio"
  4. _ "bytes"
  5. _ "errors"
  6. "fmt"
  7. "io"
  8. _ "io"
  9. "os"
  10. _ "reflect"
  11. _ "runtime"
  12. "strconv"
  13. "strings"
  14. "unicode"
  15. _ "unicode"
  16. // "gitlab.com/beoran/woe/graphviz"
  17. // _ "gitlab.com/beoran/woe/monolog"
  18. )
  19. /* A Lexer splits scanned input into tokens.
  20. */
  21. type Lexer struct {
  22. Position
  23. Index int
  24. Start int
  25. io.RuneScanner
  26. buffer []rune
  27. Current rune
  28. LoggerWrapper
  29. }
  30. func (lexer *Lexer) SetLogger(logger Logger) {
  31. lexer.LoggerWrapper = LoggerWrapper{logger}
  32. }
  33. func (lexer *Lexer) ClearBuffer() {
  34. lexer.buffer = make([]rune, 0)
  35. }
  36. func (lexer *Lexer) MakeIntegerToken() Token {
  37. var sbuffer = string(lexer.buffer)
  38. i, err := strconv.ParseInt(sbuffer, 0, 64)
  39. if err == nil {
  40. lexer.ClearBuffer()
  41. return NewToken(TokenKindInteger, IntValue(i), lexer.Position)
  42. } else {
  43. lexer.ClearBuffer()
  44. return lexer.MakeErrorToken(err)
  45. }
  46. }
  47. func (lexer *Lexer) MakeFloatToken() Token {
  48. var sbuffer = string(lexer.buffer)
  49. f, err := strconv.ParseFloat(sbuffer, 64)
  50. if err == nil {
  51. lexer.ClearBuffer()
  52. return NewToken(TokenKindFloat, FloatValue(f), lexer.Position)
  53. } else {
  54. lexer.ClearBuffer()
  55. return lexer.MakeErrorToken(err)
  56. }
  57. }
  58. func (lexer *Lexer) MakeBooleanToken(b bool) Token {
  59. lexer.ClearBuffer()
  60. if b {
  61. return NewToken(TokenKindBoolean, TrueValue, lexer.Position)
  62. } else {
  63. return NewToken(TokenKindBoolean, FalseValue, lexer.Position)
  64. }
  65. }
  66. func (lexer *Lexer) MakeNilToken() Token {
  67. lexer.ClearBuffer()
  68. return NewToken(TokenKindNil, NilValue, lexer.Position)
  69. }
  70. func (lexer *Lexer) MakeBuiltinToken() Token {
  71. var sbuffer = string(lexer.buffer)
  72. lexer.ClearBuffer()
  73. if sbuffer == "true" {
  74. lexer.ClearBuffer()
  75. return NewToken(TokenKindBoolean, TrueValue, lexer.Position)
  76. } else if sbuffer == "false" {
  77. return NewToken(TokenKindBoolean, FalseValue, lexer.Position)
  78. } else if sbuffer == "nil" {
  79. return NewToken(TokenKindNil, NilValue, lexer.Position)
  80. } else {
  81. return lexer.MakeErrorfToken("Not a builtin: %s", sbuffer)
  82. }
  83. }
  84. func (lexer *Lexer) MakeStringValueToken(kind TokenKind) Token {
  85. var sbuffer = string(lexer.buffer)
  86. return NewToken(kind, StringValue(sbuffer), lexer.Position)
  87. }
  88. func (lexer *Lexer) MakeToken(kind TokenKind) Token {
  89. switch kind {
  90. case TokenKindInteger:
  91. return lexer.MakeIntegerToken()
  92. case TokenKindFloat:
  93. return lexer.MakeFloatToken()
  94. case TokenKindString:
  95. fallthrough
  96. case TokenKindSymbol:
  97. fallthrough
  98. case TokenKindType:
  99. fallthrough
  100. case TokenKindError:
  101. fallthrough
  102. case TokenKindWord:
  103. return lexer.MakeStringValueToken(kind)
  104. case TokenKindNil:
  105. fallthrough
  106. case TokenKindBoolean:
  107. return lexer.MakeBuiltinToken()
  108. case TokenKindGet:
  109. fallthrough
  110. case TokenKindSet:
  111. fallthrough
  112. case TokenKindOpenBlock:
  113. fallthrough
  114. case TokenKindCloseBlock:
  115. fallthrough
  116. case TokenKindOpenList:
  117. fallthrough
  118. case TokenKindCloseList:
  119. fallthrough
  120. case TokenKindOpenParen:
  121. fallthrough
  122. case TokenKindCloseParen:
  123. fallthrough
  124. case TokenKindEOX:
  125. fallthrough
  126. case TokenKindEOF:
  127. val := StringValue(string(lexer.buffer))
  128. lexer.ClearBuffer()
  129. return NewToken(kind, val, lexer.Position)
  130. default:
  131. return lexer.MakeErrorfToken("Internal error on token type %s", kind)
  132. }
  133. }
  134. func (lexer Lexer) MakeErrorToken(err error) Token {
  135. return NewToken(TokenKindError, ErrorValue{err}, lexer.Position)
  136. }
  137. func (lexer Lexer) MakeErrorfToken(format string, va ...interface{}) Token {
  138. err := fmt.Errorf(format, va...)
  139. return lexer.MakeErrorToken(err)
  140. }
  141. func (lexer Lexer) MakeEOFToken() Token {
  142. return NewToken(TokenKindEOF, &EmptyValue{}, lexer.Position)
  143. }
  144. func (lexer *Lexer) Peek() (rune, error) {
  145. r, _, err := lexer.RuneScanner.ReadRune()
  146. err2 := lexer.RuneScanner.UnreadRune()
  147. if err == nil {
  148. err = err2
  149. }
  150. return r, err
  151. }
  152. /* Advances the lexer's position based on the rune r read. */
  153. func (lexer *Lexer) advance(r rune) {
  154. lexer.Current = r
  155. lexer.Index++
  156. lexer.Position.Column++
  157. if r == '\n' {
  158. lexer.Position.Column = 1
  159. lexer.Position.Line++
  160. }
  161. }
  162. /* Append a rune to the lexer's buffer. */
  163. func (lexer *Lexer) appendRune(r rune) {
  164. lexer.buffer = append(lexer.buffer, r)
  165. }
  166. /* Advances the lexer's input buffer but does not store the rune read,
  167. * but just returns it. */
  168. func (lexer *Lexer) Skip() (rune, error) {
  169. r, _, err := lexer.RuneScanner.ReadRune()
  170. if err != nil {
  171. return 0, err
  172. }
  173. lexer.advance(r)
  174. return r, nil
  175. }
  176. /* Actually reads the next rune from the lexer's input source and stores
  177. * them in the lexer's token buffer.
  178. * Shorthand for r, err := lexer.Skip() ; lexer.appendRune(r) */
  179. func (lexer *Lexer) Next() (rune, error) {
  180. r, err := lexer.Skip()
  181. if err == nil {
  182. lexer.appendRune(r)
  183. }
  184. return r, nil
  185. }
  186. func (lexer *Lexer) DoIf(predicate func(rune) bool,
  187. todo func(*Lexer) (rune, error)) (bool, error) {
  188. r, err := lexer.Peek()
  189. if err != nil {
  190. return false, err
  191. }
  192. if predicate(r) {
  193. r, err = todo(lexer)
  194. if err != nil {
  195. return true, err
  196. }
  197. return true, nil
  198. }
  199. return false, nil
  200. }
  201. func (lexer *Lexer) NextIf(predicate func(rune) bool) (bool, error) {
  202. return lexer.DoIf(predicate, (*Lexer).Next)
  203. }
  204. func (lexer *Lexer) SkipIf(predicate func(rune) bool) (bool, error) {
  205. return lexer.DoIf(predicate, (*Lexer).Skip)
  206. }
  207. func (lexer *Lexer) NextWhile(predicate func(rune) bool) (bool, error) {
  208. result := true
  209. ok, err := lexer.NextIf(predicate)
  210. result = result || ok
  211. for ; ok && (err == nil); ok, err = lexer.NextIf(predicate) {
  212. result = result || ok
  213. }
  214. return result, err
  215. }
  216. func (lexer *Lexer) SkipWhile(predicate func(rune) bool) (bool, error) {
  217. result := true
  218. ok, err := lexer.SkipIf(predicate)
  219. result = result || ok
  220. for ; ok && (err == nil); ok, err = lexer.SkipIf(predicate) {
  221. result = result || ok
  222. }
  223. return result, err
  224. }
  225. func isSpace(r rune) bool {
  226. return r == ' ' || r == '\t' || r == '\v' || r == '\r'
  227. }
  228. func isComment(r rune) bool {
  229. return r == '#'
  230. }
  231. func (lexer *Lexer) SkipSpace() error {
  232. _, err := lexer.SkipWhile(isSpace)
  233. return err
  234. }
  235. func (lexer *Lexer) SkipBlockComment() error {
  236. var err error
  237. var r rune
  238. lexer.LogDebug("Skipping block comment.")
  239. for block := 1; block > 0 && err == nil; {
  240. _, err = lexer.Skip()
  241. if err != nil {
  242. return err
  243. }
  244. r, err = lexer.Peek()
  245. if r == '{' {
  246. block++
  247. } else if r == '}' {
  248. block--
  249. }
  250. lexer.LogDebug("Skipping block comment: %d", block)
  251. }
  252. _, err = lexer.Skip()
  253. return err
  254. }
  255. func (lexer *Lexer) SkipComment() error {
  256. r, err := lexer.Skip()
  257. lexer.LogDebug("Skipping %c.", r)
  258. if err != nil {
  259. return err
  260. }
  261. r, err = lexer.Peek()
  262. if r == '{' {
  263. return lexer.SkipBlockComment()
  264. }
  265. for r != '\n' && err == nil {
  266. lexer.LogDebug("Skipping comment %c.", r)
  267. _, err = lexer.Skip()
  268. if err != nil {
  269. return err
  270. }
  271. r, err = lexer.Peek()
  272. }
  273. if err != nil {
  274. return err
  275. }
  276. _, err = lexer.Skip()
  277. return err
  278. }
  279. /* Handles errors including EOF by either returning an error token or an
  280. * EOF token.
  281. */
  282. func (lexer *Lexer) handleError(err error) Token {
  283. if err == io.EOF {
  284. return lexer.MakeEOFToken()
  285. } else {
  286. return lexer.MakeErrorToken(err)
  287. }
  288. }
  289. func (lexer *Lexer) LexNumber() Token {
  290. isFloat := false
  291. // skip any first - or +
  292. _, err := lexer.NextIf(func(r rune) bool {
  293. return r == '-' || r == '+'
  294. })
  295. _, err = lexer.NextWhile(func(r rune) bool {
  296. if unicode.IsDigit(r) {
  297. return true
  298. } else if r == '.' {
  299. if isFloat {
  300. return false // double point in floating point
  301. } else {
  302. isFloat = true
  303. return true
  304. }
  305. } else {
  306. return false
  307. }
  308. })
  309. if err != nil {
  310. return lexer.MakeErrorfToken("when parsing number: %s", err)
  311. }
  312. if isFloat {
  313. return lexer.MakeToken(TokenKindFloat)
  314. } else {
  315. return lexer.MakeToken(TokenKindInteger)
  316. }
  317. }
  318. func isDoubleQuote(r rune) bool {
  319. return r == '"'
  320. }
  321. func (lexer *Lexer) handleEscapeHexChars(amount int) error {
  322. buffer := make([]byte, 0)
  323. r, err := lexer.Skip()
  324. for index := 0; err == nil && index < amount; {
  325. if unicode.Is(unicode.ASCII_Hex_Digit, r) {
  326. buffer = append(buffer, byte(r))
  327. } else {
  328. return fmt.Errorf("Not a hexadecimal digit: %c", r)
  329. }
  330. index++
  331. if index < amount {
  332. r, err = lexer.Skip()
  333. }
  334. }
  335. if err != nil {
  336. return err
  337. }
  338. i, err := strconv.ParseInt(string(buffer), 16, 32)
  339. if err != nil {
  340. return err
  341. }
  342. lexer.appendRune(rune(i))
  343. _, err = lexer.Peek()
  344. return err
  345. }
  346. func (lexer *Lexer) handleEscape() error {
  347. r, err := lexer.Skip()
  348. if err != nil {
  349. return err
  350. }
  351. switch r {
  352. case 'a':
  353. lexer.appendRune('\a')
  354. case 'b':
  355. lexer.appendRune('\b')
  356. case 'e':
  357. lexer.appendRune('\033')
  358. case 'f':
  359. lexer.appendRune('\f')
  360. case 'n':
  361. lexer.appendRune('\n')
  362. case 'r':
  363. lexer.appendRune('\r')
  364. case 't':
  365. lexer.appendRune('\t')
  366. case '\\':
  367. lexer.appendRune('\\')
  368. case '"':
  369. lexer.appendRune('"')
  370. // case 'o': fallthrough // No octals, for now.
  371. case 'x':
  372. err = lexer.handleEscapeHexChars(2)
  373. case 'u':
  374. err = lexer.handleEscapeHexChars(4)
  375. case 'U':
  376. err = lexer.handleEscapeHexChars(6)
  377. default:
  378. return fmt.Errorf("Unknown escape sequence character %c: %d", r, r)
  379. }
  380. return err
  381. }
  382. func (lexer *Lexer) LexString() Token {
  383. var err error
  384. var r rune
  385. _, err = lexer.Skip() // Skip first "
  386. if err != nil {
  387. return lexer.handleError(err)
  388. }
  389. r, err = lexer.Skip()
  390. for r != '"' && err == nil {
  391. if r == '\\' {
  392. err = lexer.handleEscape()
  393. if err != nil {
  394. return lexer.handleError(err)
  395. }
  396. } else {
  397. lexer.appendRune(r)
  398. // still inside the string
  399. }
  400. r, err = lexer.Skip()
  401. }
  402. if err != nil {
  403. return lexer.MakeErrorfToken("when parsing string: %s", err)
  404. }
  405. _, err = lexer.Skip() // skip last "
  406. if err != nil {
  407. return lexer.handleError(err)
  408. }
  409. return lexer.MakeToken(TokenKindString)
  410. }
  411. func (lexer *Lexer) LexLongString() Token {
  412. var err error
  413. _, err = lexer.Skip()
  414. if err != nil {
  415. return lexer.handleError(err)
  416. }
  417. _, err = lexer.NextWhile(func(r rune) bool {
  418. return r != '`'
  419. })
  420. if err != nil {
  421. return lexer.MakeErrorfToken("when parsing long string: %s", err)
  422. }
  423. _, err = lexer.Skip()
  424. if err != nil {
  425. return lexer.handleError(err)
  426. }
  427. return lexer.MakeToken(TokenKindString)
  428. }
  429. func (lexer *Lexer) LexWordOrType(kind TokenKind) Token {
  430. var err error
  431. first := true
  432. _, err = lexer.Next()
  433. if err != nil {
  434. return lexer.handleError(err)
  435. }
  436. _, err = lexer.NextWhile(func(r rune) bool {
  437. if first {
  438. first = false
  439. return unicode.IsLetter(r) || r == '_'
  440. } else {
  441. return unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_'
  442. }
  443. })
  444. if err != nil {
  445. return lexer.handleError(err)
  446. }
  447. sbuffer := string(lexer.buffer)
  448. // handle key words
  449. switch sbuffer {
  450. case "true":
  451. return lexer.MakeBooleanToken(true)
  452. case "false":
  453. return lexer.MakeBooleanToken(false)
  454. case "nil":
  455. return lexer.MakeNilToken()
  456. default:
  457. }
  458. return lexer.MakeToken(kind)
  459. }
  460. func (lexer *Lexer) LexWord() Token {
  461. return lexer.LexWordOrType(TokenKindWord)
  462. }
  463. func (lexer *Lexer) LexType() Token {
  464. return lexer.LexWordOrType(TokenKindType)
  465. }
  466. func (lexer *Lexer) LexSymbol() Token {
  467. var err error
  468. _, err = lexer.Skip()
  469. if err != nil {
  470. return lexer.handleError(err)
  471. }
  472. _, err = lexer.NextWhile(func(r rune) bool {
  473. return !unicode.IsSpace(r)
  474. })
  475. if err != nil {
  476. return lexer.handleError(err)
  477. }
  478. return lexer.MakeToken(TokenKindSymbol)
  479. }
  480. func (lexer *Lexer) LexBuiltin() Token {
  481. var err error
  482. _, err = lexer.Skip()
  483. if err != nil {
  484. return lexer.handleError(err)
  485. }
  486. _, err = lexer.NextWhile(func(r rune) bool {
  487. return !unicode.IsSpace(r)
  488. })
  489. if err != nil {
  490. return lexer.handleError(err)
  491. }
  492. return lexer.MakeBuiltinToken()
  493. }
  494. func (lexer *Lexer) skipSpaceAndCommentAndPeek() (rune, error) {
  495. r, err := lexer.Peek()
  496. if err != nil {
  497. return r, err
  498. }
  499. i := 0
  500. for isSpace(r) || isComment(r) {
  501. if isSpace(r) {
  502. err = lexer.SkipSpace()
  503. } else if isComment(r) {
  504. err = lexer.SkipComment()
  505. }
  506. if err != nil {
  507. return r, err
  508. }
  509. i++
  510. r, err = lexer.Peek()
  511. lexer.LogDebug("Peeked again: >%c< %v %v %d", r, isSpace(r), isComment(r), i)
  512. if err != nil {
  513. return r, err
  514. }
  515. }
  516. return r, err
  517. }
  518. func (lexer *Lexer) lex() Token {
  519. r, err := lexer.skipSpaceAndCommentAndPeek()
  520. lexer.LogDebug(" After skip: >%c< >%v<\n", r, err)
  521. if err != nil {
  522. return lexer.handleError(err)
  523. }
  524. if unicode.IsDigit(r) || r == '-' || r == '+' {
  525. return lexer.LexNumber()
  526. }
  527. if r == '\n' || r == '.' {
  528. lexer.Next()
  529. return lexer.MakeToken(TokenKindEOX)
  530. }
  531. if r == '"' {
  532. return lexer.LexString()
  533. }
  534. if r == '`' {
  535. return lexer.LexLongString()
  536. }
  537. if r == '!' {
  538. return lexer.LexBuiltin()
  539. }
  540. if r == ':' {
  541. return lexer.LexSymbol()
  542. }
  543. switch TokenKind(r) {
  544. case TokenKindGet:
  545. fallthrough
  546. case TokenKindSet:
  547. fallthrough
  548. case TokenKindOpenBlock:
  549. fallthrough
  550. case TokenKindCloseBlock:
  551. fallthrough
  552. case TokenKindOpenList:
  553. fallthrough
  554. case TokenKindCloseList:
  555. fallthrough
  556. case TokenKindOpenParen:
  557. fallthrough
  558. case TokenKindCloseParen:
  559. lexer.Next()
  560. return lexer.MakeToken(TokenKind(r))
  561. default:
  562. }
  563. if unicode.IsLetter(r) {
  564. if unicode.IsUpper(r) {
  565. return lexer.LexType()
  566. } else {
  567. return lexer.LexWord()
  568. }
  569. }
  570. return lexer.MakeErrorfToken("Unknown character: %c", r)
  571. }
  572. func (lexer *Lexer) Lex() Token {
  573. res := lexer.lex()
  574. lexer.ClearBuffer() // ensure buffer is cleared after lexing, always.
  575. return res
  576. }
  577. func (lexer *Lexer) LexAll() []Token {
  578. var token Token
  579. res := make([]Token, 0)
  580. for token = lexer.Lex(); !token.IsLast(); token = lexer.Lex() {
  581. res = append(res, token)
  582. }
  583. res = append(res, token)
  584. return res
  585. }
  586. func NewLexer(scanner io.RuneScanner, filename string) *Lexer {
  587. lexer := &Lexer{}
  588. lexer.RuneScanner = scanner
  589. lexer.Position.FileName = filename
  590. lexer.Position.Column = 1
  591. lexer.Position.Line = 1
  592. lexer.LoggerWrapper = LoggerWrapper{nil}
  593. return lexer
  594. }
  595. func (lexer * Lexer) Report() {
  596. if lexer == nil {
  597. fmt.Printf("Lexer: is nil\n")
  598. } else {
  599. fmt.Printf("Lexer: %s:%d:%d\n",
  600. lexer.Position.FileName,
  601. lexer.Position.Column,
  602. lexer.Position.Line)
  603. }
  604. }
  605. func NewLexerFromString(input string) *Lexer {
  606. reader := strings.NewReader(input)
  607. return NewLexer(reader, "<input>")
  608. }
  609. func NewLexerFromFilename(filename string) (*Lexer, error) {
  610. read, err := os.Open(filename)
  611. if err == nil {
  612. bread := bufio.NewReader(read)
  613. lex := NewLexer(bread, filename)
  614. return lex, nil
  615. }
  616. return nil, err
  617. }