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 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
|
// Package parse implements the elvish parser.
package parse
//go:generate ./boilerplate.py
//go:generate stringer -type=PrimaryType,RedirMode -output=string.go
import (
"bytes"
"errors"
"fmt"
"unicode"
)
// Parse parses Elvish source. If the error is not nil, it always has type
// ParseError.
func Parse(srcname, src string) (*Chunk, error) {
ps := NewParser(srcname, src)
n := ParseChunk(ps)
ps.Done()
return n, ps.Errors()
}
// Errors.
var (
errShouldBeForm = newError("", "form")
errBadLHS = errors.New("bad assignment LHS")
errDuplicateExitusRedir = newError("duplicate exitus redir")
errBadRedirSign = newError("bad redir sign", "'<'", "'>'", "'>>'", "'<>'")
errShouldBeFD = newError("", "a composite term representing fd")
errShouldBeFilename = newError("", "a composite term representing filename")
errShouldBeArray = newError("", "spaced")
errStringUnterminated = newError("string not terminated")
errChainedAssignment = newError("chained assignment not yet supported")
errInvalidEscape = newError("invalid escape sequence")
errInvalidEscapeOct = newError("invalid escape sequence", "octal digit")
errInvalidEscapeHex = newError("invalid escape sequence", "hex digit")
errInvalidEscapeControl = newError("invalid control sequence", "a rune between @ (0x40) and _(0x5F)")
errShouldBePrimary = newError("",
"single-quoted string", "double-quoted string", "bareword")
errShouldBeVariableName = newError("", "variable name")
errShouldBeRBracket = newError("", "']'")
errShouldBeRBrace = newError("", "'}'")
errShouldBeBraceSepOrRBracket = newError("", "','", "'}'")
errShouldBeRParen = newError("", "')'")
errShouldBeCompound = newError("", "compound")
errShouldBeEqual = newError("", "'='")
errBothElementsAndPairs = newError("cannot contain both list elements and map pairs")
errShouldBeEscapeSequence = newError("", "escape sequence")
)
// Chunk = { PipelineSep | Space } { Pipeline { PipelineSep | Space } }
type Chunk struct {
node
Pipelines []*Pipeline
}
func (bn *Chunk) parse(ps *Parser) {
bn.parseSeps(ps)
for startsPipeline(ps.peek()) {
bn.addToPipelines(ParsePipeline(ps))
if bn.parseSeps(ps) == 0 {
break
}
}
}
func isPipelineSep(r rune) bool {
return r == '\n' || r == ';'
}
// parseSeps parses pipeline separators along with whitespaces. It returns the
// number of pipeline separators parsed.
func (bn *Chunk) parseSeps(ps *Parser) int {
nseps := 0
for {
r := ps.peek()
if isPipelineSep(r) {
// parse as a Sep
parseSep(bn, ps, r)
nseps++
} else if IsSpace(r) {
// parse a run of spaces as a Sep
parseSpaces(bn, ps)
} else if r == '#' {
// parse a comment as a Sep
for {
r := ps.peek()
if r == eof || r == '\n' {
break
}
ps.next()
}
addSep(bn, ps)
nseps++
} else {
break
}
}
return nseps
}
// Pipeline = Form { '|' Form }
type Pipeline struct {
node
Forms []*Form
Background bool
}
func (pn *Pipeline) parse(ps *Parser) {
pn.addToForms(ParseForm(ps))
for parseSep(pn, ps, '|') {
parseSpacesAndNewlines(pn, ps)
if !startsForm(ps.peek()) {
ps.error(errShouldBeForm)
return
}
pn.addToForms(ParseForm(ps))
}
parseSpaces(pn, ps)
if ps.peek() == '&' {
ps.next()
addSep(pn, ps)
pn.Background = true
parseSpaces(pn, ps)
}
}
func startsPipeline(r rune) bool {
return startsForm(r)
}
// Form = { Space } { { Assignment } { Space } }
// { Compound } { Space } { ( Compound | MapPair | Redir | ExitusRedir ) { Space } }
type Form struct {
node
Assignments []*Assignment
Head *Compound
// Left-hand-sides for the spacey assignment. Right-hand-sides are in Args.
Vars []*Compound
Args []*Compound
Opts []*MapPair
Redirs []*Redir
ExitusRedir *ExitusRedir
}
func (fn *Form) parse(ps *Parser) {
parseSpaces(fn, ps)
for fn.tryAssignment(ps) {
parseSpaces(fn, ps)
}
// Parse head.
if !startsCompound(ps.peek(), CmdExpr) {
if len(fn.Assignments) > 0 {
// Assignment-only form.
return
}
// Bad form.
ps.error(fmt.Errorf("bad rune at form head: %q", ps.peek()))
}
fn.setHead(ParseCompound(ps, CmdExpr))
parseSpaces(fn, ps)
for {
r := ps.peek()
switch {
case r == '&':
ps.next()
hasMapPair := startsCompound(ps.peek(), LHSExpr)
ps.backup()
if !hasMapPair {
// background indicator
return
}
fn.addToOpts(ParseMapPair(ps))
case startsCompound(r, NormalExpr):
if ps.hasPrefix("?>") {
if fn.ExitusRedir != nil {
ps.error(errDuplicateExitusRedir)
// Parse the duplicate redir anyway.
addChild(fn, ParseExitusRedir(ps))
} else {
fn.setExitusRedir(ParseExitusRedir(ps))
}
continue
}
cn := ParseCompound(ps, NormalExpr)
if isRedirSign(ps.peek()) {
// Redir
fn.addToRedirs(ParseRedir(ps, cn))
} else if cn.sourceText == "=" {
// Spacey assignment.
// Turn the equal sign into a Sep.
addChild(fn, NewSep(ps.src, cn.begin, cn.end))
// Turn the head and preceding arguments into LHSs.
addLHS := func(cn *Compound) {
if len(cn.Indexings) == 1 && checkVariableInAssignment(cn.Indexings[0].Head, ps) {
fn.Vars = append(fn.Vars, cn)
} else {
ps.errorp(cn.begin, cn.end, errBadLHS)
}
}
if fn.Head != nil {
addLHS(fn.Head)
} else {
ps.error(errChainedAssignment)
}
fn.Head = nil
for _, cn := range fn.Args {
addLHS(cn)
}
fn.Args = nil
} else {
fn.addToArgs(cn)
}
case isRedirSign(r):
fn.addToRedirs(ParseRedir(ps, nil))
default:
return
}
parseSpaces(fn, ps)
}
}
// tryAssignment tries to parse an assignment. If succeeded, it adds the parsed
// assignment to fn.Assignments and returns true. Otherwise it rewinds the
// parser and returns false.
func (fn *Form) tryAssignment(ps *Parser) bool {
if !startsIndexing(ps.peek(), LHSExpr) {
return false
}
pos := ps.pos
errorEntries := ps.errors.Entries
an := ParseAssignment(ps)
// If errors were added, revert
if len(ps.errors.Entries) > len(errorEntries) {
ps.errors.Entries = errorEntries
ps.pos = pos
return false
}
fn.addToAssignments(an)
return true
}
func startsForm(r rune) bool {
return IsSpace(r) || startsCompound(r, CmdExpr)
}
// Assignment = Indexing '=' Compound
type Assignment struct {
node
Left *Indexing
Right *Compound
}
func (an *Assignment) parse(ps *Parser) {
an.setLeft(ParseIndexing(ps, LHSExpr))
head := an.Left.Head
if !checkVariableInAssignment(head, ps) {
ps.errorp(head.Begin(), head.End(), errShouldBeVariableName)
}
if !parseSep(an, ps, '=') {
ps.error(errShouldBeEqual)
}
an.setRight(ParseCompound(ps, NormalExpr))
}
func checkVariableInAssignment(p *Primary, ps *Parser) bool {
if p.Type == Braced {
// XXX don't check further inside braced expression
return true
}
if p.Type != Bareword && p.Type != SingleQuoted && p.Type != DoubleQuoted {
return false
}
if p.Value == "" {
return false
}
for _, r := range p.Value {
// XXX special case '&' and '@'.
if !allowedInVariableName(r) && r != '&' && r != '@' {
return false
}
}
return true
}
// ExitusRedir = '?' '>' { Space } Compound
type ExitusRedir struct {
node
Dest *Compound
}
func (ern *ExitusRedir) parse(ps *Parser) {
ps.next()
ps.next()
addSep(ern, ps)
parseSpaces(ern, ps)
ern.setDest(ParseCompound(ps, NormalExpr))
}
// Redir = { Compound } { '<'|'>'|'<>'|'>>' } { Space } ( '&'? Compound )
type Redir struct {
node
Left *Compound
Mode RedirMode
RightIsFd bool
Right *Compound
}
func (rn *Redir) parse(ps *Parser, dest *Compound) {
// The parsing of the Left part is done in Form.parse.
if dest != nil {
rn.setLeft(dest)
rn.begin = dest.begin
}
begin := ps.pos
for isRedirSign(ps.peek()) {
ps.next()
}
sign := ps.src[begin:ps.pos]
switch sign {
case "<":
rn.Mode = Read
case ">":
rn.Mode = Write
case ">>":
rn.Mode = Append
case "<>":
rn.Mode = ReadWrite
default:
ps.error(errBadRedirSign)
}
addSep(rn, ps)
parseSpaces(rn, ps)
if parseSep(rn, ps, '&') {
rn.RightIsFd = true
}
rn.setRight(ParseCompound(ps, NormalExpr))
if len(rn.Right.Indexings) == 0 {
if rn.RightIsFd {
ps.error(errShouldBeFD)
} else {
ps.error(errShouldBeFilename)
}
return
}
}
func isRedirSign(r rune) bool {
return r == '<' || r == '>'
}
// RedirMode records the mode of an IO redirection.
type RedirMode int
// Possible values for RedirMode.
const (
BadRedirMode RedirMode = iota
Read
Write
ReadWrite
Append
)
// Compound = { Indexing }
type Compound struct {
node
Indexings []*Indexing
}
// ExprCtx represents special contexts of expression parsing.
type ExprCtx int
const (
// NormalExpr represents a normal expression, namely none of the special
// ones below.
NormalExpr ExprCtx = iota
// CmdExpr represents an expression used as the command in a form. In this
// context, unquoted <>*^ are treated as bareword characters.
CmdExpr
// LHSExpr represents an expression used as the left-hand-side in either
// assignments or map pairs. In this context, an unquoted = serves as an
// expression terminator and is thus not treated as a bareword character.
LHSExpr
// BracedElemExpr represents an expression used as an element in a braced
// expression. In this context, an unquoted , serves as an expression
// terminator and is thus not treated as a bareword character.
BracedElemExpr
// strictExpr is only meaningful to allowedInBareword.
strictExpr
)
func (cn *Compound) parse(ps *Parser, ctx ExprCtx) {
cn.tilde(ps)
for startsIndexing(ps.peek(), ctx) {
cn.addToIndexings(ParseIndexing(ps, ctx))
}
}
// tilde parses a tilde if there is one. It is implemented here instead of
// within Primary since a tilde can only appear as the first part of a
// Compound. Elsewhere tildes are barewords.
func (cn *Compound) tilde(ps *Parser) {
if ps.peek() == '~' {
ps.next()
base := node{nil, ps.pos - 1, ps.pos, "~", nil}
pn := &Primary{node: base, Type: Tilde, Value: "~"}
in := &Indexing{node: base}
in.setHead(pn)
cn.addToIndexings(in)
}
}
func startsCompound(r rune, ctx ExprCtx) bool {
return startsIndexing(r, ctx)
}
// Indexing = Primary { '[' Array ']' }
type Indexing struct {
node
Head *Primary
Indicies []*Array
}
func (in *Indexing) parse(ps *Parser, ctx ExprCtx) {
in.setHead(ParsePrimary(ps, ctx))
for parseSep(in, ps, '[') {
if !startsArray(ps.peek()) {
ps.error(errShouldBeArray)
}
in.addToIndicies(ParseArray(ps, false))
if !parseSep(in, ps, ']') {
ps.error(errShouldBeRBracket)
return
}
}
}
func startsIndexing(r rune, ctx ExprCtx) bool {
return startsPrimary(r, ctx)
}
// Array = { Space | '\n' } { Compound { Space | '\n' } }
type Array struct {
node
Compounds []*Compound
// When non-empty, records the occurrences of semicolons by the indices of
// the compounds they appear before. For instance, [; ; a b; c d;] results
// in Semicolons={0 0 2 4}.
Semicolons []int
}
func (sn *Array) parse(ps *Parser, allowSemicolon bool) {
parseSep := func() {
parseSpacesAndNewlines(sn, ps)
if allowSemicolon {
for parseSep(sn, ps, ';') {
sn.Semicolons = append(sn.Semicolons, len(sn.Compounds))
}
parseSpacesAndNewlines(sn, ps)
}
}
parseSep()
for startsCompound(ps.peek(), NormalExpr) {
sn.addToCompounds(ParseCompound(ps, NormalExpr))
parseSep()
}
}
func IsSpace(r rune) bool {
return r == ' ' || r == '\t'
}
func startsArray(r rune) bool {
return IsSpaceOrNewline(r) || startsIndexing(r, NormalExpr)
}
// Primary is the smallest expression unit.
type Primary struct {
node
Type PrimaryType
// The unquoted string value. Valid for Bareword, SingleQuoted,
// DoubleQuoted, Variable, Wildcard and Tilde.
Value string
Elements []*Compound // Valid for List and Labda
Chunk *Chunk // Valid for OutputCapture, ExitusCapture and Lambda
MapPairs []*MapPair // Valid for Map and Lambda
Braced []*Compound // Valid for Braced
}
// PrimaryType is the type of a Primary.
type PrimaryType int
// Possible values for PrimaryType.
const (
BadPrimary PrimaryType = iota
Bareword
SingleQuoted
DoubleQuoted
Variable
Wildcard
Tilde
ExceptionCapture
OutputCapture
List
Lambda
Map
Braced
)
func (pn *Primary) parse(ps *Parser, ctx ExprCtx) {
r := ps.peek()
if !startsPrimary(r, ctx) {
ps.error(errShouldBePrimary)
return
}
// Try bareword early, since it has precedence over wildcard on *
// when ctx = commandExpr.
if allowedInBareword(r, ctx) {
pn.bareword(ps, ctx)
return
}
switch r {
case '\'':
pn.singleQuoted(ps)
case '"':
pn.doubleQuoted(ps)
case '$':
pn.variable(ps)
case '*':
pn.wildcard(ps)
case '?':
if ps.hasPrefix("?(") {
pn.exitusCapture(ps)
} else {
pn.wildcard(ps)
}
case '(':
pn.outputCapture(ps)
case '[':
pn.lbracket(ps)
case '{':
pn.lbrace(ps)
default:
// Parse an empty bareword.
pn.Type = Bareword
}
}
func (pn *Primary) singleQuoted(ps *Parser) {
pn.Type = SingleQuoted
ps.next()
var buf bytes.Buffer
defer func() { pn.Value = buf.String() }()
for {
switch r := ps.next(); r {
case eof:
ps.error(errStringUnterminated)
return
case '\'':
if ps.peek() == '\'' {
// Two consecutive single quotes
ps.next()
buf.WriteByte('\'')
} else {
// End of string
return
}
default:
buf.WriteRune(r)
}
}
}
func (pn *Primary) doubleQuoted(ps *Parser) {
pn.Type = DoubleQuoted
ps.next()
var buf bytes.Buffer
defer func() { pn.Value = buf.String() }()
for {
switch r := ps.next(); r {
case eof:
ps.error(errStringUnterminated)
return
case '"':
return
case '\\':
switch r := ps.next(); r {
case 'c', '^':
// Control sequence
r := ps.next()
if r < 0x40 || r >= 0x60 {
ps.backup()
ps.error(errInvalidEscapeControl)
ps.next()
}
buf.WriteByte(byte(r - 0x40))
case 'x', 'u', 'U':
var n int
switch r {
case 'x':
n = 2
case 'u':
n = 4
case 'U':
n = 8
}
var rr rune
for i := 0; i < n; i++ {
d, ok := hexToDigit(ps.next())
if !ok {
ps.backup()
ps.error(errInvalidEscapeHex)
break
}
rr = rr*16 + d
}
buf.WriteRune(rr)
case '0', '1', '2', '3', '4', '5', '6', '7':
// 2 more octal digits
rr := r - '0'
for i := 0; i < 2; i++ {
r := ps.next()
if r < '0' || r > '7' {
ps.backup()
ps.error(errInvalidEscapeOct)
break
}
rr = rr*8 + (r - '0')
}
buf.WriteRune(rr)
default:
if rr, ok := doubleEscape[r]; ok {
buf.WriteRune(rr)
} else {
ps.backup()
ps.error(errInvalidEscape)
ps.next()
}
}
default:
buf.WriteRune(r)
}
}
}
// a table for the simple double-quote escape sequences.
var doubleEscape = map[rune]rune{
// same as golang
'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r',
't': '\t', 'v': '\v', '\\': '\\', '"': '"',
// additional
'e': '\033',
}
var doubleUnescape = map[rune]rune{}
func init() {
for k, v := range doubleEscape {
doubleUnescape[v] = k
}
}
func hexToDigit(r rune) (rune, bool) {
switch {
case '0' <= r && r <= '9':
return r - '0', true
case 'a' <= r && r <= 'f':
return r - 'a' + 10, true
case 'A' <= r && r <= 'F':
return r - 'A' + 10, true
default:
return -1, false
}
}
func (pn *Primary) variable(ps *Parser) {
pn.Type = Variable
defer func() { pn.Value = ps.src[pn.begin+1 : ps.pos] }()
ps.next()
// The character of the variable name can be anything.
if ps.next() == eof {
ps.backup()
ps.error(errShouldBeVariableName)
ps.next()
}
for allowedInVariableName(ps.peek()) {
ps.next()
}
}
// The following are allowed in variable names:
// * Anything beyond ASCII that is printable
// * Letters and numbers
// * The symbols "-_:~"
func allowedInVariableName(r rune) bool {
return (r >= 0x80 && unicode.IsPrint(r)) ||
('0' <= r && r <= '9') ||
('a' <= r && r <= 'z') ||
('A' <= r && r <= 'Z') ||
r == '-' || r == '_' || r == ':' || r == '~'
}
func (pn *Primary) wildcard(ps *Parser) {
pn.Type = Wildcard
for isWildcard(ps.peek()) {
ps.next()
}
pn.Value = ps.src[pn.begin:ps.pos]
}
func isWildcard(r rune) bool {
return r == '*' || r == '?'
}
func (pn *Primary) exitusCapture(ps *Parser) {
ps.next()
ps.next()
addSep(pn, ps)
pn.Type = ExceptionCapture
pn.setChunk(ParseChunk(ps))
if !parseSep(pn, ps, ')') {
ps.error(errShouldBeRParen)
}
}
func (pn *Primary) outputCapture(ps *Parser) {
pn.Type = OutputCapture
parseSep(pn, ps, '(')
pn.setChunk(ParseChunk(ps))
if !parseSep(pn, ps, ')') {
ps.error(errShouldBeRParen)
}
}
// List = '[' { Space } { Compound } ']'
// = '[' { Space } { MapPair { Space } } ']'
// Map = '[' { Space } '&' { Space } ']'
// Lambda = '[' { Space } { (Compound | MapPair) { Space } } ']' '{' Chunk '}'
func (pn *Primary) lbracket(ps *Parser) {
parseSep(pn, ps, '[')
parseSpacesAndNewlines(pn, ps)
loneAmpersand := false
items:
for {
r := ps.peek()
switch {
case r == '&':
ps.next()
hasMapPair := startsCompound(ps.peek(), LHSExpr)
if !hasMapPair {
loneAmpersand = true
addSep(pn, ps)
parseSpacesAndNewlines(pn, ps)
break items
}
ps.backup()
pn.addToMapPairs(ParseMapPair(ps))
case startsCompound(r, NormalExpr):
pn.addToElements(ParseCompound(ps, NormalExpr))
default:
break items
}
parseSpacesAndNewlines(pn, ps)
}
if !parseSep(pn, ps, ']') {
ps.error(errShouldBeRBracket)
}
if parseSep(pn, ps, '{') {
pn.lambda(ps)
} else {
if loneAmpersand || len(pn.MapPairs) > 0 {
if len(pn.Elements) > 0 {
ps.error(errBothElementsAndPairs)
}
pn.Type = Map
} else {
pn.Type = List
}
}
}
// lambda parses a lambda expression. The opening brace has been seen.
func (pn *Primary) lambda(ps *Parser) {
pn.Type = Lambda
pn.setChunk(ParseChunk(ps))
if !parseSep(pn, ps, '}') {
ps.error(errShouldBeRBrace)
}
}
// Braced = '{' Compound { BracedSep Compounds } '}'
// BracedSep = { Space | '\n' } [ ',' ] { Space | '\n' }
func (pn *Primary) lbrace(ps *Parser) {
parseSep(pn, ps, '{')
if r := ps.peek(); r == ';' || r == '\n' || IsSpace(r) {
pn.lambda(ps)
return
}
pn.Type = Braced
// XXX: The compound can be empty, which allows us to parse {,foo}.
// Allowing compounds to be empty can be fragile in other cases.
pn.addToBraced(ParseCompound(ps, BracedElemExpr))
for isBracedSep(ps.peek()) {
parseSpacesAndNewlines(pn, ps)
// optional, so ignore the return value
parseSep(pn, ps, ',')
parseSpacesAndNewlines(pn, ps)
pn.addToBraced(ParseCompound(ps, BracedElemExpr))
}
if !parseSep(pn, ps, '}') {
ps.error(errShouldBeBraceSepOrRBracket)
}
}
func isBracedSep(r rune) bool {
return r == ',' || IsSpaceOrNewline(r)
}
func (pn *Primary) bareword(ps *Parser, ctx ExprCtx) {
pn.Type = Bareword
defer func() { pn.Value = ps.src[pn.begin:ps.pos] }()
for allowedInBareword(ps.peek(), ctx) {
ps.next()
}
}
// allowedInBareword returns where a rune is allowed in barewords in the given
// expression context. The special strictExpr context queries whether the rune
// is allowed in all contexts.
//
// The following are allowed in barewords:
//
// * Anything allowed in variable names
// * The symbols "./@%+!"
// * The symbol "=", if ctx != lhsExpr && ctx != strictExpr
// * The symbol ",", if ctx != bracedExpr && ctx != strictExpr
// * The symbols "<>*^", if ctx = commandExpr
//
// The seemingly weird inclusion of \ is for easier path manipulation in
// Windows.
func allowedInBareword(r rune, ctx ExprCtx) bool {
return allowedInVariableName(r) || r == '.' || r == '/' ||
r == '@' || r == '%' || r == '+' || r == '!' ||
(ctx != LHSExpr && ctx != strictExpr && r == '=') ||
(ctx != BracedElemExpr && ctx != strictExpr && r == ',') ||
(ctx == CmdExpr && (r == '<' || r == '>' || r == '*' || r == '^'))
}
func startsPrimary(r rune, ctx ExprCtx) bool {
return r == '\'' || r == '"' || r == '$' || allowedInBareword(r, ctx) ||
r == '?' || r == '*' || r == '(' || r == '[' || r == '{'
}
// MapPair = '&' { Space } Compound { Space } Compound
type MapPair struct {
node
Key, Value *Compound
}
func (mpn *MapPair) parse(ps *Parser) {
parseSep(mpn, ps, '&')
mpn.setKey(ParseCompound(ps, LHSExpr))
if len(mpn.Key.Indexings) == 0 {
ps.error(errShouldBeCompound)
}
if parseSep(mpn, ps, '=') {
parseSpacesAndNewlines(mpn, ps)
// Parse value part.
mpn.setValue(ParseCompound(ps, NormalExpr))
// The value part can be empty.
}
}
// Sep is the catch-all node type for leaf nodes that lack internal structures
// and semantics, and serve solely for syntactic purposes. The parsing of
// separators depend on the Parent node; as such it lacks a genuine parse
// method.
type Sep struct {
node
}
func NewSep(src string, begin, end int) *Sep {
return &Sep{node{nil, begin, end, src[begin:end], nil}}
}
func addSep(n Node, ps *Parser) {
var begin int
ch := n.Children()
if len(ch) > 0 {
begin = ch[len(ch)-1].End()
} else {
begin = n.Begin()
}
if begin < ps.pos {
addChild(n, NewSep(ps.src, begin, ps.pos))
}
}
func parseSep(n Node, ps *Parser, sep rune) bool {
if ps.peek() == sep {
ps.next()
addSep(n, ps)
return true
}
return false
}
func parseSpaces(n Node, ps *Parser) {
parseSpacesInner(n, ps, IsSpace)
}
func parseSpacesAndNewlines(n Node, ps *Parser) {
parseSpacesInner(n, ps, IsSpaceOrNewline)
}
func parseSpacesInner(n Node, ps *Parser, isSpace func(rune) bool) {
spaces:
for {
r := ps.peek()
switch {
case isSpace(r):
ps.next()
case r == '\\': // line continuation
ps.next()
switch ps.peek() {
case '\n':
ps.next()
case eof:
ps.error(errShouldBeEscapeSequence)
default:
ps.backup()
break spaces
}
default:
break spaces
}
}
addSep(n, ps)
}
func IsSpaceOrNewline(r rune) bool {
return IsSpace(r) || r == '\n'
}
func addChild(p Node, ch Node) {
p.n().children = append(p.n().children, ch)
ch.n().parent = p
}
|