aboutsummaryrefslogtreecommitdiff
path: root/parser/parser.go
blob: 7d69e30375bfacfc5102ab6e96089dc127e09d8f (plain) (blame)
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package parser

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
	"unicode"
)

type nodeType uint

const (
	Normal nodeType = iota
	Tagless
	TaglessTrim
	Text
)

// Attr represents an HTML attribute.  It is a key/value pair.
type Attr struct {
	Key   string
	Value string
}

// AstNode represents a GSP node.  Each node has a type, and depending on that
// type it may have inner text, child nodes, or attributes.  Some nodes may also
// have the newline flag.
type AstNode struct {
	Type     nodeType
	Text     string
	Attrs    []Attr
	Children []AstNode
}

// ParseFile reads and parses a GSP-formatted text file and returns a GSP AST.
func ParseFile(file *os.File) (AstNode, error) {
	r := reader{r: bufio.NewReader(file)}
	document := AstNode{Type: Tagless}

	for {
		if _, err := r.readNonSpaceRune(); err == io.EOF {
			return document, nil
		} else if err != nil {
			return AstNode{}, err
		} else if err := r.unreadRune(); err != nil {
			return AstNode{}, err
		}

		if err := r.skipSpaces(); err != nil {
			return AstNode{}, err
		}

		if node, err := r.parseNode(); err != nil {
			return AstNode{}, err
		} else {
			document.Children = append(document.Children, node)
		}
	}
}

// parseNode parses the next node in the GSP document, and may call itself
// recursively on any child nodes.
func (reader *reader) parseNode() (node AstNode, err error) {
	if err = reader.skipSpaces(); err != nil {
		return
	}

	r, err := reader.peekRune()
	if err != nil {
		return
	}

	if r == '-' || r == '=' {
		return reader.parseText(r == '=')
	}

	if node.Text, err = reader.parseNodeName(); err != nil {
		return
	} else {
		node.Type = Normal
	}

	if node.Attrs, err = reader.parseAttrs(); err != nil {
		return
	}

	// The above call to reader.parseAttrs() guarantees that we have the ‘{’
	// token.
	if _, err = reader.readRune(); err != nil {
		return
	}

loop:
	for {
		if err = reader.skipSpaces(); err != nil {
			return
		}

		if r, err = reader.peekRune(); err == io.EOF {
			return AstNode{}, eof{}
		} else if err != nil {
			return
		} else if r == '}' {
			break loop
		}

		var n AstNode
		if n, err = reader.parseNode(); err != nil {
			return
		} else {
			node.Children = append(node.Children, n)
		}
	}

	// The above loop guarantees that we have the ‘}’ token.
	if _, err = reader.readRune(); err != nil {
		return
	}
	return
}

// parseNodeName parses the next node name, validating it to ensure it is a
// valid XML node name.
func (reader *reader) parseNodeName() (string, error) {
	var r rune
	var err error

	if err = reader.skipSpaces(); err != nil {
		return "", err
	}

	sb := strings.Builder{}

	if r, err = reader.readRune(); err != nil {
		return "", err
	} else if !validNameStartChar(r) {
		return "", invalidSyntax{
			pos:      reader.pos,
			expected: "node name",
			found:    fmt.Sprintf("invalid character ‘%c’", r),
		}
	}

	for validNameChar(r) {
		sb.WriteRune(r)
		if r, err = reader.readRune(); err != nil {
			return "", err
		}
	}

	if err = reader.unreadRune(); err != nil {
		return "", err
	}
	return sb.String(), nil
}

// parseText parses the text that can be found within an outer node.  It also
// detects embedded nodes using ‘@’ syntax and calls ‘reader.parseNode()’ on
// them.
func (reader *reader) parseText(trim bool) (AstNode, error) {
	if _, err := reader.readRune(); err != nil {
		return AstNode{}, err
	}

	sb := strings.Builder{}
	node := AstNode{}
	if trim {
		node.Type = TaglessTrim
	} else {
		node.Type = Tagless
	}

loop:
	for {
		r, err := reader.readRune()
		if err != nil {
			return AstNode{}, err
		}
		switch r {
		case '}':
			if err := reader.unreadRune(); err != nil {
				return AstNode{}, err
			}
			break loop
		case '@':
			node.Children = append(node.Children, AstNode{
				Type: Text,
				Text: sb.String(),
			})
			sb = strings.Builder{}

			n, err := reader.parseNode()
			if err != nil {
				return AstNode{}, err
			}
			node.Children = append(node.Children, n)
		case '\\':
			r, err = reader.readRune()
			if err != nil {
				return AstNode{}, err
			}
			if r != '\\' && r != '@' && r != '}' {
				return AstNode{}, invalidSyntax{
					pos:      reader.pos,
					expected: "valid escape sequence (‘\\\\’, ‘\\@’, or ‘\\}’)",
					found:    fmt.Sprintf("‘\\%c’", r),
				}
			}
			fallthrough
		default:
			sb.WriteRune(r)
		}
	}

	node.Children = append(node.Children, AstNode{
		Type: Text,
		Text: sb.String(),
	})
	return node, nil
}

