lexer.go 13 KB

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