lexer.go 14 KB

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