lexer.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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. // Mutex block
  191. "mutex": TokenMUTEX,
  192. }
  193. /*
  194. SymbolMap is a map of special symbols which will always be unique - these will separate unquoted strings
  195. Symbols can be maximal 2 characters long.
  196. */
  197. var SymbolMap = map[string]LexTokenID{
  198. // Condition operators
  199. ">=": TokenGEQ,
  200. "<=": TokenLEQ,
  201. "!=": TokenNEQ,
  202. "==": TokenEQ,
  203. ">": TokenGT,
  204. "<": TokenLT,
  205. // Grouping symbols
  206. "(": TokenLPAREN,
  207. ")": TokenRPAREN,
  208. "[": TokenLBRACK,
  209. "]": TokenRBRACK,
  210. "{": TokenLBRACE,
  211. "}": TokenRBRACE,
  212. // Separators
  213. ".": TokenDOT,
  214. ",": TokenCOMMA,
  215. ";": TokenSEMICOLON,
  216. // Grouping
  217. ":": TokenCOLON,
  218. "=": TokenEQUAL,
  219. // Arithmetic operators
  220. "+": TokenPLUS,
  221. "-": TokenMINUS,
  222. "*": TokenTIMES,
  223. "/": TokenDIV,
  224. "//": TokenDIVINT,
  225. "%": TokenMODINT,
  226. // Assignment statement
  227. ":=": TokenASSIGN,
  228. }
  229. // Lexer
  230. // =====
  231. /*
  232. RuneEOF is a special rune which represents the end of the input
  233. */
  234. const RuneEOF = -1
  235. /*
  236. Function which represents the current state of the lexer and returns the next state
  237. */
  238. type lexFunc func(*lexer) lexFunc
  239. /*
  240. Lexer data structure
  241. */
  242. type lexer struct {
  243. name string // Name to identify the input
  244. input string // Input string of the lexer
  245. pos int // Current rune pointer
  246. line int // Current line pointer
  247. lastnl int // Last newline position
  248. width int // Width of last rune
  249. start int // Start position of the current red token
  250. tokens chan LexToken // Channel for lexer output
  251. }
  252. /*
  253. Lex lexes a given input. Returns a channel which contains tokens.
  254. */
  255. func Lex(name string, input string) chan LexToken {
  256. l := &lexer{name, input, 0, 0, 0, 0, 0, make(chan LexToken)}
  257. go l.run()
  258. return l.tokens
  259. }
  260. /*
  261. LexToList lexes a given input. Returns a list of tokens.
  262. */
  263. func LexToList(name string, input string) []LexToken {
  264. var tokens []LexToken
  265. for t := range Lex(name, input) {
  266. tokens = append(tokens, t)
  267. }
  268. return tokens
  269. }
  270. /*
  271. Main loop of the lexer.
  272. */
  273. func (l *lexer) run() {
  274. if skipWhiteSpace(l) {
  275. for state := lexToken; state != nil; {
  276. state = state(l)
  277. if !skipWhiteSpace(l) {
  278. break
  279. }
  280. }
  281. }
  282. close(l.tokens)
  283. }
  284. /*
  285. next returns the next rune in the input and advances the current rune pointer
  286. if peek is 0. If peek is >0 then the nth character is returned without advancing
  287. the rune pointer.
  288. */
  289. func (l *lexer) next(peek int) rune {
  290. // Check if we reached the end
  291. if int(l.pos) >= len(l.input) {
  292. return RuneEOF
  293. }
  294. // Decode the next rune
  295. pos := l.pos
  296. if peek > 0 {
  297. pos += peek - 1
  298. }
  299. r, w := utf8.DecodeRuneInString(l.input[pos:])
  300. if peek == 0 {
  301. l.width = w
  302. l.pos += l.width
  303. }
  304. return r
  305. }
  306. /*
  307. backup sets the pointer one rune back. Can only be called once per next call.
  308. */
  309. func (l *lexer) backup(width int) {
  310. if width == 0 {
  311. width = l.width
  312. }
  313. l.pos -= width
  314. }
  315. /*
  316. startNew starts a new token.
  317. */
  318. func (l *lexer) startNew() {
  319. l.start = l.pos
  320. }
  321. /*
  322. emitToken passes a token back to the client.
  323. */
  324. func (l *lexer) emitToken(t LexTokenID) {
  325. if t == TokenEOF {
  326. l.emitTokenAndValue(t, "", false, false)
  327. return
  328. }
  329. if l.tokens != nil {
  330. l.tokens <- LexToken{t, l.start, l.input[l.start:l.pos], false, false, l.name,
  331. l.line + 1, l.start - l.lastnl + 1}
  332. }
  333. }
  334. /*
  335. emitTokenAndValue passes a token with a given value back to the client.
  336. */
  337. func (l *lexer) emitTokenAndValue(t LexTokenID, val string, identifier bool, allowEscapes bool) {
  338. if l.tokens != nil {
  339. l.tokens <- LexToken{t, l.start, val, identifier, allowEscapes, l.name, l.line + 1, l.start - l.lastnl + 1}
  340. }
  341. }
  342. /*
  343. emitError passes an error token back to the client.
  344. */
  345. func (l *lexer) emitError(msg string) {
  346. if l.tokens != nil {
  347. l.tokens <- LexToken{TokenError, l.start, msg, false, false, l.name, l.line + 1, l.start - l.lastnl + 1}
  348. }
  349. }
  350. // Helper functions
  351. // ================
  352. /*
  353. skipWhiteSpace skips any number of whitespace characters. Returns false if the parser
  354. reaches EOF while skipping whitespaces.
  355. */
  356. func skipWhiteSpace(l *lexer) bool {
  357. r := l.next(0)
  358. for unicode.IsSpace(r) || unicode.IsControl(r) || r == RuneEOF {
  359. if r == '\n' {
  360. l.line++
  361. l.lastnl = l.pos
  362. }
  363. r = l.next(0)
  364. if r == RuneEOF {
  365. l.emitToken(TokenEOF)
  366. return false
  367. }
  368. }
  369. l.backup(0)
  370. return true
  371. }
  372. /*
  373. lexTextBlock lexes a block of text without whitespaces. Interprets
  374. optionally all one or two letter tokens.
  375. */
  376. func lexTextBlock(l *lexer, interpretToken bool) {
  377. r := l.next(0)
  378. if interpretToken {
  379. // Check if we start with a known symbol
  380. nr := l.next(1)
  381. if _, ok := SymbolMap[strings.ToLower(string(r)+string(nr))]; ok {
  382. l.next(0)
  383. return
  384. }
  385. if _, ok := SymbolMap[strings.ToLower(string(r))]; ok {
  386. return
  387. }
  388. }
  389. for !unicode.IsSpace(r) && !unicode.IsControl(r) && r != RuneEOF {
  390. if interpretToken {
  391. // Check if we find a token in the block
  392. if _, ok := SymbolMap[strings.ToLower(string(r))]; ok {
  393. l.backup(0)
  394. return
  395. }
  396. nr := l.next(1)
  397. if _, ok := SymbolMap[strings.ToLower(string(r)+string(nr))]; ok {
  398. l.backup(0)
  399. return
  400. }
  401. }
  402. r = l.next(0)
  403. }
  404. if r != RuneEOF {
  405. l.backup(0)
  406. }
  407. }
  408. /*
  409. lexNumberBlock lexes a block potentially containing a number.
  410. */
  411. func lexNumberBlock(l *lexer) {
  412. r := l.next(0)
  413. for !unicode.IsSpace(r) && !unicode.IsControl(r) && r != RuneEOF {
  414. if !unicode.IsNumber(r) && r != '.' {
  415. if r == 'e' {
  416. l1 := l.next(1)
  417. l2 := l.next(2)
  418. if l1 != '+' || !unicode.IsNumber(l2) {
  419. break
  420. }
  421. l.next(0)
  422. l.next(0)
  423. } else {
  424. break
  425. }
  426. }
  427. r = l.next(0)
  428. }
  429. if r != RuneEOF {
  430. l.backup(0)
  431. }
  432. }
  433. // State functions
  434. // ===============
  435. /*
  436. lexToken is the main entry function for the lexer.
  437. */
  438. func lexToken(l *lexer) lexFunc {
  439. // Check if we got a quoted value or a comment
  440. n1 := l.next(1)
  441. n2 := l.next(2)
  442. // Parse comments
  443. if (n1 == '/' && n2 == '*') || n1 == '#' {
  444. return lexComment
  445. }
  446. // Parse strings
  447. if (n1 == '"' || n1 == '\'') || (n1 == 'r' && (n2 == '"' || n2 == '\'')) {
  448. return lexValue
  449. }
  450. // Lex a block of text and emit any found tokens
  451. l.startNew()
  452. // First try to parse a number
  453. lexNumberBlock(l)
  454. identifierCandidate := l.input[l.start:l.pos]
  455. keywordCandidate := strings.ToLower(identifierCandidate)
  456. // Check for number
  457. if NumberPattern.MatchString(keywordCandidate) {
  458. _, err := strconv.ParseFloat(keywordCandidate, 64)
  459. if err == nil {
  460. l.emitTokenAndValue(TokenNUMBER, keywordCandidate, false, false)
  461. return lexToken
  462. }
  463. }
  464. if len(keywordCandidate) > 0 {
  465. l.backup(l.pos - l.start)
  466. }
  467. lexTextBlock(l, true)
  468. identifierCandidate = l.input[l.start:l.pos]
  469. keywordCandidate = strings.ToLower(identifierCandidate)
  470. // Check for keyword
  471. token, ok := KeywordMap[keywordCandidate]
  472. if !ok {
  473. // Check for symbol
  474. token, ok = SymbolMap[keywordCandidate]
  475. }
  476. if ok {
  477. // A known token was found
  478. l.emitToken(token)
  479. } else {
  480. if !NamePattern.MatchString(keywordCandidate) {
  481. 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))
  482. return nil
  483. }
  484. // An identifier was found
  485. l.emitTokenAndValue(TokenIDENTIFIER, identifierCandidate, true, false)
  486. }
  487. return lexToken
  488. }
  489. /*
  490. lexValue lexes a string value.
  491. Values can be declared in different ways:
  492. ' ... ' or " ... "
  493. Characters are parsed between quotes (escape sequences are interpreted)
  494. r' ... ' or r" ... "
  495. Characters are parsed plain between quote
  496. */
  497. func lexValue(l *lexer) lexFunc {
  498. var endToken rune
  499. l.startNew()
  500. allowEscapes := false
  501. r := l.next(0)
  502. // Check if we have a raw quoted string
  503. if q := l.next(1); r == 'r' && (q == '"' || q == '\'') {
  504. endToken = q
  505. l.next(0)
  506. } else {
  507. allowEscapes = true
  508. endToken = r
  509. }
  510. r = l.next(0)
  511. rprev := ' '
  512. lLine := l.line
  513. lLastnl := l.lastnl
  514. for (!allowEscapes && r != endToken) ||
  515. (allowEscapes && (r != endToken || rprev == '\\')) {
  516. if r == '\n' {
  517. lLine++
  518. lLastnl = l.pos
  519. }
  520. rprev = r
  521. r = l.next(0)
  522. if r == RuneEOF {
  523. l.emitError("Unexpected end while reading string value (unclosed quotes)")
  524. return nil
  525. }
  526. }
  527. if allowEscapes {
  528. val := l.input[l.start+1 : l.pos-1]
  529. // Interpret escape sequences right away
  530. if endToken == '\'' {
  531. // Escape double quotes in a single quoted string
  532. val = strings.Replace(val, "\"", "\\\"", -1)
  533. }
  534. s, err := strconv.Unquote("\"" + val + "\"")
  535. if err != nil {
  536. l.emitError(err.Error() + " while parsing string")
  537. return nil
  538. }
  539. l.emitTokenAndValue(TokenSTRING, s, false, true)
  540. } else {
  541. l.emitTokenAndValue(TokenSTRING, l.input[l.start+2:l.pos-1], false, false)
  542. }
  543. // Set newline
  544. l.line = lLine
  545. l.lastnl = lLastnl
  546. return lexToken
  547. }
  548. /*
  549. lexComment lexes comments.
  550. */
  551. func lexComment(l *lexer) lexFunc {
  552. // Consume initial /*
  553. r := l.next(0)
  554. if r == '#' {
  555. l.startNew()
  556. for r != '\n' && r != RuneEOF {
  557. r = l.next(0)
  558. }
  559. l.emitTokenAndValue(TokenPOSTCOMMENT, l.input[l.start:l.pos], false, false)
  560. if r == RuneEOF {
  561. return nil
  562. }
  563. l.line++
  564. } else {
  565. l.next(0)
  566. lLine := l.line
  567. lLastnl := l.lastnl
  568. l.startNew()
  569. r = l.next(0)
  570. for r != '*' || l.next(1) != '/' {
  571. if r == '\n' {
  572. lLine++
  573. lLastnl = l.pos
  574. }
  575. r = l.next(0)
  576. if r == RuneEOF {
  577. l.emitError("Unexpected end while reading comment")
  578. return nil
  579. }
  580. }
  581. l.emitTokenAndValue(TokenPRECOMMENT, l.input[l.start:l.pos-1], false, false)
  582. // Consume final /
  583. l.next(0)
  584. // Set newline
  585. l.line = lLine
  586. l.lastnl = lLastnl
  587. }
  588. return lexToken
  589. }