lexer.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. /*
  2. * ECAL
  3. *
  4. * Copyright 2020 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. package parser
  11. import (
  12. "bytes"
  13. "encoding/json"
  14. "fmt"
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. "unicode"
  19. "unicode/utf8"
  20. )
  21. var namePattern = regexp.MustCompile("^[A-Za-z][A-Za-z0-9]*$")
  22. var numberPattern = regexp.MustCompile("^[0-9].*$")
  23. /*
  24. LexToken represents a token which is returned by the lexer.
  25. */
  26. type LexToken struct {
  27. ID LexTokenID // Token kind
  28. Pos int // Starting position (in bytes)
  29. Val string // Token value
  30. Identifier bool // Flag if the value is an identifier (not quoted and not a number)
  31. Lline int // Line in the input this token appears
  32. Lpos int // Position in the input line this token appears
  33. }
  34. /*
  35. NewLexTokenInstance creates a new LexToken object instance from given LexToken values.
  36. */
  37. func NewLexTokenInstance(t LexToken) *LexToken {
  38. return &LexToken{
  39. t.ID,
  40. t.Pos,
  41. t.Val,
  42. t.Identifier,
  43. t.Lline,
  44. t.Lpos,
  45. }
  46. }
  47. /*
  48. Equals checks if this LexToken equals another LexToken. Returns also a message describing
  49. what is the found difference.
  50. */
  51. func (t LexToken) Equals(other LexToken, ignorePosition bool) (bool, string) {
  52. var res = true
  53. var msg = ""
  54. if t.ID != other.ID {
  55. res = false
  56. msg += fmt.Sprintf("ID is different %v vs %v\n", t.ID, other.ID)
  57. }
  58. if !ignorePosition && t.Pos != other.Pos {
  59. res = false
  60. msg += fmt.Sprintf("Pos is different %v vs %v\n", t.Pos, other.Pos)
  61. }
  62. if t.Val != other.Val {
  63. res = false
  64. msg += fmt.Sprintf("Val is different %v vs %v\n", t.Val, other.Val)
  65. }
  66. if t.Identifier != other.Identifier {
  67. res = false
  68. msg += fmt.Sprintf("Identifier is different %v vs %v\n", t.Identifier, other.Identifier)
  69. }
  70. if !ignorePosition && t.Lline != other.Lline {
  71. res = false
  72. msg += fmt.Sprintf("Lline is different %v vs %v\n", t.Lline, other.Lline)
  73. }
  74. if !ignorePosition && t.Lpos != other.Lpos {
  75. res = false
  76. msg += fmt.Sprintf("Lpos is different %v vs %v\n", t.Lpos, other.Lpos)
  77. }
  78. if msg != "" {
  79. var buf bytes.Buffer
  80. out, _ := json.MarshalIndent(t, "", " ")
  81. buf.WriteString(string(out))
  82. buf.WriteString("\nvs\n")
  83. out, _ = json.MarshalIndent(other, "", " ")
  84. buf.WriteString(string(out))
  85. msg = fmt.Sprintf("%v%v", msg, buf.String())
  86. }
  87. return res, msg
  88. }
  89. /*
  90. PosString returns the position of this token in the origianl input as a string.
  91. */
  92. func (t LexToken) PosString() string {
  93. return fmt.Sprintf("Line %v, Pos %v", t.Lline, t.Lpos)
  94. }
  95. /*
  96. String returns a string representation of a token.
  97. */
  98. func (t LexToken) String() string {
  99. prefix := ""
  100. if !t.Identifier {
  101. prefix = "v:" // Value is not an identifier
  102. }
  103. switch {
  104. case t.ID == TokenEOF:
  105. return "EOF"
  106. case t.ID == TokenError:
  107. return fmt.Sprintf("Error: %s (%s)", t.Val, t.PosString())
  108. case t.ID == TokenPRECOMMENT:
  109. return fmt.Sprintf("/* %s */", t.Val)
  110. case t.ID == TokenPOSTCOMMENT:
  111. return fmt.Sprintf("# %s", t.Val)
  112. case t.ID > TOKENodeSYMBOLS && t.ID < TOKENodeKEYWORDS:
  113. return fmt.Sprintf("%s", strings.ToUpper(t.Val))
  114. case t.ID > TOKENodeKEYWORDS:
  115. return fmt.Sprintf("<%s>", strings.ToUpper(t.Val))
  116. case len(t.Val) > 20:
  117. // Special case for very long values
  118. return fmt.Sprintf("%s%.10q...", prefix, t.Val)
  119. }
  120. return fmt.Sprintf("%s%q", prefix, t.Val)
  121. }
  122. // Meta data interface
  123. /*
  124. Type returns the meta data type.
  125. */
  126. func (t LexToken) Type() string {
  127. if t.ID == TokenPRECOMMENT {
  128. return MetaDataPreComment
  129. } else if t.ID == TokenPOSTCOMMENT {
  130. return MetaDataPostComment
  131. }
  132. return MetaDataGeneral
  133. }
  134. /*
  135. Value returns the meta data value.
  136. */
  137. func (t LexToken) Value() string {
  138. return t.Val
  139. }
  140. /*
  141. KeywordMap is a map of keywords - these require spaces between them
  142. */
  143. var KeywordMap = map[string]LexTokenID{
  144. // Import statement
  145. "import": TokenIMPORT,
  146. "as": TokenAS,
  147. // Sink definition
  148. "sink": TokenSINK,
  149. "kindmatch": TokenKINDMATCH,
  150. "scopematch": TokenSCOPEMATCH,
  151. "statematch": TokenSTATEMATCH,
  152. "priority": TokenPRIORITY,
  153. "suppresses": TokenSUPPRESSES,
  154. // Function definition
  155. "func": TokenFUNC,
  156. "return": TokenRETURN,
  157. // Boolean operators
  158. "and": TokenAND,
  159. "or": TokenOR,
  160. "not": TokenNOT,
  161. // String operators
  162. "like": TokenLIKE,
  163. "hasprefix": TokenHASPREFIX,
  164. "hassuffix": TokenHASSUFFIX,
  165. // List operators
  166. "in": TokenIN,
  167. "notin": TokenNOTIN,
  168. // Constant terminals
  169. "false": TokenFALSE,
  170. "true": TokenTRUE,
  171. "null": TokenNULL,
  172. // Conditional statements
  173. "if": TokenIF,
  174. "elif": TokenELIF,
  175. "else": TokenELSE,
  176. // Loop statements
  177. "for": TokenFOR,
  178. "break": TokenBREAK,
  179. "continue": TokenCONTINUE,
  180. }
  181. /*
  182. SymbolMap is a map of special symbols which will always be unique - these will separate unquoted strings
  183. Symbols can be maximal 2 characters long.
  184. */
  185. var SymbolMap = map[string]LexTokenID{
  186. // Condition operators
  187. ">=": TokenGEQ,
  188. "<=": TokenLEQ,
  189. "!=": TokenNEQ,
  190. "==": TokenEQ,
  191. ">": TokenGT,
  192. "<": TokenLT,
  193. // Grouping symbols
  194. "(": TokenLPAREN,
  195. ")": TokenRPAREN,
  196. "[": TokenLBRACK,
  197. "]": TokenRBRACK,
  198. "{": TokenLBRACE,
  199. "}": TokenRBRACE,
  200. // Separators
  201. ".": TokenDOT,
  202. ",": TokenCOMMA,
  203. ";": TokenSEMICOLON,
  204. // Grouping
  205. ":": TokenCOLON,
  206. "=": TokenEQUAL,
  207. // Arithmetic operators
  208. "+": TokenPLUS,
  209. "-": TokenMINUS,
  210. "*": TokenTIMES,
  211. "/": TokenDIV,
  212. "//": TokenDIVINT,
  213. "%": TokenMODINT,
  214. // Assignment statement
  215. ":=": TokenASSIGN,
  216. }
  217. // Lexer
  218. // =====
  219. /*
  220. RuneEOF is a special rune which represents the end of the input
  221. */
  222. const RuneEOF = -1
  223. /*
  224. Function which represents the current state of the lexer and returns the next state
  225. */
  226. type lexFunc func(*lexer) lexFunc
  227. /*
  228. Lexer data structure
  229. */
  230. type lexer struct {
  231. name string // Name to identify the input
  232. input string // Input string of the lexer
  233. pos int // Current rune pointer
  234. line int // Current line pointer
  235. lastnl int // Last newline position
  236. width int // Width of last rune
  237. start int // Start position of the current red token
  238. tokens chan LexToken // Channel for lexer output
  239. }
  240. /*
  241. Lex lexes a given input. Returns a channel which contains tokens.
  242. */
  243. func Lex(name string, input string) chan LexToken {
  244. l := &lexer{name, input, 0, 0, 0, 0, 0, make(chan LexToken)}
  245. go l.run()
  246. return l.tokens
  247. }
  248. /*
  249. LexToList lexes a given input. Returns a list of tokens.
  250. */
  251. func LexToList(name string, input string) []LexToken {
  252. var tokens []LexToken
  253. for t := range Lex(name, input) {
  254. tokens = append(tokens, t)
  255. }
  256. return tokens
  257. }
  258. /*
  259. Main loop of the lexer.
  260. */
  261. func (l *lexer) run() {
  262. if skipWhiteSpace(l) {
  263. for state := lexToken; state != nil; {
  264. state = state(l)
  265. if !skipWhiteSpace(l) {
  266. break
  267. }
  268. }
  269. }
  270. close(l.tokens)
  271. }
  272. /*
  273. next returns the next rune in the input and advances the current rune pointer
  274. if peek is 0. If peek is >0 then the nth character is returned without advancing
  275. the rune pointer.
  276. */
  277. func (l *lexer) next(peek int) rune {
  278. // Check if we reached the end
  279. if int(l.pos) >= len(l.input) {
  280. return RuneEOF
  281. }
  282. // Decode the next rune
  283. pos := l.pos
  284. if peek > 0 {
  285. pos += peek - 1
  286. }
  287. r, w := utf8.DecodeRuneInString(l.input[pos:])
  288. if peek == 0 {
  289. l.width = w
  290. l.pos += l.width
  291. }
  292. return r
  293. }
  294. /*
  295. backup sets the pointer one rune back. Can only be called once per next call.
  296. */
  297. func (l *lexer) backup(width int) {
  298. if width == 0 {
  299. width = l.width
  300. }
  301. l.pos -= width
  302. }
  303. /*
  304. startNew starts a new token.
  305. */
  306. func (l *lexer) startNew() {
  307. l.start = l.pos
  308. }
  309. /*
  310. emitToken passes a token back to the client.
  311. */
  312. func (l *lexer) emitToken(t LexTokenID) {
  313. if t == TokenEOF {
  314. l.emitTokenAndValue(t, "", false)
  315. return
  316. }
  317. if l.tokens != nil {
  318. l.tokens <- LexToken{t, l.start, l.input[l.start:l.pos], false,
  319. l.line + 1, l.start - l.lastnl + 1}
  320. }
  321. }
  322. /*
  323. emitTokenAndValue passes a token with a given value back to the client.
  324. */
  325. func (l *lexer) emitTokenAndValue(t LexTokenID, val string, identifier bool) {
  326. if l.tokens != nil {
  327. l.tokens <- LexToken{t, l.start, val, identifier, l.line + 1, l.start - l.lastnl + 1}
  328. }
  329. }
  330. /*
  331. emitError passes an error token back to the client.
  332. */
  333. func (l *lexer) emitError(msg string) {
  334. if l.tokens != nil {
  335. l.tokens <- LexToken{TokenError, l.start, msg, false, l.line + 1, l.start - l.lastnl + 1}
  336. }
  337. }
  338. // Helper functions
  339. // ================
  340. /*
  341. skipWhiteSpace skips any number of whitespace characters. Returns false if the parser
  342. reaches EOF while skipping whitespaces.
  343. */
  344. func skipWhiteSpace(l *lexer) bool {
  345. r := l.next(0)
  346. for unicode.IsSpace(r) || unicode.IsControl(r) || r == RuneEOF {
  347. if r == '\n' {
  348. l.line++
  349. l.lastnl = l.pos
  350. }
  351. r = l.next(0)
  352. if r == RuneEOF {
  353. l.emitToken(TokenEOF)
  354. return false
  355. }
  356. }
  357. l.backup(0)
  358. return true
  359. }
  360. /*
  361. lexTextBlock lexes a block of text without whitespaces. Interprets
  362. optionally all one or two letter tokens.
  363. */
  364. func lexTextBlock(l *lexer, interpretToken bool) {
  365. r := l.next(0)
  366. if interpretToken {
  367. // Check if we start with a known symbol
  368. nr := l.next(1)
  369. if _, ok := SymbolMap[strings.ToLower(string(r)+string(nr))]; ok {
  370. l.next(0)
  371. return
  372. }
  373. if _, ok := SymbolMap[strings.ToLower(string(r))]; ok {
  374. return
  375. }
  376. }
  377. for !unicode.IsSpace(r) && !unicode.IsControl(r) && r != RuneEOF {
  378. if interpretToken {
  379. // Check if we find a token in the block
  380. if _, ok := SymbolMap[strings.ToLower(string(r))]; ok {
  381. l.backup(0)
  382. return
  383. }
  384. nr := l.next(1)
  385. if _, ok := SymbolMap[strings.ToLower(string(r)+string(nr))]; ok {
  386. l.backup(0)
  387. return
  388. }
  389. }
  390. r = l.next(0)
  391. }
  392. if r != RuneEOF {
  393. l.backup(0)
  394. }
  395. }
  396. /*
  397. lexNumberBlock lexes a block potentially containing a number.
  398. */
  399. func lexNumberBlock(l *lexer) {
  400. r := l.next(0)
  401. for !unicode.IsSpace(r) && !unicode.IsControl(r) && r != RuneEOF {
  402. if !unicode.IsNumber(r) && r != '.' {
  403. if r == 'e' {
  404. l1 := l.next(1)
  405. l2 := l.next(2)
  406. if l1 != '+' || !unicode.IsNumber(l2) {
  407. break
  408. }
  409. l.next(0)
  410. l.next(0)
  411. } else {
  412. break
  413. }
  414. }
  415. r = l.next(0)
  416. }
  417. if r != RuneEOF {
  418. l.backup(0)
  419. }
  420. }
  421. // State functions
  422. // ===============
  423. /*
  424. lexToken is the main entry function for the lexer.
  425. */
  426. func lexToken(l *lexer) lexFunc {
  427. // Check if we got a quoted value or a comment
  428. n1 := l.next(1)
  429. n2 := l.next(2)
  430. // Parse comments
  431. if (n1 == '/' && n2 == '*') || n1 == '#' {
  432. return lexComment
  433. }
  434. // Parse strings
  435. if (n1 == '"' || n1 == '\'') || (n1 == 'r' && (n2 == '"' || n2 == '\'')) {
  436. return lexValue
  437. }
  438. // Lex a block of text and emit any found tokens
  439. l.startNew()
  440. // First try to parse a number
  441. lexNumberBlock(l)
  442. identifierCandidate := l.input[l.start:l.pos]
  443. keywordCandidate := strings.ToLower(identifierCandidate)
  444. // Check for number
  445. if numberPattern.MatchString(keywordCandidate) {
  446. _, err := strconv.ParseFloat(keywordCandidate, 64)
  447. if err == nil {
  448. l.emitTokenAndValue(TokenNUMBER, keywordCandidate, false)
  449. return lexToken
  450. }
  451. }
  452. if len(keywordCandidate) > 0 {
  453. l.backup(l.pos - l.start)
  454. }
  455. lexTextBlock(l, true)
  456. identifierCandidate = l.input[l.start:l.pos]
  457. keywordCandidate = strings.ToLower(identifierCandidate)
  458. // Check for keyword
  459. token, ok := KeywordMap[keywordCandidate]
  460. if !ok {
  461. // Check for symbol
  462. token, ok = SymbolMap[keywordCandidate]
  463. }
  464. if ok {
  465. // A known token was found
  466. l.emitToken(token)
  467. } else {
  468. if !namePattern.MatchString(keywordCandidate) {
  469. l.emitError(fmt.Sprintf("Cannot parse identifier '%v'. Identifies may only contain [a-zA-Z] and [a-zA-Z0-9] from the second character", keywordCandidate))
  470. return nil
  471. }
  472. // An identifier was found
  473. l.emitTokenAndValue(TokenIDENTIFIER, identifierCandidate, true)
  474. }
  475. return lexToken
  476. }
  477. /*
  478. lexValue lexes a string value.
  479. Values can be declared in different ways:
  480. ' ... ' or " ... "
  481. Characters are parsed between quotes (escape sequences are interpreted)
  482. r' ... ' or r" ... "
  483. Characters are parsed plain between quote
  484. */
  485. func lexValue(l *lexer) lexFunc {
  486. var endToken rune
  487. l.startNew()
  488. allowEscapes := false
  489. r := l.next(0)
  490. // Check if we have a raw quoted string
  491. if q := l.next(1); r == 'r' && (q == '"' || q == '\'') {
  492. endToken = q
  493. l.next(0)
  494. } else {
  495. allowEscapes = true
  496. endToken = r
  497. }
  498. r = l.next(0)
  499. rprev := ' '
  500. lLine := l.line
  501. lLastnl := l.lastnl
  502. for (!allowEscapes && r != endToken) ||
  503. (allowEscapes && (r != endToken || rprev == '\\')) {
  504. if r == '\n' {
  505. lLine++
  506. lLastnl = l.pos
  507. }
  508. rprev = r
  509. r = l.next(0)
  510. if r == RuneEOF {
  511. l.emitError("Unexpected end while reading string value (unclosed quotes)")
  512. return nil
  513. }
  514. }
  515. if allowEscapes {
  516. val := l.input[l.start+1 : l.pos-1]
  517. // Interpret escape sequences right away
  518. if endToken == '\'' {
  519. // Escape double quotes in a single quoted string
  520. val = strings.Replace(val, "\"", "\\\"", -1)
  521. }
  522. s, err := strconv.Unquote("\"" + val + "\"")
  523. if err != nil {
  524. l.emitError(err.Error() + " while parsing string")
  525. return nil
  526. }
  527. l.emitTokenAndValue(TokenSTRING, s, true)
  528. } else {
  529. l.emitTokenAndValue(TokenSTRING, l.input[l.start+2:l.pos-1], true)
  530. }
  531. // Set newline
  532. l.line = lLine
  533. l.lastnl = lLastnl
  534. return lexToken
  535. }
  536. /*
  537. lexComment lexes comments.
  538. */
  539. func lexComment(l *lexer) lexFunc {
  540. // Consume initial /*
  541. r := l.next(0)
  542. if r == '#' {
  543. l.startNew()
  544. for r != '\n' && r != RuneEOF {
  545. r = l.next(0)
  546. }
  547. l.emitTokenAndValue(TokenPOSTCOMMENT, l.input[l.start:l.pos], false)
  548. if r == RuneEOF {
  549. return nil
  550. }
  551. l.line++
  552. } else {
  553. l.next(0)
  554. lLine := l.line
  555. lLastnl := l.lastnl
  556. l.startNew()
  557. r = l.next(0)
  558. for r != '*' && l.next(1) != '/' {
  559. if r == '\n' {
  560. lLine++
  561. lLastnl = l.pos
  562. }
  563. r = l.next(0)
  564. if r == RuneEOF {
  565. l.emitError("Unexpected end while reading comment")
  566. return nil
  567. }
  568. }
  569. l.emitTokenAndValue(TokenPRECOMMENT, l.input[l.start:l.pos-1], false)
  570. // Consume final /
  571. l.next(0)
  572. // Set newline
  573. l.line = lLine
  574. l.lastnl = lLastnl
  575. }
  576. return lexToken
  577. }