2018-05-01 02:37:51 +05:00
|
|
|
package chroma
|
|
|
|
|
|
|
|
type remappingLexer struct {
|
|
|
|
lexer Lexer
|
2019-03-07 08:43:28 +05:00
|
|
|
mapper func(Token) []Token
|
2018-05-01 02:37:51 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
// RemappingLexer remaps a token to a set of, potentially empty, tokens.
|
2019-03-07 08:43:28 +05:00
|
|
|
func RemappingLexer(lexer Lexer, mapper func(Token) []Token) Lexer {
|
2018-05-01 02:37:51 +05:00
|
|
|
return &remappingLexer{lexer, mapper}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *remappingLexer) Config() *Config {
|
|
|
|
return r.lexer.Config()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *remappingLexer) Tokenise(options *TokeniseOptions, text string) (Iterator, error) {
|
|
|
|
it, err := r.lexer.Tokenise(options, text)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-03-07 08:43:28 +05:00
|
|
|
var buffer []Token
|
|
|
|
return func() Token {
|
2018-05-01 02:37:51 +05:00
|
|
|
for {
|
|
|
|
if len(buffer) > 0 {
|
|
|
|
t := buffer[0]
|
|
|
|
buffer = buffer[1:]
|
|
|
|
return t
|
|
|
|
}
|
|
|
|
t := it()
|
2019-03-07 08:43:28 +05:00
|
|
|
if t == EOF {
|
2018-05-01 02:37:51 +05:00
|
|
|
return t
|
|
|
|
}
|
|
|
|
buffer = r.mapper(t)
|
|
|
|
}
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type TypeMapping []struct {
|
|
|
|
From, To TokenType
|
|
|
|
Words []string
|
|
|
|
}
|
|
|
|
|
|
|
|
// TypeRemappingLexer remaps types of tokens coming from a parent Lexer.
|
|
|
|
//
|
|
|
|
// eg. Map "defvaralias" tokens of type NameVariable to NameFunction:
|
|
|
|
//
|
|
|
|
// mapping := TypeMapping{
|
|
|
|
// {NameVariable, NameFunction, []string{"defvaralias"},
|
|
|
|
// }
|
|
|
|
// lexer = TypeRemappingLexer(lexer, mapping)
|
|
|
|
func TypeRemappingLexer(lexer Lexer, mapping TypeMapping) Lexer {
|
|
|
|
// Lookup table for fast remapping.
|
|
|
|
lut := map[TokenType]map[string]TokenType{}
|
|
|
|
for _, rt := range mapping {
|
|
|
|
km, ok := lut[rt.From]
|
|
|
|
if !ok {
|
|
|
|
km = map[string]TokenType{}
|
|
|
|
lut[rt.From] = km
|
|
|
|
}
|
2019-03-07 08:43:28 +05:00
|
|
|
if len(rt.Words) == 0 {
|
|
|
|
km[""] = rt.To
|
|
|
|
} else {
|
|
|
|
for _, k := range rt.Words {
|
|
|
|
km[k] = rt.To
|
|
|
|
}
|
2018-05-01 02:37:51 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2019-03-07 08:43:28 +05:00
|
|
|
return RemappingLexer(lexer, func(t Token) []Token {
|
2018-05-01 02:37:51 +05:00
|
|
|
if k, ok := lut[t.Type]; ok {
|
|
|
|
if tt, ok := k[t.Value]; ok {
|
|
|
|
t.Type = tt
|
2019-03-07 08:43:28 +05:00
|
|
|
} else if tt, ok := k[""]; ok {
|
|
|
|
t.Type = tt
|
2018-05-01 02:37:51 +05:00
|
|
|
}
|
|
|
|
}
|
2019-03-07 08:43:28 +05:00
|
|
|
return []Token{t}
|
2018-05-01 02:37:51 +05:00
|
|
|
})
|
|
|
|
}
|