-
Notifications
You must be signed in to change notification settings - Fork 327
/
skip.go
80 lines (73 loc) · 2.34 KB
/
skip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (C) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package parse
import (
"unicode/utf8"
"github.com/google/gapid/core/text/parse/cst"
)
type SkipMode int
const (
// SkipPrefix is the skip mode that skips tokens that are associated with
// the following lexically relevant token. This is mostly important for
// comment association.
SkipPrefix SkipMode = iota
// SkipSuffix is the skip mode that skips tokens that are associated with
// the preceding lexically relevant token. This is mostly important for
// comment association.
SkipSuffix
)
// Skip is the function used to skip separating tokens.
// A separating token is one where, as far as the parser is concerned, the
// tokens do not exist, even though the tokens may have been necessary to
// separate the lexical tokens (whitespace), or carry useful information
// (comments).
type Skip func(parser *Parser, mode SkipMode) cst.Separator
// NewSkip builds a Skip function for the common case of a parser that has one
// type of line comment, one type of block comment, and want to treat all
// unicode space characters as skippable.
func NewSkip(line, blockstart, blockend string) Skip {
return func(p *Parser, mode SkipMode) cst.Separator {
var sep cst.Separator
for {
switch {
case p.Space():
sep = append(sep, p.Consume())
case mode == SkipPrefix && p.EOL():
sep = append(sep, p.Consume())
case p.String(line):
if !p.SeekRune('\n') {
for !p.IsEOF() {
p.Advance()
}
}
sep = append(sep, p.Consume())
case p.String(blockstart):
first, _ := utf8.DecodeRuneInString(blockend)
for {
if !p.SeekRune(first) {
p.Error("Unterminated block comment")
break
}
if p.String(blockend) {
break
}
p.Advance()
}
sep = append(sep, p.Consume())
default:
return sep
}
}
}
}