// parseAttrs parses the next nodes attributes.  It also parses shorthand
// class- and ID syntax.
func (reader *reader) parseAttrs() ([]Attr, error) {
	attrs := make([]Attr, 0, 2)

loop:
	for {
		if err := reader.skipSpaces(); err != nil {
			return nil, err
		}
		r, err := reader.peekRune()
		if err != nil {
			return nil, err
		}

		attr := Attr{}
		switch r {
		case '{':
			break loop
		case '.', '#':
			sym := r

			// Skip ‘sym’
			if _, err := reader.readRune(); err != nil {
				return nil, err
			}

			if s, err := reader.parseShorthand(); err != nil {
				return nil, err
			} else {
				attr.Value = s
				if sym == '.' {
					attr.Key = "class"
				} else {
					attr.Key = "id"
				}
			}
		default:
			if unicode.IsSpace(r) {
				if err := reader.skipSpaces(); err != nil {
					return nil, err
				}
				continue
			}

			if s, err := reader.parseNodeName(); err != nil {
				return nil, err
			} else {
				attr.Key = s
			}

			if r, err := reader.readNonSpaceRune(); err != nil {
				return nil, err
			} else if r != '=' {
				reader.unreadRune()
				break
			}

			if s, err := reader.parseString(); err != nil {
				return nil, err
			} else {
				attr.Value = s
			}
		}
		attrs = append(attrs, attr)
	}

	return attrs, nil
}

// parseShorthand parses an ID- or class shorthand value.
func (reader *reader) parseShorthand() (string, error) {
	sb := strings.Builder{}

	for {
		r, err := reader.readRune()
		if err != nil {
			return "", err
		}

		if unicode.IsSpace(r) {
			break
		}
		sb.WriteRune(r)
	}

	s := sb.String()
	if len(s) == 0 {
		return "", invalidSyntax{
			pos:      reader.pos,
			expected: "id- or class name",
			found:    "no value",
		}
	}
	return s, nil
}

// parseString parses the double quoted strings used as attribute values.
func (reader *reader) parseString() (string, error) {
	sb := strings.Builder{}

	if r, err := reader.readNonSpaceRune(); err != nil {
		return "", err
	} else if r != '"' {
		return "", invalidSyntax{
			pos:      reader.pos,
			expected: "double-quoted string",
			found:    fmt.Sprintf("‘%c’", r),
		}
	}

	for {
		r, err := reader.readRune()
		if err != nil {
			return "", err
		}

		switch r {
		case '"':
			return sb.String(), nil
		case '\\':
			r, err := reader.readRune()
			if err != nil {
				return "", err
			}

			if r != '\\' && r != '"' {
				return "", invalidSyntax{
					pos:      reader.pos,
					expected: "valid escape sequence (‘\\\\’ or ‘\\\"’)",
					found:    fmt.Sprintf("‘\\%c’", r),
				}
			}

			sb.WriteRune(r)
		default:
			sb.WriteRune(r)
		}
	}
}

// validNameStartChar returns whether or not the rune ‘r’ is a legal rune in the
// first position an XML tag name.
func validNameStartChar(r rune) bool {
	return r == ':' || r == '_' ||
		(r >= 'A' && r <= 'Z') ||
		(r >= 'a' && r <= 'z') ||
		(r >= 0x000C0 && r <= 0x000D6) ||
		(r >= 0x000D8 && r <= 0x000F6) ||
		(r >= 0x000F8 && r <= 0x002FF) ||
		(r >= 0x00370 && r <= 0x0037D) ||
		(r >= 0x0037F && r <= 0x01FFF) ||
		(r >= 0x0200C && r <= 0x0200D) ||
		(r >= 0x02070 && r <= 0x0218F) ||
		(r >= 0x02C00 && r <= 0x02FEF) ||
		(r >= 0x03001 && r <= 0x0D7FF) ||
		(r >= 0x0F900 && r <= 0x0FDCF) ||
		(r >= 0x0FDF0 && r <= 0x0FFFD) ||
		(r >= 0x10000 && r <= 0xEFFFF)
}

// validNameChar returns whether or not the rune ‘r’ is a legal rune in an XML
// tag name.
func validNameChar(r rune) bool {
	return validNameStartChar(r) ||
		r == '-' || r == '.' || r == '·' ||
		(r >= '0' && r <= '9') ||
		(r >= 0x0300 && r <= 0x036F) ||
		(r >= 0x203F && r <= 0x2040)
}