github.com/cilki/sh@v2.6.4+incompatible/syntax/nodes_test.go (about)

     1  // Copyright (c) 2016, Daniel Martí <mvdan@mvdan.cc>
     2  // See LICENSE for licensing information
     3  
     4  package syntax
     5  
     6  import (
     7  	"fmt"
     8  	"strings"
     9  	"testing"
    10  )
    11  
    12  func TestPosition(t *testing.T) {
    13  	t.Parallel()
    14  	parserBash := NewParser(KeepComments)
    15  	parserPosix := NewParser(KeepComments, Variant(LangPOSIX))
    16  	parserMirBSD := NewParser(KeepComments, Variant(LangMirBSDKorn))
    17  	for i, c := range fileTests {
    18  		for j, in := range c.Strs {
    19  			t.Run(fmt.Sprintf("%03d-%d", i, j), func(t *testing.T) {
    20  				parser := parserPosix
    21  				if c.Bash != nil {
    22  					parser = parserBash
    23  				} else if c.MirBSDKorn != nil {
    24  					parser = parserMirBSD
    25  				}
    26  				prog, err := parser.Parse(strings.NewReader(in), "")
    27  				if err != nil {
    28  					t.Fatalf("Unexpected error in %q: %v", in, err)
    29  				}
    30  				v := &posWalker{
    31  					t:     t,
    32  					f:     prog,
    33  					lines: strings.Split(in, "\n"),
    34  				}
    35  				Walk(prog, v.Visit)
    36  			})
    37  		}
    38  	}
    39  }
    40  
    41  type posWalker struct {
    42  	t     *testing.T
    43  	f     *File
    44  	lines []string
    45  }
    46  
    47  func (v *posWalker) Visit(n Node) bool {
    48  	if n == nil {
    49  		return true
    50  	}
    51  	p := n.Pos()
    52  	if !p.IsValid() && len(v.f.Stmts) > 0 {
    53  		v.t.Fatalf("Invalid Pos")
    54  	}
    55  	if c, ok := n.(*Comment); ok {
    56  		if v.f.Pos().After(c.Pos()) {
    57  			v.t.Fatalf("A Comment is before its File")
    58  		}
    59  		if c.End().After(v.f.End()) {
    60  			v.t.Fatalf("A Comment is after its File")
    61  		}
    62  	}
    63  	return true
    64  }
    65  
    66  func TestWeirdOperatorString(t *testing.T) {
    67  	t.Parallel()
    68  	op := RedirOperator(1000)
    69  	want := "token(1000)"
    70  	if got := op.String(); got != want {
    71  		t.Fatalf("token.String() mismatch: want %s, got %s", want, got)
    72  	}
    73  }