package editor import ( "strings" ) // Lexers for languages the general lexer does not fit: JSON's keys, // TOML's tables, HCL's heredocs, CSS, markup with the scripts and styles // inside it and Svelte's expressions, ERB's Ruby, Markdown with the code // of its fenced blocks, and diffs. // relabel gives the tokens of line covering start to end kind k, // splitting those that reach past them. func relabel(toks []Token, start, end int, k TokenKind) []Token { var out []Token from := 0 for _, t := range toks { a, b := from, t.End from = t.End if b <= start || a >= end { out = appendTok(out, b, t.Kind) continue } if a < start { out = appendTok(out, start, t.Kind) } out = appendTok(out, min(b, end), k) if b > end { out = appendTok(out, b, t.Kind) } } return out } func appendTok(toks []Token, end int, k TokenKind) []Token { if n := len(toks); n > 0 { if toks[n-1].End >= end { return toks } if toks[n-1].Kind == k { toks[n-1].End = end return toks } } return append(toks, Token{End: end, Kind: k}) } // jsonLexer makes the strings before colons keys. type jsonLexer struct{ lexer } // Tokenize relabels each key's tokens where they are, in one pass over // the line: relabeling a key at a time would copy every token after it, // and a minified file's one line, of thousands of keys, would take // minutes. func (j *jsonLexer) Tokenize(line string, state uint64, tokens []Token) ([]Token, uint64) { n0 := len(tokens) tokens, next := j.lexer.Tokenize(line, state, tokens) toks := tokens[n0:] out := toks[:0] // written behind where it is read for i := 0; i < len(toks); i++ { if toks[i].Kind != TokenString { out = appendTok(out, toks[i].End, toks[i].Kind) continue } // A string, with its escapes. k := i for k+1 < len(toks) && (toks[k+1].Kind == TokenString || toks[k+1].Kind == TokenEscape) { k++ } end := toks[k].End p := end for p < len(line) && (line[p] == ' ' || line[p] == '\t') { p++ } if p < len(line) && line[p] == ':' { out = appendTok(out, end, TokenProperty) } else { for ; i <= k; i++ { out = appendTok(out, toks[i].End, toks[i].Kind) } } i = k } return tokens[:n0+len(out)], next } // tomlLexer makes tables types and keys properties. type tomlLexer struct{ lexer } func (t *tomlLexer) Tokenize(line string, state uint64, tokens []Token) ([]Token, uint64) { n0 := len(tokens) tokens, next := t.lexer.Tokenize(line, state, tokens) if state != 0 { return tokens, next } toks := tokens[n0:] trimmed := strings.TrimLeft(line, " \t") start := len(line) - len(trimmed) switch { case strings.HasPrefix(trimmed, "["): end := strings.LastIndexByte(line, ']') if end > start { toks = relabel(toks, start, end+1, TokenType) } default: if eq := strings.IndexByte(line, '='); eq > start && !strings.ContainsAny(line[start:eq], "\"'#") { key := strings.TrimRight(line[start:eq], " \t") toks = relabel(toks, start, start+len(key), TokenProperty) } } return append(tokens[:n0], toks...), next } // hclLexer adds HCL's heredocs, <>8 { return out.toks, 0 } return out.toks, state } n0 := len(tokens) tokens, next := h.lexer.Tokenize(line, state, tokens) // A block word before a dot, as in data.x.id or module.m.out, names // a value the way var.x and local.x do. for i := n0; i < len(tokens); i++ { if t := &tokens[i]; t.Kind == TokenKeyword && t.End < len(line) && line[t.End] == '.' { t.Kind = TokenVariable } } if next != 0 { return tokens, next } body := strings.TrimRight(line, " \t\r") j := len(body) for j > 0 && isIdentByte(body[j-1]) { j-- } word := body[j:] k := j if k > 0 && body[k-1] == '-' { k-- } if word == "" || !identStart(word, "") || k < 2 || body[k-2:k] != "<<" || kindAt(tokens[n0:], k-2) != TokenOperator { return tokens, next } toks := relabel(tokens[n0:], k-2, len(body), TokenString) return append(tokens[:n0], toks...), hclHeredoc | hclHash(word)<<8 } // hclHash hashes a heredoc's word into 32 bits, FNV-1a. func hclHash(s string) uint64 { h := uint32(2166136261) for i := 0; i < len(s); i++ { h = (h ^ uint32(s[i])) * 16777619 } return uint64(h) } // templateLexer lexes a template: text in a host language with code in // tags, as ERB's <% %> or Jinja's {{ }} and {% %}, and comments in others. // Outside a tag its state is the host's. In a tag that goes on to the next // line, it is the code's state (bits 0-39), the host's without the state of // a script or style in it (bits 40-55), and one more than the tag's index // (bits 62-63). A host whose state needs more bits, as Markdown's in a // fence, resumes after such a tag from those it kept. type templateLexer struct { // host lexes the text outside tags; without one, it is plain text. host, code Tokenizer // tags are tried in order where one opens, so a longer opener goes // before one it starts with, as <%# before <%. All their openers // start with the same byte, and there are at most three. tags []templateTag // marks are characters after an opener that belong to it, as = and - // in <%= and <%-; trims before a closer, as - in -%>. marks, trims string // escape is an opener written out as text, as <%% in ERB. escape string } type templateTag struct { open, close string comment bool } func (t *templateLexer) Tokenize(line string, state uint64, tokens []Token) ([]Token, uint64) { out := lexOut{toks: tokens} n := len(line) tag := int(state >> 62) // the open tag's index plus 1; 0 outside one hostState, codeState := state, uint64(0) if tag != 0 { codeState, hostState = state&(1<<40-1), state>>40&0xffff } // sub lexes line[from:to] with tk, from state. sub := func(tk Tokenizer, from, to int, state uint64) uint64 { if from >= to { return state } if tk == nil { out.add(to, TokenText) return state } // Lexed into the room after the line's tokens, and each written // back behind where it is read. toks, next := tk.Tokenize(line[from:to], state, out.toks[len(out.toks):]) for _, tk := range toks { out.add(from+tk.End, tk.Kind) } return next } for i := 0; i < n; { if tag == 0 { j, k := t.opener(line, i) hostState = sub(t.host, i, j, hostState) if j == n { break } e := j + len(t.tags[k].open) if t.tags[k].comment { out.add(e, TokenComment) } else { if e < n && strings.IndexByte(t.marks, line[e]) >= 0 { e++ } out.add(e, TokenMeta) } i, tag, codeState = e, k+1, 0 continue } tg := t.tags[tag-1] end := strings.Index(line[i:], tg.close) stop := n if end >= 0 { stop = i + end } if tg.comment { out.add(min(stop+len(tg.close), n), TokenComment) } else { code := stop if end >= 0 && code > i && strings.IndexByte(t.trims, line[code-1]) >= 0 { code-- } codeState = sub(t.code, i, code, codeState) if end >= 0 { out.add(stop+len(tg.close), TokenMeta) } } if end < 0 { break } i, tag, codeState = stop+len(tg.close), 0, 0 } if tag != 0 { return out.toks, uint64(tag)<<62 | (hostState&0xffff)<<40 | codeState&(1<<40-1) } return out.toks, hostState } // opener returns where the next tag opens in line from i, and which tag, // skipping escapes; len(line) when none does. func (t *templateLexer) opener(line string, i int) (int, int) { c := t.tags[0].open[0] for j := i; ; { k := strings.IndexByte(line[j:], c) if k < 0 { return len(line), 0 } j += k if t.escape != "" && strings.HasPrefix(line[j:], t.escape) { j += len(t.escape) continue } for k, tg := range t.tags { if strings.HasPrefix(line[j:], tg.open) { return j, k } } j++ } } // cssLexer lexes CSS, SCSS and Less: selectors, at-rules, properties and // their values. Its state packs the mode (bits 0-3: 1 a comment) and how // many blocks the line starts in (bits 8-15). type cssLexer struct{} func (cssLexer) Tokenize(line string, state uint64, tokens []Token) ([]Token, uint64) { out := lexOut{toks: tokens} mode := int(state & 0xf) depth := int(state >> 8 & 0xff) n := len(line) // value: after a property's colon, until ; or }. value := false for i := 0; i < n; { c := line[i] if mode == 1 { end := strings.Index(line[i:], "*/") if end < 0 { out.add(n, TokenComment) i = n continue } out.add(i+end+2, TokenComment) i += end + 2 mode = 0 continue } switch { case c == ' ' || c == '\t' || c == '\r': out.add(i+1, TokenText) i++ case strings.HasPrefix(line[i:], "/*"): mode = 1 out.add(i+2, TokenComment) i += 2 case strings.HasPrefix(line[i:], "//") && (i == 0 || line[i-1] != ':'): out.add(n, TokenComment) i = n case c == '"' || c == '\'': j := i + 1 for j < n && line[j] != c { if line[j] == '\\' { j++ } j++ } out.add(min(n, j+1), TokenString) i = min(n, j+1) case c == '{': depth = min(depth+1, 255) value = false out.add(i+1, TokenPunctuation) i++ case c == '}': depth = max(depth-1, 0) value = false out.add(i+1, TokenPunctuation) i++ case c == ';': value = false out.add(i+1, TokenPunctuation) i++ case c == '@': j := i + 1 for j < n && (isIdentByte(line[j]) || line[j] == '-') { j++ } out.add(j, TokenKeyword) i = j case c == '$' && i+1 < n && (isIdentByte(line[i+1]) || line[i+1] == '-'): j := i + 1 for j < n && (isIdentByte(line[j]) || line[j] == '-') { j++ } out.add(j, TokenVariable) i = j case c == '#' && value: j := i + 1 for j < n && isIdentByte(line[j]) { j++ } out.add(j, TokenNumber) i = j case c >= '0' && c <= '9' || (c == '.' || c == '-' || c == '+') && i+1 < n && line[i+1] >= '0' && line[i+1] <= '9' && value: j := i + 1 for j < n && (line[j] >= '0' && line[j] <= '9' || line[j] == '.') { j++ } // The unit. for j < n && (line[j] >= 'a' && line[j] <= 'z' || line[j] == '%') { j++ } out.add(j, TokenNumber) i = j case isIdentByte(c) || c == '-' || c >= 0x80: j := i for j < n && (isIdentByte(line[j]) || line[j] == '-' || line[j] >= 0x80) { j++ } k := j for k < n && (line[k] == ' ' || line[k] == '\t') { k++ } kind := TokenTag switch { case value && k < n && line[k] == '(': kind = TokenFunction case value: kind = TokenConstant if line[i] == '-' && strings.HasPrefix(line[i:], "--") { kind = TokenVariable } case depth > 0 && k < n && line[k] == ':' && !cssSelectorAhead(line[k:]): kind = TokenProperty case strings.HasPrefix(line[i:], "--"): kind = TokenVariable } out.add(j, kind) i = j case c == ':' && !value && depth > 0 && !cssSelectorAhead(line[i:]): value = true out.add(i+1, TokenPunctuation) i++ case c == ':': // A pseudo-class or element. j := i + 1 for j < n && (line[j] == ':' || isIdentByte(line[j]) || line[j] == '-') { j++ } out.add(j, TokenKeyword) i = j case (c == '.' || c == '#') && !value && i+1 < n && (isIdentByte(line[i+1]) || line[i+1] == '-'): j := i + 1 for j < n && (isIdentByte(line[j]) || line[j] == '-') { j++ } out.add(j, TokenType) i = j case c == '!' && strings.HasPrefix(line[i:], "!important"): out.add(i+10, TokenKeyword) i += 10 default: kind := TokenOperator if strings.IndexByte("(),[]", c) >= 0 { kind = TokenPunctuation } out.add(i+1, kind) i++ } } return out.toks, uint64(mode) | uint64(depth)<<8 } // cssSelectorAhead reports whether what follows a colon is a selector // going on to a block, as a:hover {, rather than a value. func cssSelectorAhead(s string) bool { brace := strings.IndexByte(s, '{') semi := strings.IndexByte(s, ';') return brace >= 0 && (semi < 0 || brace < semi) } // markupLexer lexes HTML and XML: tags, attributes, comments, entities, // and, in HTML, the scripts and styles inside it with their own // tokenizers. With braces, as Svelte's, it lexes {expressions} in text, // in tags and in attribute values with the script's tokenizer, and // {#blocks}. Its state packs the mode (bits 0-3), what the tag being // lexed opens (bits 4-5: 1 a script, 2 a style), whether the script is // TypeScript (bit 6), the braces open in an expression (bits 8-13) and // the mode it goes back to (bits 14-15: text, a tag, or a double- or // single-quoted value), and the state of the script, style or // expression (bits 16-55). type markupLexer struct { html bool script, style Tokenizer // braces lexes {…} as expressions, as Svelte's. braces bool // ts lexes a