lexer.go 14 KB

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