lexer.go 12 KB

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