Debian Codegraph @

syntax/nodes.go

raw
1 // Copyright (c) 2016, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package syntax
5
6 import (
7 "math"
8 "strconv"
9 "strings"
10 )
11
12 // Node represents a syntax tree node.
13 type Node interface {
14 // Pos returns the position of the first character of the node. Comments
15 // are ignored, except if the node is a [*File].
16 Pos() Pos
17 // End returns the position of the character immediately after the node.
18 // If the character is a newline, the line number won't cross into the
19 // next line. Comments are ignored, except if the node is a [*File].
20 End() Pos
21 }
22
23 // File represents a shell source file.
24 type File struct {
25 Name string
26
27 Stmts []*Stmt
28 Last []Comment
29 }
30
31 func (f *File) Pos() Pos { return stmtsPos(f.Stmts, f.Last) }
32 func (f *File) End() Pos { return stmtsEnd(f.Stmts, f.Last) }
33
34 func stmtsPos(stmts []*Stmt, last []Comment) Pos {
35 if len(stmts) > 0 {
36 s := stmts[0]
37 sPos := s.Pos()
38 if len(s.Comments) > 0 {
39 if cPos := s.Comments[0].Pos(); sPos.After(cPos) {
40 return cPos
41 }
42 }
43 return sPos
44 }
45 if len(last) > 0 {
46 return last[0].Pos()
47 }
48 return Pos{}
49 }
50
51 func stmtsEnd(stmts []*Stmt, last []Comment) Pos {
52 if len(last) > 0 {
53 return last[len(last)-1].End()
54 }
55 if len(stmts) > 0 {
56 s := stmts[len(stmts)-1]
57 sEnd := s.End()
58 if len(s.Comments) > 0 {
59 // The comments are sorted by position; a comment which trails
60 // the statement on the same line is last.
61 if cEnd := s.Comments[len(s.Comments)-1].End(); cEnd.After(sEnd) {
62 return cEnd
63 }
64 }
65 return sEnd
66 }
67 return Pos{}
68 }
69
70 // Pos is a position within a shell source file.
71 type Pos struct {
72 offs, lineCol uint32
73 }
74
75 const (
76 // Offsets use 32 bits for a reasonable amount of precision.
77 // We reserve a few of the highest values to represent types of invalid positions.
78 // We leave some space before the real uint32 maximum so that we can easily detect
79 // when arithmetic on invalid positions is done by mistake.
80 offsetRecovered = math.MaxUint32 - 10
81 offsetMax = math.MaxUint32 - 11
82
83 // We used to split line and column numbers evenly in 16 bits, but line numbers
84 // are significantly more important in practice. Use more bits for them.
85
86 lineBitSize = 18
87 lineMax = (1 << lineBitSize) - 1
88
89 colBitSize = 32 - lineBitSize
90 colMax = (1 << colBitSize) - 1
91 colBitMask = colMax
92 )
93
94 // TODO(v4): consider using uint32 for Offset/Line/Col to better represent bit sizes.
95 // Or go with int64, which more closely resembles portable "sizes" elsewhere.
96 // The latter is probably nicest, as then we can change the number of internal
97 // bits later, and we can also do overflow checks for the user in NewPos.
98
99 // NewPos creates a position with the given offset, line, and column.
100 //
101 // Note that [Pos] uses a limited number of bits to store these numbers.
102 // If line or column overflow their allocated space, they are replaced with 0.
103 func NewPos(offset, line, column uint) Pos {
104 // Basic protection against offset overflow;
105 // note that an offset of 0 is valid, so we leave the maximum.
106 offset = min(offset, offsetMax)
107 if line > lineMax {
108 line = 0 // protect against overflows; rendered as "?"
109 }
110 if column > colMax {
111 column = 0 // protect against overflows; rendered as "?"
112 }
113 return Pos{
114 offs: uint32(offset),
115 lineCol: (uint32(line) << colBitSize) | uint32(column),
116 }
117 }
118
119 // Offset returns the byte offset of the position in the original source file.
120 // Byte offsets start at 0. Invalid positions always report the offset 0.
121 //
122 // Offset has basic protection against overflows; if an input is too large,
123 // offset numbers will stop increasing past a very large number.
124 func (p Pos) Offset() uint {
125 if p.offs > offsetMax {
126 return 0 // invalid
127 }
128 return uint(p.offs)
129 }
130
131 // Line returns the line number of the position, starting at 1.
132 // Invalid positions always report the line number 0.
133 //
134 // Line is protected against overflows; if an input has too many lines, extra
135 // lines will have a line number of 0, rendered as "?" by [Pos.String].
136 func (p Pos) Line() uint { return uint(p.lineCol >> colBitSize) }
137
138 // Col returns the column number of the position, starting at 1. It counts in
139 // bytes. Invalid positions always report the column number 0.
140 //
141 // Col is protected against overflows; if an input line has too many columns,
142 // extra columns will have a column number of 0, rendered as "?" by [Pos.String].
143 func (p Pos) Col() uint { return uint(p.lineCol & colBitMask) }
144
145 func (p Pos) String() string {
146 var b strings.Builder
147 if line := p.Line(); line > 0 {
148 b.WriteString(strconv.FormatUint(uint64(line), 10))
149 } else {
150 b.WriteByte('?')
151 }
152 b.WriteByte(':')
153 if col := p.Col(); col > 0 {
154 b.WriteString(strconv.FormatUint(uint64(col), 10))
155 } else {
156 b.WriteByte('?')
157 }
158 return b.String()
159 }
160
161 // IsValid reports whether the position contains useful position information.
162 // Some positions returned via [Parse] may be invalid: for example, [Stmt.Semicolon]
163 // will only be valid if a statement contained a closing token such as ';'.
164 //
165 // Recovered positions, as reported by [Pos.IsRecovered], are not considered valid
166 // given that they don't contain position information.
167 func (p Pos) IsValid() bool {
168 return p.offs <= offsetMax && p.lineCol != 0
169 }
170
171 var recoveredPos = Pos{offs: offsetRecovered}
172
173 // IsRecovered reports whether the position that the token or node belongs to
174 // was missing in the original input and recovered via [RecoverErrors].
175 func (p Pos) IsRecovered() bool { return p == recoveredPos }
176
177 // After reports whether the position p is after p2. It is a more expressive
178 // version of p.Offset() > p2.Offset().
179 // It always returns false if p is an invalid position.
180 func (p Pos) After(p2 Pos) bool {
181 if !p.IsValid() {
182 return false
183 }
184 return p.offs > p2.offs
185 }
186
187 func posAddCol(p Pos, n int) Pos {
188 if !p.IsValid() {
189 return p
190 }
191 // Clamp the offset, and drop columns which no longer fit,
192 // just like [NewPos] does. Note that a column of zero is already unknown,
193 // so adding to it would only make up a number.
194 offs := min(max(int64(p.offs)+int64(n), 0), offsetMax)
195 col := int64(p.Col())
196 if col > 0 {
197 if col += int64(n); col < 1 || col > colMax {
198 col = 0 // protect against overflows; rendered as "?"
199 }
200 }
201 p.offs = uint32(offs)
202 p.lineCol = (p.lineCol &^ colBitMask) | uint32(col)
203 return p
204 }
205
206 func posMax(p1, p2 Pos) Pos {
207 if p2.After(p1) {
208 return p2
209 }
210 return p1
211 }
212
213 // Comment represents a single comment on a single line.
214 type Comment struct {
215 Hash Pos
216 Text string
217 }
218
219 func (c *Comment) Pos() Pos { return c.Hash }
220 func (c *Comment) End() Pos { return posAddCol(c.Hash, 1+len(c.Text)) }
221
222 // Stmt represents a statement, also known as a "complete command". It is
223 // compromised of a command and other components that may come before or after
224 // it.
225 type Stmt struct {
226 Comments []Comment
227 Cmd Command
228 Position Pos
229 Semicolon Pos // position of ';', '&', or '|&', if any
230 Negated bool // ! stmt
231 Background bool // stmt &
232 Coprocess bool // mksh's |&
233 Disown bool // zsh's &| or &!
234
235 Redirs []*Redirect // stmt >a <b
236 }
237
238 func (s *Stmt) Pos() Pos { return s.Position }
239 func (s *Stmt) End() Pos {
240 if s.Semicolon.IsValid() {
241 end := posAddCol(s.Semicolon, 1) // ';' or '&'
242 if s.Coprocess || s.Disown {
243 end = posAddCol(end, 1) // '|&' or '&|' or '&!'
244 }
245 return end
246 }
247 end := s.Position
248 if s.Negated {
249 end = posAddCol(end, 1)
250 }
251 if s.Cmd != nil {
252 end = s.Cmd.End()
253 }
254 if len(s.Redirs) > 0 {
255 end = posMax(end, s.Redirs[len(s.Redirs)-1].End())
256 }
257 return end
258 }
259
260 // Command represents all nodes that are simple or compound commands, including
261 // function declarations.
262 //
263 // These are [*CallExpr], [*IfClause], [*WhileClause], [*ForClause], [*CaseClause],
264 // [*Block], [*Subshell], [*BinaryCmd], [*FuncDecl], [*ArithmCmd], [*TestClause],
265 // [*DeclClause], [*LetClause], [*TimeClause], and [*CoprocClause].
266 type Command interface {
267 Node
268 commandNode()
269 }
270
271 func (*CallExpr) commandNode() {}
272 func (*IfClause) commandNode() {}
273 func (*WhileClause) commandNode() {}
274 func (*ForClause) commandNode() {}
275 func (*CaseClause) commandNode() {}
276 func (*Block) commandNode() {}
277 func (*Subshell) commandNode() {}
278 func (*BinaryCmd) commandNode() {}
279 func (*FuncDecl) commandNode() {}
280 func (*ArithmCmd) commandNode() {}
281 func (*TestClause) commandNode() {}
282 func (*DeclClause) commandNode() {}
283 func (*LetClause) commandNode() {}
284 func (*TimeClause) commandNode() {}
285 func (*CoprocClause) commandNode() {}
286 func (*TestDecl) commandNode() {}
287
288 // Assign represents an assignment to a variable.
289 //
290 // Here and elsewhere, Index can mean either an index expression into an indexed
291 // array, or a string key into an associative array.
292 //
293 // If Index is non-nil, the value will be a word and not an array as nested
294 // arrays are not allowed.
295 //
296 // If Naked is true and Name is nil, the assignment is part of a [DeclClause] and
297 // the argument (in the Value field) will be evaluated at run-time. This
298 // includes parameter expansions, which may expand to assignments or options.
299 type Assign struct {
300 Append bool // +=
301 Naked bool // without '='
302 Name *Lit // must be a valid name
303 Index ArithmExpr // [i], ["k"]
304 Value *Word // =val
305 Array *ArrayExpr // =(arr)
306 }
307
308 func (a *Assign) Pos() Pos {
309 if a.Name == nil {
310 return a.Value.Pos()
311 }
312 return a.Name.Pos()
313 }
314
315 func (a *Assign) End() Pos {
316 if a.Value != nil {
317 return a.Value.End()
318 }
319 if a.Array != nil {
320 return a.Array.End()
321 }
322 if a.Index != nil {
323 if a.Naked {
324 return posAddCol(a.Index.End(), len("]"))
325 }
326 return posAddCol(a.Index.End(), len("]="))
327 }
328 if a.Naked {
329 return a.Name.End()
330 }
331 return posAddCol(a.Name.End(), 1)
332 }
333
334 // Redirect represents an input/output redirection.
335 type Redirect struct {
336 OpPos Pos
337 Op RedirOperator
338 N *Lit // fd>, or {varname}> with [LangBash] or [LangZsh]
339 Word *Word // >word
340 Hdoc *Word // here-document body
341 }
342
343 func (r *Redirect) Pos() Pos {
344 if r.N != nil {
345 return r.N.Pos()
346 }
347 return r.OpPos
348 }
349
350 func (r *Redirect) End() Pos {
351 if r.Hdoc != nil {
352 return r.Hdoc.End()
353 }
354 return r.Word.End()
355 }
356
357 // CallExpr represents a command execution or function call, otherwise known as
358 // a "simple command".
359 //
360 // If Args is empty, Assigns apply to the shell environment. Otherwise, they are
361 // variables that cannot be arrays and which only apply to the call.
362 type CallExpr struct {
363 Assigns []*Assign // a=x b=y args
364 Args []*Word
365 }
366
367 func (c *CallExpr) Pos() Pos {
368 if len(c.Assigns) > 0 {
369 return c.Assigns[0].Pos()
370 }
371 return c.Args[0].Pos()
372 }
373
374 func (c *CallExpr) End() Pos {
375 if len(c.Args) == 0 {
376 return c.Assigns[len(c.Assigns)-1].End()
377 }
378 return c.Args[len(c.Args)-1].End()
379 }
380
381 // Subshell represents a series of commands that should be executed in a nested
382 // shell environment.
383 type Subshell struct {
384 Lparen, Rparen Pos
385
386 Stmts []*Stmt
387 Last []Comment
388 }
389
390 func (s *Subshell) Pos() Pos { return s.Lparen }
391 func (s *Subshell) End() Pos { return posAddCol(s.Rparen, 1) }
392
393 // Block represents a series of commands that should be executed in a nested
394 // scope. It is essentially a list of statements within curly braces.
395 type Block struct {
396 Lbrace, Rbrace Pos
397
398 Stmts []*Stmt
399 Last []Comment
400 }
401
402 func (b *Block) Pos() Pos { return b.Lbrace }
403 func (b *Block) End() Pos { return posAddCol(b.Rbrace, 1) }
404
405 // IfClause represents an if statement.
406 type IfClause struct {
407 Position Pos // position of the starting "if", "elif", or "else" token
408 ThenPos Pos // position of "then", empty if this is an "else"
409 FiPos Pos // position of "fi", shared with .Else if non-nil
410
411 Cond []*Stmt
412 CondLast []Comment
413 Then []*Stmt
414 ThenLast []Comment
415
416 Else *IfClause // if non-nil, an "elif" or an "else"
417
418 Last []Comment // comments on the first "elif", "else", or "fi"
419 }
420
421 func (c *IfClause) Pos() Pos { return c.Position }
422 func (c *IfClause) End() Pos { return posAddCol(c.FiPos, 2) }
423
424 // WhileClause represents a while or an until clause.
425 type WhileClause struct {
426 WhilePos, DoPos, DonePos Pos
427 Until bool
428
429 Cond []*Stmt
430 CondLast []Comment
431 Do []*Stmt
432 DoLast []Comment
433 }
434
435 func (w *WhileClause) Pos() Pos { return w.WhilePos }
436 func (w *WhileClause) End() Pos { return posAddCol(w.DonePos, 4) }
437
438 // ForClause represents a for or a select clause. The latter is only present in
439 // Bash.
440 type ForClause struct {
441 ForPos, DoPos, DonePos Pos
442 Select bool
443 Braces bool // deprecated form with { } instead of do/done
444 Loop Loop
445
446 Do []*Stmt
447 DoLast []Comment
448 }
449
450 func (f *ForClause) Pos() Pos { return f.ForPos }
451 func (f *ForClause) End() Pos {
452 if f.Braces {
453 return posAddCol(f.DonePos, len("}"))
454 }
455 return posAddCol(f.DonePos, len("done"))
456 }
457
458 // Loop holds either [*WordIter] or [*CStyleLoop].
459 type Loop interface {
460 Node
461 loopNode()
462 }
463
464 func (*WordIter) loopNode() {}
465 func (*CStyleLoop) loopNode() {}
466
467 // WordIter represents the iteration of a variable over a series of words in a
468 // for clause. If InPos is an invalid position, the "in" token was missing, so
469 // the iteration is over the shell's positional parameters.
470 type WordIter struct {
471 Name *Lit
472 InPos Pos // position of "in"
473 Items []*Word
474 }
475
476 func (w *WordIter) Pos() Pos { return w.Name.Pos() }
477 func (w *WordIter) End() Pos {
478 if len(w.Items) > 0 {
479 return wordLastEnd(w.Items)
480 }
481 return posMax(w.Name.End(), posAddCol(w.InPos, 2))
482 }
483
484 // CStyleLoop represents the behavior of a for clause similar to the C
485 // language.
486 //
487 // This node will only appear with [LangBash].
488 type CStyleLoop struct {
489 Lparen, Rparen Pos
490 // Init, Cond, Post can each be nil, if the for loop construct omits it.
491 Init, Cond, Post ArithmExpr
492 }
493
494 func (c *CStyleLoop) Pos() Pos { return c.Lparen }
495 func (c *CStyleLoop) End() Pos { return posAddCol(c.Rparen, 2) }
496
497 // BinaryCmd represents a binary expression between two statements.
498 type BinaryCmd struct {
499 OpPos Pos
500 Op BinCmdOperator
501 X, Y *Stmt
502 }
503
504 func (b *BinaryCmd) Pos() Pos { return b.X.Pos() }
505 func (b *BinaryCmd) End() Pos { return b.Y.End() }
506
507 // FuncDecl represents the declaration of a function.
508 type FuncDecl struct {
509 Position Pos
510 RsrvWord bool // non-posix "function f" style
511 Parens bool // with () parentheses, can only be false when RsrvWord==true
512
513 // Only one of these is set at a time.
514 // Neither is set when declaring an anonymous func with [LangZsh].
515 // TODO(v4): join these, even if it's mildly annoying to non-Zsh users.
516 Name *Lit
517 Names []*Lit // When declaring many func names with [LangZsh].
518
519 Body *Stmt
520 }
521
522 func (f *FuncDecl) Pos() Pos { return f.Position }
523 func (f *FuncDecl) End() Pos { return f.Body.End() }
524
525 // Word represents a shell word, containing one or more word parts contiguous to
526 // each other. The word is delimited by word boundaries, such as spaces,
527 // newlines, semicolons, or parentheses.
528 type Word struct {
529 Parts []WordPart
530 }
531
532 func (w *Word) Pos() Pos { return w.Parts[0].Pos() }
533 func (w *Word) End() Pos { return w.Parts[len(w.Parts)-1].End() }
534
535 // Lit returns the word as a string when it is a simple literal,
536 // made up of [*Lit] word parts only.
537 // An empty string is returned otherwise.
538 //
539 // For example, the word "foo" will return "foo",
540 // but the word "foo${bar}" will return "".
541 func (w *Word) Lit() string {
542 // In the usual case, we'll have either a single part that's a literal,
543 // or one of the parts being a non-literal. Using strings.Join instead
544 // of a strings.Builder avoids extra work in these cases, since a single
545 // part is a shortcut, and many parts don't incur string copies.
546 lits := make([]string, 0, 1)
547 for _, part := range w.Parts {
548 lit, ok := part.(*Lit)
549 if !ok {
550 return ""
551 }
552 lits = append(lits, lit.Value)
553 }
554 return strings.Join(lits, "")
555 }
556
557 // WordPart represents all nodes that can form part of a word.
558 //
559 // These are [*Lit], [*SglQuoted], [*DblQuoted], [*ParamExp], [*CmdSubst], [*ArithmExp],
560 // [*ProcSubst], and [*ExtGlob].
561 type WordPart interface {
562 Node
563 wordPartNode()
564 }
565
566 func (*Lit) wordPartNode() {}
567 func (*SglQuoted) wordPartNode() {}
568 func (*DblQuoted) wordPartNode() {}
569 func (*ParamExp) wordPartNode() {}
570 func (*CmdSubst) wordPartNode() {}
571 func (*ArithmExp) wordPartNode() {}
572 func (*ProcSubst) wordPartNode() {}
573 func (*ExtGlob) wordPartNode() {}
574 func (*BraceExp) wordPartNode() {}
575
576 // Lit represents a string literal.
577 //
578 // Note that a parsed string literal may not appear as-is in the original source
579 // code, as it is possible to split literals by escaping newlines. The splitting
580 // is lost, but the end position is not.
581 type Lit struct {
582 ValuePos, ValueEnd Pos
583 Value string
584 }
585
586 func (l *Lit) Pos() Pos { return l.ValuePos }
587 func (l *Lit) End() Pos { return l.ValueEnd }
588
589 // SglQuoted represents a string within single quotes.
590 type SglQuoted struct {
591 Left, Right Pos
592 Dollar bool // $''
593 Value string
594 }
595
596 func (q *SglQuoted) Pos() Pos { return q.Left }
597 func (q *SglQuoted) End() Pos { return posAddCol(q.Right, 1) }
598
599 // DblQuoted represents a list of nodes within double quotes.
600 type DblQuoted struct {
601 Left, Right Pos
602 Dollar bool // $""
603 Parts []WordPart
604 }
605
606 func (q *DblQuoted) Pos() Pos { return q.Left }
607 func (q *DblQuoted) End() Pos { return posAddCol(q.Right, 1) }
608
609 // CmdSubst represents a command substitution.
610 type CmdSubst struct {
611 Left, Right Pos
612
613 Stmts []*Stmt
614 Last []Comment
615
616 Backquotes bool // deprecated `foo`
617 TempFile bool // mksh's ${ foo;}
618 ReplyVar bool // mksh's ${|foo;}
619 }
620
621 func (c *CmdSubst) Pos() Pos { return c.Left }
622 func (c *CmdSubst) End() Pos { return posAddCol(c.Right, 1) }
623
624 // OptState represents a boolean option which may be unset
625 // on top of being explicitly set on or off.
626 type OptState uint8
627
628 const (
629 OptUnset OptState = iota // option not set
630 OptOn // option set to true
631 OptOff // option set to false
632 )
633
634 // ParamExp represents a parameter expansion.
635 type ParamExp struct {
636 Dollar, Rbrace Pos
637
638 // TODO(v4): replace Short for !Rbrace.IsValid()
639
640 Short bool // $a instead of ${a}
641
642 Flags *Lit // ${(flags)a} with [LangZsh]
643
644 // Only one of these is set at a time.
645 // TODO(v4): perhaps use an Operator token here,
646 // given how we've grown the number of booleans
647 // TODO(v4): rename Excl to reflect its purpose
648 Excl bool // ${!a}
649 Length bool // ${#a}
650 Width bool // mksh's ${%a}
651 IsSet bool // ${+a} with [LangZsh]
652
653 // Zsh expansion prefixes that override shell options for this expansion.
654 // They can stack with one another and with the operators above.
655 // The doubled forms (${==a}, ${~~a}, ${^^a}) force the option off.
656 Split OptState // ${=a} / ${==a} word splitting with [LangZsh]
657 GlobSubst OptState // ${~a} / ${~~a} treat value as a glob pattern with [LangZsh]
658 RcExpand OptState // ${^a} / ${^^a} RC_EXPAND_PARAM-style array expansion with [LangZsh]
659
660 // Only one of these is set at a time,
661 // or neither with [LangZsh] when the name is omitted.
662 // TODO(v4): consider joining Param and NestedParam into a single field,
663 // even if that would be mildly annoying to non-Zsh users.
664 Param *Lit
665 // A nested parameter expression in the form of [*ParamExp] or [*CmdSubst],
666 // or either of those in a [*DblQuoted]. Only possible with [LangZsh].
667 NestedParam WordPart
668
669 // TODO(v4): rename Index to Subscript, which better matches bash and zsh terminology
670
671 Index ArithmExpr // ${a[i]}, ${a["k"]}, or a ${a[i,j]} slice with [LangZsh]
672
673 // Only one of these is set at a time.
674 // TODO(v4): consider joining these in a single "expansion" field/type,
675 // because it should be impossible for multiple to be set at once,
676 // and a flat structure like this takes up more space.
677 Modifiers []*Lit // ${a:h2} with [LangZsh]
678 Slice *Slice // ${a:x:y}
679 Repl *Replace // ${a/x/y}
680 Names ParNamesOperator // ${!prefix*} or ${!prefix@}
681 Exp *Expansion // ${a:-b}, ${a#b}, etc
682 }
683
684 // simple returns true if the parameter expansion is of the form $name or ${name},
685 // only expanding a name without any further logic.
686 func (p *ParamExp) simple() bool {
687 return p.Param != nil && p.Flags == nil &&
688 !p.Excl && !p.Length && !p.Width && !p.IsSet &&
689 p.Split == OptUnset && p.GlobSubst == OptUnset && p.RcExpand == OptUnset &&
690 p.NestedParam == nil && p.Index == nil &&
691 len(p.Modifiers) == 0 && p.Slice == nil &&
692 p.Repl == nil && p.Names == 0 && p.Exp == nil
693 }
694
695 func (p *ParamExp) Pos() Pos {
696 if p.Dollar.IsValid() {
697 return p.Dollar
698 }
699 return p.Param.Pos()
700 }
701
702 func (p *ParamExp) End() Pos {
703 if !p.Short {
704 return posAddCol(p.Rbrace, 1)
705 }
706 // In short mode, we can only end in either an index or a simple name.
707 if p.Index != nil {
708 return posAddCol(p.Index.End(), 1)
709 }
710 return p.Param.End()
711 }
712
713 func (p *ParamExp) nakedIndex() bool {
714 // A naked index is arr[x] inside arithmetic, without a leading '$'.
715 // In that case Dollar is unset, unlike $arr[x] where it holds the '$' position.
716 return p.Short && p.Index != nil && !p.Dollar.IsValid()
717 }
718
719 // Slice represents a character slicing expression inside a [ParamExp].
720 //
721 // This node will only appear with [LangBash] and [LangMirBSDKorn].
722 // [LangZsh] uses a [BinaryArithm] with [Comma] in [ParamExp.Index] instead.
723 type Slice struct {
724 Offset, Length ArithmExpr
725 }
726
727 // Replace represents a search and replace expression inside a [ParamExp].
728 type Replace struct {
729 All bool
730 Orig, With *Word
731 }
732
733 // Expansion represents string manipulation in a [ParamExp] other than those
734 // covered by [Replace].
735 type Expansion struct {
736 Op ParExpOperator
737 Word *Word
738 }
739
740 // ArithmExp represents an arithmetic expansion.
741 type ArithmExp struct {
742 Left, Right Pos
743 Bracket bool // deprecated $[expr] form
744 Unsigned bool // mksh's $((# expr))
745
746 X ArithmExpr
747 }
748
749 func (a *ArithmExp) Pos() Pos { return a.Left }
750 func (a *ArithmExp) End() Pos {
751 if a.Bracket {
752 return posAddCol(a.Right, 1)
753 }
754 return posAddCol(a.Right, 2)
755 }
756
757 // ArithmCmd represents an arithmetic command.
758 //
759 // This node will only appear with [LangBash] and [LangMirBSDKorn].
760 type ArithmCmd struct {
761 Left, Right Pos
762 Unsigned bool // mksh's ((# expr))
763
764 X ArithmExpr
765 }
766
767 func (a *ArithmCmd) Pos() Pos { return a.Left }
768 func (a *ArithmCmd) End() Pos { return posAddCol(a.Right, 2) }
769
770 // ArithmExpr represents all nodes that form arithmetic expressions.
771 //
772 // These are [*BinaryArithm], [*UnaryArithm], [*ParenArithm], [*FlagsArithm], and [*Word].
773 type ArithmExpr interface {
774 Node
775 arithmExprNode()
776 }
777
778 func (*BinaryArithm) arithmExprNode() {}
779 func (*UnaryArithm) arithmExprNode() {}
780 func (*ParenArithm) arithmExprNode() {}
781 func (*FlagsArithm) arithmExprNode() {}
782 func (*Word) arithmExprNode() {}
783
784 // BinaryArithm represents a binary arithmetic expression.
785 //
786 // If Op is any assign operator, X will be a word with a single [*Lit] whose value
787 // is a valid name.
788 //
789 // Ternary operators like "a ? b : c" are fit into this structure. Thus, if
790 // Op==[TernQuest], Y will be a [*BinaryArithm] with Op==[TernColon].
791 // [TernColon] does not appear in any other scenario.
792 type BinaryArithm struct {
793 OpPos Pos
794 Op BinAritOperator
795 X, Y ArithmExpr
796 }
797
798 func (b *BinaryArithm) Pos() Pos { return b.X.Pos() }
799 func (b *BinaryArithm) End() Pos { return b.Y.End() }
800
801 // UnaryArithm represents an unary arithmetic expression. The unary operator
802 // may come before or after the sub-expression.
803 //
804 // If Op is [Inc] or [Dec], X will be a word with a single [*Lit] whose value is a
805 // valid name.
806 type UnaryArithm struct {
807 OpPos Pos
808 Op UnAritOperator
809 Post bool
810 X ArithmExpr
811 }
812
813 func (u *UnaryArithm) Pos() Pos {
814 if u.Post {
815 return u.X.Pos()
816 }
817 return u.OpPos
818 }
819
820 func (u *UnaryArithm) End() Pos {
821 if u.Post {
822 return posAddCol(u.OpPos, 2)
823 }
824 return u.X.End()
825 }
826
827 // ParenArithm represents an arithmetic expression within parentheses.
828 type ParenArithm struct {
829 Lparen, Rparen Pos
830
831 X ArithmExpr
832 }
833
834 func (p *ParenArithm) Pos() Pos { return p.Lparen }
835 func (p *ParenArithm) End() Pos { return posAddCol(p.Rparen, 1) }
836
837 // FlagsArithm represents zsh subscript flags attached to an arithmetic expression,
838 // such as ${array[(flags)expr]}.
839 //
840 // This node will only appear with [LangZsh].
841 type FlagsArithm struct {
842 Flags *Lit
843 X ArithmExpr
844 }
845
846 func (z *FlagsArithm) Pos() Pos { return posAddCol(z.Flags.Pos(), -1) }
847 func (z *FlagsArithm) End() Pos {
848 if z.X != nil {
849 return z.X.End()
850 }
851 return posAddCol(z.Flags.End(), 1) // closing paren
852 }
853
854 // CaseClause represents a case (switch) clause.
855 type CaseClause struct {
856 Case, In, Esac Pos
857 Braces bool // deprecated mksh form with braces instead of in/esac
858
859 Word *Word
860 Items []*CaseItem
861 Last []Comment
862 }
863
864 func (c *CaseClause) Pos() Pos { return c.Case }
865 func (c *CaseClause) End() Pos {
866 if c.Braces {
867 return posAddCol(c.Esac, len("}"))
868 }
869 return posAddCol(c.Esac, len("esac"))
870 }
871
872 // CaseItem represents a pattern list (case) within a [CaseClause].
873 type CaseItem struct {
874 Op CaseOperator
875 OpPos Pos // unset if it was finished by "esac"
876 Comments []Comment
877 Patterns []*Word
878
879 Stmts []*Stmt
880 Last []Comment
881 }
882
883 func (c *CaseItem) Pos() Pos { return c.Patterns[0].Pos() }
884 func (c *CaseItem) End() Pos {
885 if c.OpPos.IsValid() {
886 return posAddCol(c.OpPos, len(c.Op.String()))
887 }
888 return stmtsEnd(c.Stmts, c.Last)
889 }
890
891 // TestClause represents a Bash extended test clause.
892 //
893 // This node will only appear with [LangBash] and [LangMirBSDKorn].
894 type TestClause struct {
895 Left, Right Pos
896
897 X TestExpr
898 }
899
900 func (t *TestClause) Pos() Pos { return t.Left }
901 func (t *TestClause) End() Pos { return posAddCol(t.Right, 2) }
902
903 // TestExpr represents all nodes that form test expressions.
904 //
905 // These are [*BinaryTest], [*UnaryTest], [*ParenTest], and [*Word].
906 type TestExpr interface {
907 Node
908 testExprNode()
909 }
910
911 func (*BinaryTest) testExprNode() {}
912 func (*UnaryTest) testExprNode() {}
913 func (*ParenTest) testExprNode() {}
914 func (*Word) testExprNode() {}
915
916 // BinaryTest represents a binary test expression.
917 type BinaryTest struct {
918 OpPos Pos
919 Op BinTestOperator
920 X, Y TestExpr
921 }
922
923 func (b *BinaryTest) Pos() Pos { return b.X.Pos() }
924 func (b *BinaryTest) End() Pos { return b.Y.End() }
925
926 // UnaryTest represents a unary test expression. The unary operator may come
927 // before or after the sub-expression.
928 type UnaryTest struct {
929 OpPos Pos
930 Op UnTestOperator
931 X TestExpr
932 }
933
934 func (u *UnaryTest) Pos() Pos { return u.OpPos }
935 func (u *UnaryTest) End() Pos { return u.X.End() }
936
937 // ParenTest represents a test expression within parentheses.
938 type ParenTest struct {
939 Lparen, Rparen Pos
940
941 X TestExpr
942 }
943
944 func (p *ParenTest) Pos() Pos { return p.Lparen }
945 func (p *ParenTest) End() Pos { return posAddCol(p.Rparen, 1) }
946
947 // DeclClause represents a Bash declare clause.
948 //
949 // Args can contain a mix of regular and naked assignments. The naked
950 // assignments can represent either options or variable names.
951 //
952 // This node will only appear with [LangBash].
953 type DeclClause struct {
954 // Variant is one of "declare", "local", "export", "readonly",
955 // "typeset", or "nameref".
956 Variant *Lit
957 Args []*Assign
958 }
959
960 func (d *DeclClause) Pos() Pos { return d.Variant.Pos() }
961 func (d *DeclClause) End() Pos {
962 if len(d.Args) > 0 {
963 return d.Args[len(d.Args)-1].End()
964 }
965 return d.Variant.End()
966 }
967
968 // ArrayExpr represents a Bash array expression.
969 //
970 // This node will only appear with [LangBash].
971 type ArrayExpr struct {
972 Lparen, Rparen Pos
973
974 Elems []*ArrayElem
975 Last []Comment
976 }
977
978 func (a *ArrayExpr) Pos() Pos { return a.Lparen }
979 func (a *ArrayExpr) End() Pos { return posAddCol(a.Rparen, 1) }
980
981 // ArrayElem represents a Bash array element.
982 //
983 // Index can be nil; for example, declare -a x=(value).
984 // Value can be nil; for example, declare -A x=([index]=).
985 // Finally, neither can be nil; for example, declare -A x=([index]=value)
986 type ArrayElem struct {
987 Index ArithmExpr
988 Value *Word
989 Comments []Comment
990 }
991
992 func (a *ArrayElem) Pos() Pos {
993 if a.Index != nil {
994 return a.Index.Pos()
995 }
996 return a.Value.Pos()
997 }
998
999 func (a *ArrayElem) End() Pos {
1000 if a.Value != nil {
1001 return a.Value.End()
1002 }
1003 return posAddCol(a.Index.End(), len("]="))
1004 }
1005
1006 // TODO(v4): the expand package has to stringify ExtGlob again,
1007 // and we don't gain much from a WordPart node anyway;
1008 // make these opaque literals like we did for zsh glob qualifiers.
1009
1010 // ExtGlob represents a Bash extended globbing expression. Note that these are
1011 // parsed independently of whether or not `shopt -s extglob` has been used,
1012 // as the parser runs statically and independently of any interpreter.
1013 //
1014 // This node will only appear with [LangBash] and [LangMirBSDKorn].
1015 type ExtGlob struct {
1016 OpPos Pos
1017 Op GlobOperator
1018 Pattern *Lit
1019 }
1020
1021 func (e *ExtGlob) Pos() Pos { return e.OpPos }
1022 func (e *ExtGlob) End() Pos { return posAddCol(e.Pattern.End(), 1) }
1023
1024 // ProcSubst represents a Bash process substitution.
1025 //
1026 // This node will only appear with [LangBash].
1027 type ProcSubst struct {
1028 OpPos, Rparen Pos
1029 Op ProcOperator
1030
1031 Stmts []*Stmt
1032 Last []Comment
1033 }
1034
1035 func (s *ProcSubst) Pos() Pos { return s.OpPos }
1036 func (s *ProcSubst) End() Pos { return posAddCol(s.Rparen, 1) }
1037
1038 // TimeClause represents a Bash time clause. PosixFormat corresponds to the -p
1039 // flag.
1040 //
1041 // This node will only appear with [LangBash] and [LangMirBSDKorn].
1042 type TimeClause struct {
1043 Time Pos
1044 PosixFormat bool
1045 Stmt *Stmt
1046 }
1047
1048 func (c *TimeClause) Pos() Pos { return c.Time }
1049 func (c *TimeClause) End() Pos {
1050 if c.Stmt == nil {
1051 return posAddCol(c.Time, 4)
1052 }
1053 return c.Stmt.End()
1054 }
1055
1056 // CoprocClause represents a Bash coproc clause.
1057 //
1058 // This node will only appear with [LangBash].
1059 type CoprocClause struct {
1060 Coproc Pos
1061 Name *Word
1062 Stmt *Stmt
1063 }
1064
1065 func (c *CoprocClause) Pos() Pos { return c.Coproc }
1066 func (c *CoprocClause) End() Pos { return c.Stmt.End() }
1067
1068 // LetClause represents a Bash let clause.
1069 //
1070 // This node will only appear with [LangBash] and [LangMirBSDKorn].
1071 type LetClause struct {
1072 Let Pos
1073 Exprs []ArithmExpr
1074 }
1075
1076 func (l *LetClause) Pos() Pos { return l.Let }
1077 func (l *LetClause) End() Pos { return l.Exprs[len(l.Exprs)-1].End() }
1078
1079 // BraceExp represents a Bash brace expression, such as "{a,f}" or "{1..10}".
1080 //
1081 // This node will only appear as a result of [SplitBraces].
1082 type BraceExp struct {
1083 Sequence bool // {x..y[..incr]} instead of {x,y[,...]}
1084 Elems []*Word
1085 }
1086
1087 func (b *BraceExp) Pos() Pos {
1088 return posAddCol(b.Elems[0].Pos(), -1)
1089 }
1090
1091 func (b *BraceExp) End() Pos {
1092 return posAddCol(wordLastEnd(b.Elems), 1)
1093 }
1094
1095 // TestDecl represents the declaration of a Bats test function.
1096 type TestDecl struct {
1097 Position Pos
1098 Description *Word
1099 Body *Stmt
1100 }
1101
1102 func (f *TestDecl) Pos() Pos { return f.Position }
1103 func (f *TestDecl) End() Pos { return f.Body.End() }
1104
1105 func wordLastEnd(ws []*Word) Pos {
1106 if len(ws) == 0 {
1107 return Pos{}
1108 }
1109 return ws[len(ws)-1].End()
1110 }