lexer.go 15 KB

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