Skip to content

Commit

Permalink
Add spec.EscapePattern function
Browse files Browse the repository at this point in the history
  • Loading branch information
nihei9 committed Jul 22, 2021
1 parent 7e169f8 commit a30fe0c
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
28 changes: 28 additions & 0 deletions driver/lexer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,34 @@ func TestLexer_Next(t *testing.T) {
return nil
},
},
{
lspec: &spec.LexSpec{
Entries: []*spec.LexEntry{
newLexEntryDefaultNOP("dot", spec.EscapePattern(`.`)),
newLexEntryDefaultNOP("star", spec.EscapePattern(`*`)),
newLexEntryDefaultNOP("plus", spec.EscapePattern(`+`)),
newLexEntryDefaultNOP("question", spec.EscapePattern(`?`)),
newLexEntryDefaultNOP("vbar", spec.EscapePattern(`|`)),
newLexEntryDefaultNOP("lparen", spec.EscapePattern(`(`)),
newLexEntryDefaultNOP("rparen", spec.EscapePattern(`)`)),
newLexEntryDefaultNOP("lbrace", spec.EscapePattern(`[`)),
newLexEntryDefaultNOP("backslash", spec.EscapePattern(`\`)),
},
},
src: `.*+?|()[\`,
tokens: []*Token{
newTokenDefault(1, "dot", newByteSequence([]byte(`.`))),
newTokenDefault(2, "star", newByteSequence([]byte(`*`))),
newTokenDefault(3, "plus", newByteSequence([]byte(`+`))),
newTokenDefault(4, "question", newByteSequence([]byte(`?`))),
newTokenDefault(5, "vbar", newByteSequence([]byte(`|`))),
newTokenDefault(6, "lparen", newByteSequence([]byte(`(`))),
newTokenDefault(7, "rparen", newByteSequence([]byte(`)`))),
newTokenDefault(8, "lbrace", newByteSequence([]byte(`[`))),
newTokenDefault(9, "backslash", newByteSequence([]byte(`\`))),
newEOFTokenDefault(),
},
},
}
for i, tt := range test {
for compLv := compiler.CompressionLevelMin; compLv <= compiler.CompressionLevelMax; compLv++ {
Expand Down
21 changes: 21 additions & 0 deletions spec/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package spec

import "strings"

var rep = strings.NewReplacer(
`.`, `\.`,
`*`, `\*`,
`+`, `\+`,
`?`, `\?`,
`|`, `\|`,
`(`, `\(`,
`)`, `\)`,
`[`, `\[`,
`\`, `\\`,
)

// EscapePattern escapes the special characters.
// For example, EscapePattern(`+`) returns `\+`.
func EscapePattern(s string) string {
return rep.Replace(s)
}

0 comments on commit a30fe0c

Please sign in to comment.