lexer.go 14 KB

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