build: set version to 0.5
[vis.git] / lua / lexers / xs.lua
blob2243a6fb057255795e2cfc3930a307a7825365c6
1 -- Copyright 2017 Michael Forney. See LICENSE.
2 -- Copyright 2017 David B. Lamkins. See LICENSE.
3 -- xs LPeg lexer.
5 local l = require('lexer')
6 local token, word_match = l.token, l.word_match
7 local P, R, S = lpeg.P, lpeg.R, lpeg.S
9 local M = {_NAME = 'xs'}
11 -- Whitespace.
12 local ws = token(l.WHITESPACE, l.space^1)
14 -- Comments.
15 local comment = token(l.COMMENT, '#' * l.nonnewline^0)
17 -- Strings.
18 local str = l.delimited_range("'", false, true)
19 local herestr = '<<<' * str
20 local heredoc = '<<' * P(function(input, index)
21 local s, e, _, delimiter =
22 input:find('[ \t]*(["\']?)([%w!"%%+,-./:?@_~]+)%1', index)
23 if s == index and delimiter then
24 delimiter = delimiter:gsub('[%%+-.?]', '%%%1')
25 local _, e = input:find('[\n\r]'..delimiter..'[\n\r]', e)
26 return e and e + 1 or #input + 1
27 end
28 end)
29 local string = token(l.STRING, str + herestr + heredoc)
31 -- Numbers.
32 local number = token(l.NUMBER, l.integer + l.float)
34 -- Keywords.
35 local keyword = token(l.KEYWORD, word_match({
36 'access', 'alias', 'catch', 'cd', 'dirs', 'echo', 'else', 'escape', 'eval',
37 'exec', 'exit', 'false', 'fn-', 'fn', 'for', 'forever', 'fork', 'history',
38 'if', 'jobs', 'let', 'limit', 'local', 'map', 'omap', 'popd', 'printf',
39 'pushd', 'read', 'result', 'set-', 'switch', 'throw', 'time', 'true',
40 'umask', 'until', 'unwind-protect', 'var', 'vars', 'wait', 'whats', 'while',
41 ':lt', ':le', ':gt', ':ge', ':eq', ':ne', '~', '~~', '...', '.',
42 }, '!"%*+,-./:?@[]~'))
44 -- Constants.
45 local constant = token(l.CONSTANT, '$&' * l.word)
47 -- Identifiers.
48 local identifier = token(l.IDENTIFIER, l.word)
50 -- Variables.
51 local variable = token(l.VARIABLE,
52 '$' * S('"#')^-1 * ('*' + l.digit^1 + l.word))
54 -- Operators.
55 local operator = token(l.OPERATOR, S('@`=!<>*&^|;?()[]{}') + '\\\n')
57 M._rules = {
58 {'whitespace', ws},
59 {'keyword', keyword},
60 {'constant', constant},
61 {'identifier', identifier},
62 {'string', string},
63 {'comment', comment},
64 {'number', number},
65 {'variable', variable},
66 {'operator', operator},
69 M._foldsymbols = {
70 _patterns = {'[{}]', '#'},
71 [l.OPERATOR] = {['{'] = 1, ['}'] = -1},
72 [l.COMMENT] = {['#'] = l.fold_line_comments('#')}
75 return M