-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader.go
More file actions
383 lines (340 loc) · 8.07 KB
/
reader.go
File metadata and controls
383 lines (340 loc) · 8.07 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
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
// Copyright 2026 The Zaparoo Project Contributors.
// SPDX-License-Identifier: Apache-2.0
//
// 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 zapscript
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"sort"
"strings"
"unicode/utf8"
)
// AdvArgs is a wrapper around raw advanced arguments that enforces type-safe access.
// Direct map access is not allowed; use the getter/setter methods for pre-parse operations.
type AdvArgs struct {
raw map[string]string
}
func NewAdvArgs(m map[string]string) AdvArgs {
return AdvArgs{raw: m}
}
func (a AdvArgs) Get(key Key) string {
return a.raw[string(key)]
}
// With returns a new AdvArgs with the key set to value. Does not mutate the receiver.
func (a AdvArgs) With(key Key, value string) AdvArgs {
newMap := make(map[string]string, len(a.raw)+1)
for k, v := range a.raw {
newMap[k] = v
}
newMap[string(key)] = value
return AdvArgs{raw: newMap}
}
func (a AdvArgs) GetWhen() (string, bool) {
v, ok := a.raw[string(KeyWhen)]
return v, ok
}
func (a AdvArgs) IsEmpty() bool {
return len(a.raw) == 0
}
func (a AdvArgs) Range(fn func(key Key, value string) bool) {
for k, v := range a.raw {
if !fn(Key(k), v) {
return
}
}
}
func (a AdvArgs) Raw() map[string]string {
return a.raw
}
func (a AdvArgs) MarshalJSON() ([]byte, error) {
if a.raw == nil {
return []byte("null"), nil
}
b, err := json.Marshal(a.raw)
if err != nil {
return nil, fmt.Errorf("failed to marshal AdvArgs: %w", err)
}
return b, nil
}
func (a *AdvArgs) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &a.raw); err != nil {
return fmt.Errorf("failed to unmarshal AdvArgs: %w", err)
}
return nil
}
type Command struct {
AdvArgs AdvArgs
Name string
Args []string
}
// argNeedsQuoting returns true if the arg contains characters that require
// double-quoting to be safely represented in ZapScript.
func argNeedsQuoting(s string) bool {
for _, ch := range s {
switch ch {
case SymArgSep, SymArgStart, SymAdvArgStart, SymAdvArgSep,
SymAdvArgEq, SymArgDoubleQuote, SymArgSingleQuote, SymCmdSep,
SymEscapeSeq, SymCmdStart, SymExpressionStart, SymTraitsStart,
SymJSONStart, '\n', '\r', '\t':
return true
}
}
return false
}
// escapeArg re-escapes control characters using ZapScript escape sequences
// and wraps the arg in double quotes.
func escapeArg(s string) string {
var b strings.Builder
_, _ = b.WriteRune('"')
for _, ch := range s {
switch ch {
case '"':
_, _ = b.WriteRune(SymEscapeSeq)
_, _ = b.WriteRune('"')
case '\n':
_, _ = b.WriteRune(SymEscapeSeq)
_, _ = b.WriteRune('n')
case '\r':
_, _ = b.WriteRune(SymEscapeSeq)
_, _ = b.WriteRune('r')
case '\t':
_, _ = b.WriteRune(SymEscapeSeq)
_, _ = b.WriteRune('t')
case SymEscapeSeq:
_, _ = b.WriteRune(SymEscapeSeq)
_, _ = b.WriteRune(SymEscapeSeq)
case SymExpressionStart:
_, _ = b.WriteRune(SymEscapeSeq)
_, _ = b.WriteRune(SymExpressionStart)
default:
_, _ = b.WriteRune(ch)
}
}
_, _ = b.WriteRune('"')
return b.String()
}
// String returns the canonical ZapScript representation of the command.
// The output is valid ZapScript that can be re-parsed to produce an
// equivalent Command.
func (c Command) String() string {
var b strings.Builder
_, _ = b.WriteString("**")
_, _ = b.WriteString(c.Name)
if len(c.Args) > 0 {
_, _ = b.WriteRune(SymArgStart)
if isInputMacroCmd(normalizeCmdName(c.Name)) {
// Input macro commands concatenate args directly
for _, arg := range c.Args {
if len(arg) > 1 && rune(arg[0]) == SymInputMacroExtStart &&
rune(arg[len(arg)-1]) == SymInputMacroExtEnd {
_, _ = b.WriteString(arg)
} else {
for _, ch := range arg {
switch ch {
case SymInputMacroEscapeSeq:
_, _ = b.WriteRune(SymInputMacroEscapeSeq)
_, _ = b.WriteRune(ch)
case SymAdvArgStart, SymExpressionStart, SymInputMacroExtStart, SymCmdSep:
_, _ = b.WriteRune(SymInputMacroEscapeSeq)
_, _ = b.WriteRune(ch)
default:
_, _ = b.WriteRune(ch)
}
}
}
}
} else {
for i, arg := range c.Args {
if i > 0 {
_, _ = b.WriteRune(SymArgSep)
}
if arg == "" || argNeedsQuoting(arg) {
_, _ = b.WriteString(escapeArg(arg))
} else {
_, _ = b.WriteString(arg)
}
}
}
}
if !c.AdvArgs.IsEmpty() {
_, _ = b.WriteRune(SymAdvArgStart)
// Collect and sort keys for deterministic output
var keys []string
c.AdvArgs.Range(func(key Key, _ string) bool {
keys = append(keys, string(key))
return true
})
sort.Strings(keys)
for i, key := range keys {
if i > 0 {
_, _ = b.WriteRune(SymAdvArgSep)
}
_, _ = b.WriteString(key)
_, _ = b.WriteRune(SymAdvArgEq)
value := c.AdvArgs.Get(Key(key))
if argNeedsQuoting(value) {
_, _ = b.WriteString(escapeArg(value))
} else {
_, _ = b.WriteString(value)
}
}
}
return b.String()
}
type Script struct {
Traits map[string]any `json:"traits,omitempty"`
Cmds []Command `json:"cmds"`
}
type PostArgPartType int
const (
ArgPartTypeUnknown PostArgPartType = iota
ArgPartTypeString
ArgPartTypeExpression
)
type PostArgPart struct {
Value string
Type PostArgPartType
}
type mediaTitleParseResult struct {
advArgs map[string]string
rawContent string
valid bool
}
type ScriptReader struct {
r *bufio.Reader
pos int64
}
func NewParser(value string) *ScriptReader {
return &ScriptReader{
r: bufio.NewReader(bytes.NewReader([]byte(value))),
}
}
func (sr *ScriptReader) read() (rune, error) {
ch, _, err := sr.r.ReadRune()
if errors.Is(err, io.EOF) {
return eof, nil
} else if err != nil {
return eof, fmt.Errorf("failed to read rune: %w", err)
}
sr.pos++
return ch, nil
}
func (sr *ScriptReader) unread() error {
err := sr.r.UnreadRune()
if err != nil {
return fmt.Errorf("failed to unread rune: %w", err)
}
sr.pos--
return nil
}
func (sr *ScriptReader) peek() (rune, error) {
for peekBytes := 4; peekBytes > 0; peekBytes-- {
b, err := sr.r.Peek(peekBytes)
if err == nil {
r, _ := utf8.DecodeRune(b)
if r == utf8.RuneError {
return r, errors.New("rune error")
}
return r, nil
}
}
return eof, nil
}
func (sr *ScriptReader) skip() error {
_, err := sr.read()
if err != nil {
return err
}
return nil
}
func (sr *ScriptReader) checkEndOfCmd(ch rune) (bool, error) {
if ch != SymCmdSep {
return false, nil
}
next, err := sr.peek()
if err != nil {
return false, err
}
switch next {
case eof:
return true, nil
case SymCmdSep:
err := sr.skip()
if err != nil {
return false, err
}
return true, nil
default:
return false, nil
}
}
func (sr *ScriptReader) parseEscapeSeq() (string, error) {
ch, err := sr.read()
if err != nil {
return "", err
}
switch ch {
case eof:
return "", nil
case 'n':
return "\n", nil
case 'r':
return "\r", nil
case 't':
return "\t", nil
case SymEscapeSeq:
return string(SymEscapeSeq), nil
case SymArgDoubleQuote:
return string(SymArgDoubleQuote), nil
case SymArgSingleQuote:
return string(SymArgSingleQuote), nil
default:
return string(ch), nil
}
}
func (sr *ScriptReader) parseQuotedArg(start rune) (string, error) {
arg := ""
for {
ch, err := sr.read()
if err != nil {
return arg, err
} else if ch == eof {
return arg, ErrUnmatchedQuote
}
if ch == SymEscapeSeq {
next, err := sr.parseEscapeSeq()
if err != nil {
return arg, err
}
arg += next
continue
} else if ch == SymExpressionStart {
exprValue, err := sr.parseExpression()
if err != nil {
return arg, err
}
arg += exprValue
continue
}
if ch == start {
break
}
arg += string(ch)
}
return arg, nil
}