-
Notifications
You must be signed in to change notification settings - Fork 5
/
parser.go
368 lines (289 loc) · 9.3 KB
/
parser.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
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package css
import (
"strings"
"github.com/riking/cssparse/tokenizer"
)
type cssParser struct {
tokens *cssTokenizer
input string
output string
filePath string
rootPath string
// Map of mixin names and their contents.
mixins cssMixins
// The nesting level of each `:global` declaration, where each element is a pair of integers. The
// first is the nesting level, and the second is 0 (ident) or 1 (function).
globalRuleLevels [][2]int
// The nesting level of each `:local` declaration, where each element is a pair of integers. The
// first is the nesting level, and the second is 0 (ident) or 1 (function).
localRuleLevels [][2]int
// The hash value of the path. This is used to generate unique class names.
pathHash string
// Is the path a CSS module?
isModule bool
}
func (p *cssParser) parse() (string, error) {
for {
result, ok := p.handleNextToken()
if !ok {
break
}
p.append(result)
}
return p.output, nil
}
// Append the given input to the output.
func (p *cssParser) append(input string) {
p.tokens.logOutput(input)
p.output += input
}
// Returns the next token, or nil if the end or an error is reached.
func (p *cssParser) nextToken() *tokenizer.Token {
token := p.tokens.next()
if token.Type.StopToken() {
return nil
}
switch token.Type {
case tokenizer.TokenCloseBrace:
gcount := len(p.globalRuleLevels)
if gcount > 0 {
glevel := p.globalRuleLevels[gcount-1]
if p.tokens.nesting == glevel[0] {
p.tokens.log(":global is closed at %v", p.tokens.nesting)
if glevel[1] > 0 {
p.append(token.Value)
}
p.globalRuleLevels = p.globalRuleLevels[:gcount-1]
return p.nextToken()
}
}
lcount := len(p.localRuleLevels)
if lcount > 0 {
llevel := p.localRuleLevels[lcount-1]
if p.tokens.nesting == llevel[0] {
p.tokens.log(":local is closed at %v", p.tokens.nesting)
if llevel[1] > 0 {
p.append(token.Value)
}
p.localRuleLevels = p.localRuleLevels[:lcount-1]
return p.nextToken()
}
}
}
return token
}
// Iterate over all tokens until we find a token matching `tokenType`. Returns the matching token
// and all tokens until that point. If `appendToOutput` is true, the token values will be appended
// to the output.
func (p *cssParser) outputUntilTokenType(tokenType tokenizer.TokenType, appendToOutput bool) (*tokenizer.Token, []*tokenizer.Token) {
var tokensUntil []*tokenizer.Token
for {
token := p.nextToken()
if token == nil || token.Type == tokenType {
return token, tokensUntil
}
tokensUntil = append(tokensUntil, token)
if appendToOutput {
p.append(token.Render())
}
}
}
// Iterate over all tokens, passing the given iterator function `iterFn` for each iteration.
// Returning false from that function will break from the iteration.
func (p *cssParser) forEachToken(iterFn func(token *tokenizer.Token, nesting int) bool) {
for {
token := p.nextToken()
iterResult := iterFn(token, p.tokens.nesting)
if !iterResult {
break
}
}
}
// Handle the next token and return the output, and whether we should continue. Accepts a
// `handleNextTokenUntilFunc` as an optional first argument, which is used to determine whether we
// should stop handling tokens. The function receives the current token, and should return true if
// it should stop handling tokens.
func (p *cssParser) handleNextToken(args ...interface{}) (string, bool) {
token := p.nextToken()
if token == nil {
return "", false
}
switch len(args) {
case 1:
untilFn := args[0].(handleNextTokenUntilFunc)
if untilFn(token) {
return token.Render(), false
}
}
switch token.Type {
case tokenizer.TokenAtKeyword:
if token.Value == "define-mixin" {
key, def := p.tokens.parseMixinDefinition()
if key == "" {
return token.Render(), true
}
p.mixins[p.filePath+"#"+key] = def
return "", true
} else if token.Value == "mixin" {
var mixinIdent, uri string
// Capture the mixin declaration, so we can output it later if we fail to resolve it.
original := token.Render()
// Iterate over all tokens until the next semicolon, to find the mixin name and URI.
p.forEachToken(func(token *tokenizer.Token, nesting int) bool {
original += token.Render()
if token.Type == tokenizer.TokenSemicolon {
// Current token is a semicolon, so we're done. But we need to skip to the next token,
// otherwise we get duplicates of the semicolon.
p.nextToken()
return false
}
switch token.Type {
case tokenizer.TokenIdent: // get the mixin name.
if mixinIdent == "" {
mixinIdent = token.Value
}
case tokenizer.TokenURI: // get the mixin URI - if any.
uri = token.Value
}
return true
})
if p.resolveMixin(mixinIdent, uri) {
return "", true
} else {
t := p.tokens.currentToken()
return original + t.Render(), true
}
}
case tokenizer.TokenDelim:
if p.isModule && token.Value == "." {
nextT := p.nextToken()
if nextT.Type == tokenizer.TokenIdent {
// Return the unhashed class name if we are in a global rule.
gcount := len(p.globalRuleLevels)
if gcount > 0 {
glevel := p.globalRuleLevels[gcount-1]
if glevel[1] == 0 {
return "." + nextT.Value, true
}
}
p.tokens.log(".%s is module", nextT.Value)
return "." + cssModuleClassName(nextT.Value, p.pathHash), true
}
}
case tokenizer.TokenColon:
if p.isModule {
nextT := p.nextToken()
if nextT.Type == tokenizer.TokenFunction && nextT.Value == "local" {
untilV, tokensUntil := p.outputUntilTokenType(tokenizer.TokenCloseParen, false)
if untilV == nil {
return "", false
}
var containsClass bool
var className string
for _, t := range tokensUntil {
if t.Type == tokenizer.TokenDelim && t.Value == "." {
containsClass = true
} else if containsClass && t.Type == tokenizer.TokenIdent {
className = t.Value
}
}
if !containsClass {
panic("local() must contain a class name")
}
p.append("." + cssModuleClassName(className, p.pathHash))
untilV, _ = p.outputUntilTokenType(tokenizer.TokenOpenBrace, true)
if untilV == nil {
return "", false
}
p.tokens.log(":local is opened")
p.append(untilV.Value)
p.localRuleLevels = append(p.localRuleLevels, [2]int{p.tokens.nesting, 1})
token = p.nextToken()
} else if nextT.Type == tokenizer.TokenFunction && nextT.Value == "global" {
untilV, tokensUntil := p.outputUntilTokenType(tokenizer.TokenCloseParen, true)
if untilV == nil {
return "", false
}
var containsClass bool
for _, t := range tokensUntil {
if t.Type == tokenizer.TokenDelim && t.Value == "." {
containsClass = true
}
}
if !containsClass {
panic("global() must contain a class name")
}
untilV, _ = p.outputUntilTokenType(tokenizer.TokenOpenBrace, true)
if untilV == nil {
return "", false
}
p.tokens.log(":global() is opened at %v", p.tokens.nesting)
p.append(untilV.Value)
p.globalRuleLevels = append(p.globalRuleLevels, [2]int{p.tokens.nesting, 1})
token = p.nextToken()
} else if nextT.Type == tokenizer.TokenIdent && nextT.Value == "local" {
untilV, tokensUntil := p.outputUntilTokenType(tokenizer.TokenOpenBrace, false)
if untilV == nil {
return "", false
}
var tmpOutput string
var containsClass bool
for _, t := range tokensUntil {
if t.Type == tokenizer.TokenDelim && t.Value == "." {
containsClass = true
}
if containsClass && t.Type == tokenizer.TokenIdent {
tmpOutput += cssModuleClassName(t.Value, p.pathHash)
} else {
tmpOutput += t.Value
}
}
tmpOutput += untilV.Value
// A class ident may not be present for the local rule, so we need to check for one. If
// none is found we treat all children as local.
if !containsClass {
p.tokens.log(":local is opened")
// No class is present, all children are local.
p.localRuleLevels = append(p.localRuleLevels, [2]int{p.tokens.nesting, 0})
} else {
p.tokens.log(":local is opened")
// p.output += "." + className + p.pathHash + untilV.Value
p.append(strings.TrimSpace(tmpOutput))
}
token = p.nextToken()
} else if nextT.Type == tokenizer.TokenIdent && nextT.Value == "global" {
untilV, tokensUntil := p.outputUntilTokenType(tokenizer.TokenOpenBrace, false)
if untilV == nil {
return "", false
}
var tmpOutput string
var containsClass bool
for _, t := range tokensUntil {
if t.Type == tokenizer.TokenDelim && t.Value == "." {
containsClass = true
}
tmpOutput += t.Value
}
tmpOutput += untilV.Value
// A class ident may not be present for the global rule, so we need to check for one. If
// none is found we treat all children as global.
if !containsClass {
// No class is present, all children are global.
p.globalRuleLevels = append(p.globalRuleLevels, [2]int{p.tokens.nesting, 0})
p.tokens.log(":global is opened at %v", p.tokens.nesting)
token = p.nextToken()
} else {
p.tokens.log(":global is opened at %v", p.tokens.nesting)
p.append(strings.TrimSpace(tmpOutput))
token = p.nextToken()
}
} else {
return token.Render() + nextT.Render(), true
}
}
}
return token.Render(), true
}
func cssModuleClassName(name string, hash string) string {
return name + "-" + hash
}