generated from ianlewis/repo-template
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathini_example_test.go
More file actions
312 lines (256 loc) · 8.25 KB
/
ini_example_test.go
File metadata and controls
312 lines (256 loc) · 8.25 KB
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
// Copyright 2025 Ian Lewis
//
// 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 lexparse_test
import (
"context"
"errors"
"fmt"
"io"
"regexp"
"strings"
"github.com/ianlewis/lexparse"
)
const (
// lexINITypeIden represents an identifier token (key or section name).
lexINITypeIden lexparse.TokenType = iota
// lexINITypeOper represents an operator token.
lexINITypeOper
// lexINITypeValue represents a property value token.
lexINITypeValue
// lexINITypeComment represents a comment token.
lexINITypeComment
)
type iniNodeType int
const (
// iniNodeTypeRoot represents the root node of the INI parse tree.
iniNodeTypeRoot iniNodeType = iota
// iniNodeTypeSection represents a section node in the INI parse tree.
iniNodeTypeSection
// iniNodeTypeProperty represents a property node in the INI parse tree.
iniNodeTypeProperty
)
type iniNode struct {
typ iniNodeType
// sectionName is only used for section nodes.
sectionName string
// propertyName and propertyValue are only used for property nodes.
propertyName string
propertyValue string
}
func (n *iniNode) String() string {
switch n.typ {
case iniNodeTypeRoot:
return "root"
case iniNodeTypeSection:
return fmt.Sprintf("[%s]", n.sectionName)
case iniNodeTypeProperty:
return fmt.Sprintf("%s = %s", n.propertyName, n.propertyValue)
default:
return "<Unknown>"
}
}
var iniIdenRegexp = regexp.MustCompile(`^[A-Za-z0-9]+$`)
var (
errINIIdentifier = errors.New("unexpected identifier")
errINISectionName = errors.New("invalid section name")
errINIPropertyName = errors.New("invalid property name")
)
// lexINI is the initial lexer state for INI files.
//
//nolint:ireturn // returning the generic interface is needed to return the previous value.
func lexINI(ctx *lexparse.CustomLexerContext) (lexparse.LexState, error) {
for {
rn := ctx.Peek()
switch rn {
case ' ', '\t', '\r', '\n':
ctx.Discard()
case '[', ']', '=':
return lexparse.LexStateFn(lexINIOper), nil
case ';', '#':
return lexparse.LexStateFn(lexINIComment), nil
case lexparse.EOF:
return nil, io.EOF
default:
return lexparse.LexStateFn(lexINIIden), nil
}
}
}
// lexINIOper lexes an operator token.
//
//nolint:ireturn // returning the generic interface is needed to return the previous value.
func lexINIOper(ctx *lexparse.CustomLexerContext) (lexparse.LexState, error) {
oper := ctx.NextRune()
ctx.Emit(lexINITypeOper)
if oper == '=' {
return lexparse.LexStateFn(lexINIValue), nil
}
return lexparse.LexStateFn(lexINI), nil
}
// lexINIIden lexes an identifier token (section name or property key).
//
//nolint:ireturn // returning the generic interface is needed to return the previous value.
func lexINIIden(ctx *lexparse.CustomLexerContext) (lexparse.LexState, error) {
if next := ctx.Find([]string{"]", "="}); next != "" {
ctx.Emit(lexINITypeIden)
return lexparse.LexStateFn(lexINIOper), nil
}
return nil, io.ErrUnexpectedEOF
}
// lexINIValue lexes a property value token.
//
//nolint:ireturn // returning the generic interface is needed to return the previous value.
func lexINIValue(ctx *lexparse.CustomLexerContext) (lexparse.LexState, error) {
ctx.Find([]string{";", "\n"})
ctx.Emit(lexINITypeValue)
return lexparse.LexStateFn(lexINI), nil
}
// lexINIComment lexes a comment token.
//
//nolint:ireturn // returning the generic interface is needed to return the previous value.
func lexINIComment(ctx *lexparse.CustomLexerContext) (lexparse.LexState, error) {
ctx.Find([]string{"\n"})
ctx.Emit(lexINITypeComment)
return lexparse.LexStateFn(lexINI), nil
}
// iniTokenErr formats an error message with token context.
func iniTokenErr(err error, t *lexparse.Token) error {
return fmt.Errorf("%w: %q, line %d, column %d", err,
t.Value, t.Start.Line, t.Start.Column)
}
// parseINIInit is the initial parser state for INI files.
func parseINIInit(ctx *lexparse.ParserContext[*iniNode]) error {
// Replace the root node with a new root node.
_ = ctx.Replace(&iniNode{
typ: iniNodeTypeRoot,
})
// Create the empty section node for the global section.
_ = ctx.Push(&iniNode{
typ: iniNodeTypeSection,
sectionName: "",
})
ctx.PushState(lexparse.ParseStateFn(parseINI))
return nil
}
// parseINI parses the top-level structure of an INI file.
func parseINI(ctx *lexparse.ParserContext[*iniNode]) error {
t := ctx.Peek()
switch t.Type {
case lexINITypeOper:
ctx.PushState(lexparse.ParseStateFn(parseSection))
case lexINITypeIden:
ctx.PushState(lexparse.ParseStateFn(parseProperty))
case lexINITypeComment:
_ = ctx.Next() // Discard comment
ctx.PushState(lexparse.ParseStateFn(parseINI))
case lexparse.TokenTypeEOF:
return nil
default:
return iniTokenErr(errINIIdentifier, t)
}
return nil
}
// parseSection parses a section header.
func parseSection(ctx *lexparse.ParserContext[*iniNode]) error {
openBracket := ctx.Next()
if openBracket.Type != lexINITypeOper || openBracket.Value != "[" {
return iniTokenErr(errINIIdentifier, openBracket)
}
sectionToken := ctx.Next()
if sectionToken.Type != lexINITypeIden {
return iniTokenErr(errINIIdentifier, sectionToken)
}
closeBracket := ctx.Next()
if closeBracket.Type != lexINITypeOper || closeBracket.Value != "]" {
return iniTokenErr(errINIIdentifier, closeBracket)
}
sectionName := strings.TrimSpace(sectionToken.Value)
// Validate the section name.
if !iniIdenRegexp.MatchString(sectionName) {
return iniTokenErr(errINISectionName, sectionToken)
}
// Create a new node for the section and push it onto the parse tree.
// The current node is now the new section node.
_ = ctx.Climb()
_ = ctx.Push(&iniNode{
typ: iniNodeTypeSection,
sectionName: sectionName,
})
ctx.PushState(lexparse.ParseStateFn(parseINI))
return nil
}
// parseProperty parses a property key-value pair.
func parseProperty(ctx *lexparse.ParserContext[*iniNode]) error {
keyToken := ctx.Next()
if keyToken.Type != lexINITypeIden {
return iniTokenErr(errINIIdentifier, keyToken)
}
keyName := strings.TrimSpace(keyToken.Value)
// Validate the property name.
if !iniIdenRegexp.MatchString(keyName) {
return iniTokenErr(errINIPropertyName, keyToken)
}
eqToken := ctx.Next()
if eqToken.Type != lexINITypeOper || eqToken.Value != "=" {
return iniTokenErr(errINIIdentifier, eqToken)
}
valueToken := ctx.Next()
if valueToken.Type != lexINITypeValue {
return iniTokenErr(errINIIdentifier, valueToken)
}
// Create a new node for the property and add it to the current section.
ctx.Node(&iniNode{
typ: iniNodeTypeProperty,
propertyName: keyName,
propertyValue: strings.TrimSpace(valueToken.Value),
})
ctx.PushState(lexparse.ParseStateFn(parseINI))
return nil
}
// Example_iniParser demonstrates parsing a simple INI file. It does not support
// nested sections, or escape sequences.
func Example_iniParser() {
r := strings.NewReader(`; last modified 1 April 2001 by John Doe
[owner]
name = John Doe
organization = Acme Widgets Inc.
[database]
; use IP address in case network name resolution is not working
server = 192.0.2.62
port = 143
file = "payroll.dat"
`)
// Produces a tree representation of the INI file.
// Each child of the root node is a section node, which in turn
// has property nodes as children. The global section is represented
// as a section node with an empty name.
tree, err := lexparse.LexParse(
context.Background(),
lexparse.NewCustomLexer(r, lexparse.LexStateFn(lexINI)),
lexparse.ParseStateFn(parseINIInit),
)
if err != nil {
panic(err)
}
fmt.Print(tree)
// Output:
// root (0:0)
// ├── [] (0:0)
// ├── [owner] (2:7)
// │ ├── name = John Doe (3:7)
// │ └── organization = Acme Widgets Inc. (4:15)
// └── [database] (6:10)
// ├── server = 192.0.2.62 (8:9)
// ├── port = 143 (9:7)
// └── file = "payroll.dat" (10:7)
}