Source file src/go/parser/error_test.go

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // This file implements a parser test harness. The files in the testdata
     6  // directory are parsed and the errors reported are compared against the
     7  // error messages expected in the test files. The test files must end in
     8  // .src rather than .go so that they are not disturbed by gofmt runs.
     9  //
    10  // Expected errors are indicated in the test files by putting a comment
    11  // of the form /* ERROR "rx" */ immediately following an offending token.
    12  // The harness will verify that an error matching the regular expression
    13  // rx is reported at that source position.
    14  //
    15  // For instance, the following test file indicates that a "not declared"
    16  // error should be reported for the undeclared variable x:
    17  //
    18  //	package p
    19  //	func f() {
    20  //		_ = x /* ERROR "not declared" */ + 1
    21  //	}
    22  
    23  package parser
    24  
    25  import (
    26  	"flag"
    27  	"go/internal/typeparams"
    28  	"go/scanner"
    29  	"go/token"
    30  	"os"
    31  	"path/filepath"
    32  	"regexp"
    33  	"strings"
    34  	"testing"
    35  )
    36  
    37  var traceErrs = flag.Bool("trace_errs", false, "whether to enable tracing for error tests")
    38  
    39  const testdata = "testdata"
    40  
    41  // getFile assumes that each filename occurs at most once
    42  func getFile(fset *token.FileSet, filename string) (file *token.File) {
    43  	fset.Iterate(func(f *token.File) bool {
    44  		if f.Name() == filename {
    45  			if file != nil {
    46  				panic(filename + " used multiple times")
    47  			}
    48  			file = f
    49  		}
    50  		return true
    51  	})
    52  	return file
    53  }
    54  
    55  func getPos(fset *token.FileSet, filename string, offset int) token.Pos {
    56  	if f := getFile(fset, filename); f != nil {
    57  		return f.Pos(offset)
    58  	}
    59  	return token.NoPos
    60  }
    61  
    62  // ERROR comments must be of the form /* ERROR "rx" */ and rx is
    63  // a regular expression that matches the expected error message.
    64  // The special form /* ERROR HERE "rx" */ must be used for error
    65  // messages that appear immediately after a token, rather than at
    66  // a token's position.
    67  //
    68  var errRx = regexp.MustCompile(`^/\* *ERROR *(HERE)? *"([^"]*)" *\*/$`)
    69  
    70  // expectedErrors collects the regular expressions of ERROR comments found
    71  // in files and returns them as a map of error positions to error messages.
    72  //
    73  func expectedErrors(fset *token.FileSet, filename string, src []byte) map[token.Pos]string {
    74  	errors := make(map[token.Pos]string)
    75  
    76  	var s scanner.Scanner
    77  	// file was parsed already - do not add it again to the file
    78  	// set otherwise the position information returned here will
    79  	// not match the position information collected by the parser
    80  	s.Init(getFile(fset, filename), src, nil, scanner.ScanComments)
    81  	var prev token.Pos // position of last non-comment, non-semicolon token
    82  	var here token.Pos // position immediately after the token at position prev
    83  
    84  	for {
    85  		pos, tok, lit := s.Scan()
    86  		switch tok {
    87  		case token.EOF:
    88  			return errors
    89  		case token.COMMENT:
    90  			s := errRx.FindStringSubmatch(lit)
    91  			if len(s) == 3 {
    92  				pos := prev
    93  				if s[1] == "HERE" {
    94  					pos = here
    95  				}
    96  				errors[pos] = s[2]
    97  			}
    98  		case token.SEMICOLON:
    99  			// don't use the position of auto-inserted (invisible) semicolons
   100  			if lit != ";" {
   101  				break
   102  			}
   103  			fallthrough
   104  		default:
   105  			prev = pos
   106  			var l int // token length
   107  			if tok.IsLiteral() {
   108  				l = len(lit)
   109  			} else {
   110  				l = len(tok.String())
   111  			}
   112  			here = prev + token.Pos(l)
   113  		}
   114  	}
   115  }
   116  
   117  // compareErrors compares the map of expected error messages with the list
   118  // of found errors and reports discrepancies.
   119  //
   120  func compareErrors(t *testing.T, fset *token.FileSet, expected map[token.Pos]string, found scanner.ErrorList) {
   121  	t.Helper()
   122  	for _, error := range found {
   123  		// error.Pos is a token.Position, but we want
   124  		// a token.Pos so we can do a map lookup
   125  		pos := getPos(fset, error.Pos.Filename, error.Pos.Offset)
   126  		if msg, found := expected[pos]; found {
   127  			// we expect a message at pos; check if it matches
   128  			rx, err := regexp.Compile(msg)
   129  			if err != nil {
   130  				t.Errorf("%s: %v", error.Pos, err)
   131  				continue
   132  			}
   133  			if match := rx.MatchString(error.Msg); !match {
   134  				t.Errorf("%s: %q does not match %q", error.Pos, error.Msg, msg)
   135  				continue
   136  			}
   137  			// we have a match - eliminate this error
   138  			delete(expected, pos)
   139  		} else {
   140  			// To keep in mind when analyzing failed test output:
   141  			// If the same error position occurs multiple times in errors,
   142  			// this message will be triggered (because the first error at
   143  			// the position removes this position from the expected errors).
   144  			t.Errorf("%s: unexpected error: %s", error.Pos, error.Msg)
   145  		}
   146  	}
   147  
   148  	// there should be no expected errors left
   149  	if len(expected) > 0 {
   150  		t.Errorf("%d errors not reported:", len(expected))
   151  		for pos, msg := range expected {
   152  			t.Errorf("%s: %s\n", fset.Position(pos), msg)
   153  		}
   154  	}
   155  }
   156  
   157  func checkErrors(t *testing.T, filename string, input any, mode Mode, expectErrors bool) {
   158  	t.Helper()
   159  	src, err := readSource(filename, input)
   160  	if err != nil {
   161  		t.Error(err)
   162  		return
   163  	}
   164  
   165  	fset := token.NewFileSet()
   166  	_, err = ParseFile(fset, filename, src, mode)
   167  	found, ok := err.(scanner.ErrorList)
   168  	if err != nil && !ok {
   169  		t.Error(err)
   170  		return
   171  	}
   172  	found.RemoveMultiples()
   173  
   174  	expected := map[token.Pos]string{}
   175  	if expectErrors {
   176  		// we are expecting the following errors
   177  		// (collect these after parsing a file so that it is found in the file set)
   178  		expected = expectedErrors(fset, filename, src)
   179  	}
   180  
   181  	// verify errors returned by the parser
   182  	compareErrors(t, fset, expected, found)
   183  }
   184  
   185  func TestErrors(t *testing.T) {
   186  	list, err := os.ReadDir(testdata)
   187  	if err != nil {
   188  		t.Fatal(err)
   189  	}
   190  	for _, d := range list {
   191  		name := d.Name()
   192  		t.Run(name, func(t *testing.T) {
   193  			if !d.IsDir() && !strings.HasPrefix(name, ".") && (strings.HasSuffix(name, ".src") || strings.HasSuffix(name, ".go2")) {
   194  				mode := DeclarationErrors | AllErrors
   195  				if !strings.HasSuffix(name, ".go2") {
   196  					mode |= typeparams.DisallowParsing
   197  				}
   198  				if *traceErrs {
   199  					mode |= Trace
   200  				}
   201  				checkErrors(t, filepath.Join(testdata, name), nil, mode, true)
   202  			}
   203  		})
   204  	}
   205  }
   206  

View as plain text