-
Notifications
You must be signed in to change notification settings - Fork 4
/
regexer.nim
245 lines (213 loc) · 5.24 KB
/
regexer.nim
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
##[
This module provides the backend for glob pattern parsing and the compilation
to regular expressions. While it's re-exported from the main module and importing
it separately isn't necessary, it could be imported independently of the main
``glob`` package.
]##
from strutils import spaces
type GlobSyntaxError* = object of CatchableError
## Raised if the parsing of a glob pattern fails.
const
EOL = '\0'
globMetaChars = {'\\', '*', '?', '[', '{'}
regexMetaChars = {'.', '^', '$', '+', '{', '[', ']', '|', '(', ')'}
charClasses = {
"upper": "A-Z",
"lower": "a-z",
"alpha": "a-zA-Z",
"digit": "0-9",
"xdigit": "0-9A-Fa-f",
"alnum": r"a-zA-Z0-9",
"punct": r"-!""#$%&'()*+,./\\:;<=>?@[\]^_`{|}~",
"blank": r" \t",
"space": r"\s",
"ascii": r"\x00-\x7F",
"cntrl": r"\x00-\x1F\x7F",
"graph": r"\x21-\x7E",
"print": r"\x20-\x7E ",
"word": r"\w"
}
const
isDosDefault = defined windows
proc getClassRegex (name: string): string =
result = ""
for item in charClasses:
if item[0] == name: return item[1]
template fail (message, pattern: string, index: int) =
let errLines = 2.spaces & pattern & "\p" & (2 + index).spaces & "^" & "\p\p"
raise newException(GlobSyntaxError, message & "\p\p" & errLines)
proc globToRegexString* (
pattern: string,
isDos = isDosDefault,
ignoreCase = isDosDefault
): string =
## Parses the given ``pattern`` glob string and returns a regex string.
## Syntactic errors will cause a ``GlobSyntaxError`` to be raised.
var
stack: seq[char] = @[]
hasGlobstar = false
inRange = false
inGroup = false
rgx = "^"
i = -1
template peek (i: int): char =
if i >= 0 and i < pattern.len: pattern[i] else: EOL
template add (str: string | char) =
rgx &= str
template next (c: var char) =
inc i
c = peek(i)
template isNext (cmp: char): bool =
peek(i + 1) == cmp
if ignoreCase: add "(?i)"
while i < pattern.len - 1:
inc i
var c = pattern[i]
case c
of '\\':
# escape special characters
if i + 1 == pattern.len:
fail("No character to escape", pattern, i)
let nextChar = peek(i + 1)
if nextChar in globMetaChars or nextChar in regexMetaChars:
add('\\')
add(nextChar)
inc i
of '/':
if hasGlobstar: continue
if isDos:
add(r"\\")
else:
add(c)
of '(', '|':
if stack.len > 0:
add(c)
else:
add('\\' & c)
of ')':
if stack.len > 0:
add(c)
let kind = stack.pop
case kind
of '@': add("{1}")
of '!':
if isDos:
add("[^\\]*")
else:
add("[^/]*")
else: add(kind)
else:
add('\\' & c)
of '+':
if isNext('('):
stack.add(c)
else:
add('\\' & c)
of '@':
if isNext('('):
stack.add(c)
else:
add(c)
of '!':
if inRange:
add('^')
elif isNext('('):
fail("Negated patterns are currently not supported", pattern, i + 1)
# stack.add(c)
# add("(?!")
# inc i
else:
add('\\' & c)
of '?':
if isNext('('):
stack.add(c)
elif isDos:
add(r"[^\\]")
else:
add("[^/]")
of '[':
let nextChar = peek(i + 1)
if nextChar in {'!', '-', '^', ']'}:
add(c)
case nextChar
of '!': add('^')
of '-': add('-')
of '^': add(r"\^")
of ']': add(r"\]")
else: discard
inc i
inRange = true
continue
# character classes
if inRange:
if nextChar != ':':
fail("Cannot nest groups", pattern, i - 2)
inc(i, 2)
c = peek(i)
var name = ""
while c notin {':', EOL, ']'}:
name &= c
next(c)
if not isNext(']'):
fail("Missing ']' after class", pattern, i)
let classRgx = getClassRegex(name)
if classRgx == "":
fail("Unknown class name '{name}'", pattern, i)
add(classRgx)
inc i
continue
add(c)
inRange = true
of ']':
inRange = false
add(c)
of '-':
add(c)
if inRange:
let prevChar = peek(i - 1)
let nextChar = peek(i + 1)
if nextChar == '-' or prevChar.int > nextChar.int:
fail("Invalid range", pattern, i)
of '{':
if inGroup:
fail("Cannot nest groups", pattern, i)
add("(?:(?:")
inGroup = true
of '}':
if inGroup:
add("))")
inGroup = false
else:
add('}')
of ',':
if inGroup:
add(")|(?:")
else:
add(',')
of '*':
if isNext('('):
stack.add(c)
continue
if isNext('*'):
# crosses directory boundaries
hasGlobstar = true
if isDos:
add(r"(?:[^\\]*(?:\\|$))*")
else:
add(r"(?:[^\/]*(?:\/|$))*")
inc i
else:
# within directory boundary
if isDos:
add(r"[^\\]*")
else:
add("[^/]*")
else:
if c in regexMetaChars:
add('\\')
add(c)
if inRange:
fail("Missing ']'", pattern, i)
if inGroup:
fail("Missing '}'", pattern, i)
result = rgx & '$'