func (t *test) run() {
	start := time.Now()
	defer func() {
		t.dt = time.Since(start)
		close(t.donec)
	}()
	if kf, ok := knownFails[filepath.ToSlash(t.goFileName())]; ok && kf.category == neverTerminates {
		t.err = skipError("skipping because it doesn't terminate")
		return
	}
	srcBytes, err := ioutil.ReadFile(t.goFileName())
	if err != nil {
		t.err = err
		return
	}
	t.src = string(srcBytes)
	if t.src[0] == '\n' {
		t.err = skipError("starts with newline")
		return
	}
	pos := strings.Index(t.src, "\n\n")
	if pos == -1 {
		t.err = errors.New("double newline not found")
		return
	}
	action := t.src[:pos]
	if nl := strings.Index(action, "\n"); nl >= 0 && strings.Contains(action[:nl], "+build") {
		action = action[nl+1:]
	}
	if strings.HasPrefix(action, "//") {
		action = action[2:]
	}
	pkgPos := strings.Index(t.src, "\npackage")
	if pkgPos == -1 {
		pkgPos = pos  
	}
	if ok, why := shouldTest(t.src[:pkgPos], goos, goarch); !ok {
		t.action = "skip"
		if *showSkips {
			fmt.Printf("%-20s %-20s: %s\n", t.action, t.goFileName(), why)
		}
		return
	}
	var args, flags []string
	wantError := false
	f := strings.Fields(action)
	if len(f) > 0 {
		action = f[0]
		args = f[1:]
	}
	switch action {
	case "run", "cmpout":
		if filepath.Clean(t.dir) != "fixedbugs" {
			action = "skip"
		}
	default:
		action = "skip"
	}
	switch action {
	case "rundircmpout":
		action = "rundir"
		t.action = "rundir"
	case "cmpout":
		action = "run"  
		fallthrough
	case "compile", "compiledir", "build", "run", "runoutput", "rundir":
		t.action = action
	case "errorcheck", "errorcheckdir", "errorcheckoutput":
		t.action = action
		wantError = true
		for len(args) > 0 && strings.HasPrefix(args[0], "-") {
			if args[0] == "-0" {
				wantError = false
			} else {
				flags = append(flags, args[0])
			}
			args = args[1:]
		}
	case "skip":
		t.action = "skip"
		return
	default:
		t.err = skipError("skipped; unknown pattern: " + action)
		t.action = "??"
		return
	}
	t.makeTempDir()
	defer os.RemoveAll(t.tempDir)
	err = ioutil.WriteFile(filepath.Join(t.tempDir, t.gofile), srcBytes, 0644)
	check(err)
	if os.Getenv("GOOS") == "" {
		os.Setenv("GOOS", runtime.GOOS)
	}
	if os.Getenv("GOARCH") == "" {
		os.Setenv("GOARCH", runtime.GOARCH)
	}
	useTmp := true
	runcmd := func(args ...string) ([]byte, error) {
		cmd := exec.Command(args[0], args[1:]...)
		var buf bytes.Buffer
		cmd.Stdout = &buf
		cmd.Stderr = &buf
		if useTmp {
			cmd.Dir = t.tempDir
			cmd.Env = envForDir(cmd.Dir)
		}
		err := cmd.Run()
		if err != nil {
			err = fmt.Errorf("%s\n%s", err, buf.Bytes())
		}
		return buf.Bytes(), err
	}
	long := filepath.Join(cwd, t.goFileName())
	switch action {
	default:
		t.err = fmt.Errorf("unimplemented action %q", action)
	case "errorcheck":
		cmdline := []string{"go", "tool", "compile", "-e", "-o", "a.o"}
		cmdline = append(cmdline, flags...)
		cmdline = append(cmdline, long)
		out, err := runcmd(cmdline...)
		if wantError {
			if err == nil {
				t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
				return
			}
		} else {
			if err != nil {
				t.err = err
				return
			}
		}
		if *updateErrors {
			t.updateErrors(string(out), long)
		}
		t.err = t.errorCheck(string(out), long, t.gofile)
		return
	case "compile":
		_, t.err = compileFile(runcmd, long)
	case "compiledir":
		longdir := filepath.Join(cwd, t.goDirName())
		pkgs, err := goDirPackages(longdir)
		if err != nil {
			t.err = err
			return
		}
		for _, gofiles := range pkgs {
			_, t.err = compileInDir(runcmd, longdir, gofiles...)
			if t.err != nil {
				return
			}
		}
	case "errorcheckdir":
		longdir := filepath.Join(cwd, t.goDirName())
		pkgs, err := goDirPackages(longdir)
		if err != nil {
			t.err = err
			return
		}
		for i, gofiles := range pkgs {
			out, err := compileInDir(runcmd, longdir, gofiles...)
			if i == len(pkgs)-1 {
				if wantError && err == nil {
					t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
					return
				} else if !wantError && err != nil {
					t.err = err
					return
				}
			} else if err != nil {
				t.err = err
				return
			}
			var fullshort []string
			for _, name := range gofiles {
				fullshort = append(fullshort, filepath.Join(longdir, name), name)
			}
			t.err = t.errorCheck(string(out), fullshort...)
			if t.err != nil {
				break
			}
		}
	case "rundir":
		longdir := filepath.Join(cwd, t.goDirName())
		pkgs, err := goDirPackages(longdir)
		if err != nil {
			t.err = err
			return
		}
		for i, gofiles := range pkgs {
			_, err := compileInDir(runcmd, longdir, gofiles...)
			if err != nil {
				t.err = err
				return
			}
			if i == len(pkgs)-1 {
				err = linkFile(runcmd, gofiles[0])
				if err != nil {
					t.err = err
					return
				}
				var cmd []string
				cmd = append(cmd, findExecCmd()...)
				cmd = append(cmd, filepath.Join(t.tempDir, "a.exe"))
				cmd = append(cmd, args...)
				out, err := runcmd(cmd...)
				if err != nil {
					t.err = err
					return
				}
				if strings.Replace(string(out), "\r\n", "\n", -1) != t.expectedOutput() {
					t.err = fmt.Errorf("incorrect output\n%s", out)
				}
			}
		}
	case "build":
		_, err := runcmd("go", "build", "-o", "a.exe", long)
		if err != nil {
			t.err = err
		}
	case "run":
		useTmp = false
		out, err := runcmd(append([]string{"gopherjs", "run", "-q", t.goFileName()}, args...)...)
		if err != nil {
			t.err = err
			return
		}
		if strings.Replace(string(out), "\r\n", "\n", -1) != t.expectedOutput() {
			t.err = fmt.Errorf("incorrect output\n%s", out)
		}
	case "runoutput":
		rungatec <- true
		defer func() {
			<-rungatec
		}()
		useTmp = false
		out, err := runcmd(append([]string{"go", "run", t.goFileName()}, args...)...)
		if err != nil {
			t.err = err
			return
		}
		tfile := filepath.Join(t.tempDir, "tmp__.go")
		if err := ioutil.WriteFile(tfile, out, 0666); err != nil {
			t.err = fmt.Errorf("write tempfile:%s", err)
			return
		}
		out, err = runcmd("go", "run", tfile)
		if err != nil {
			t.err = err
			return
		}
		if string(out) != t.expectedOutput() {
			t.err = fmt.Errorf("incorrect output\n%s", out)
		}
	case "errorcheckoutput":
		useTmp = false
		out, err := runcmd(append([]string{"go", "run", t.goFileName()}, args...)...)
		if err != nil {
			t.err = err
			return
		}
		tfile := filepath.Join(t.tempDir, "tmp__.go")
		err = ioutil.WriteFile(tfile, out, 0666)
		if err != nil {
			t.err = fmt.Errorf("write tempfile:%s", err)
			return
		}
		cmdline := []string{"go", "tool", "compile", "-e", "-o", "a.o"}
		cmdline = append(cmdline, flags...)
		cmdline = append(cmdline, tfile)
		out, err = runcmd(cmdline...)
		if wantError {
			if err == nil {
				t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
				return
			}
		} else {
			if err != nil {
				t.err = err
				return
			}
		}
		t.err = t.errorCheck(string(out), tfile, "tmp__.go")
		return
	}
}
run runs a test.
package main
import (
	"bytes"
	"errors"
	"flag"
	"fmt"
	"hash/fnv"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"regexp"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"time"
	"unicode"
)
var knownFails = map[string]failReason{
	"fixedbugs/bug114.go":     {desc: "fixedbugs/bug114.go:15:27: B32 (untyped int constant 4294967295) overflows int"},
	"fixedbugs/bug242.go":     {desc: "bad map check 13 false false Error: fail"},
	"fixedbugs/bug260.go":     {desc: "maybe unsupportedFeature, pointer arithm"},
	"fixedbugs/bug262.go":     {desc: "Error: fail"},
	"fixedbugs/bug273.go":     {desc: "BUG: didn't crash:  badcap1"},
	"fixedbugs/bug328.go":     {desc: "incorrect output"},
	"fixedbugs/bug347.go":     {desc: "BUG: bug347: cannot find caller"},
	"fixedbugs/bug348.go":     {desc: "BUG: bug348: cannot find caller"},
	"fixedbugs/bug352.go":     {desc: "BUG: bug352 struct{}"},
	"fixedbugs/bug409.go":     {desc: "1 2 3 4"},
	"fixedbugs/bug433.go":     {desc: "Error: [object Object]"},
	"fixedbugs/issue10353.go": {desc: "incorrect output"},
	"fixedbugs/issue11656.go": {desc: "Error: Native function not implemented: runtime/debug.setPanicOnFault"},
	"fixedbugs/issue4085b.go": {desc: "Error: got panic JavaScript error: Invalid typed array length, want len out of range"},
	"fixedbugs/issue4316.go":  {desc: "Error: runtime error: invalid memory address or nil pointer dereference"},
	"fixedbugs/issue4388.go":  {desc: "Error: expected <autogenerated>:1 have anonymous function:0"},
	"fixedbugs/issue4562.go":  {desc: "Error: cannot find issue4562.go on stack"},
	"fixedbugs/issue4620.go":  {desc: "map[0:1 1:2], Error: m[i] != 2"},
	"fixedbugs/issue5856.go":  {category: requiresSourceMapSupport},
	"fixedbugs/issue6899.go":  {desc: "incorrect output -0"},
	"fixedbugs/issue7550.go":  {desc: "FATAL ERROR: invalid table size Allocation failed - process out of memory"},
	"fixedbugs/issue7690.go":  {desc: "Error: runtime error: slice bounds out of range"},
	"fixedbugs/issue8047.go":  {desc: "null"},
	"fixedbugs/issue8047b.go": {desc: "Error: [object Object]"},
	"fixedbugs/issue10607.go": {desc: "os/exec.Command unsupported"},
	"fixedbugs/issue13268.go": {desc: "os/exec.Command unsupported"},
	"fixedbugs/issue14636.go": {desc: "os/exec.Command unsupported"},
	"fixedbugs/issue14646.go": {category: unsureIfGopherJSSupportsThisFeature, desc: "tests runtime.Caller behavior in a deferred func in SSA backend... does GopherJS even support runtime.Caller?"},
	"fixedbugs/issue15039.go": {desc: "valid bug but deal with after Go 1.7 support is out? it's likely not a regression"},
	"fixedbugs/issue15281.go": {desc: "also looks valid but deal with after Go 1.7 support is out? it's likely not a regression"},
	"fixedbugs/issue15975.go": {desc: "also looks valid but deal with after Go 1.7 support is out?"},
	"fixedbugs/issue17381.go": {category: unsureIfGopherJSSupportsThisFeature, desc: "tests runtime.{Callers,FuncForPC} behavior in a deferred func with garbage on stack... does GopherJS even support runtime.{Callers,FuncForPC}?"},
	"fixedbugs/issue18149.go": {desc: "//line directives with filenames are not correctly parsed, see https://github.com/gopherjs/gopherjs/issues/553."},
	"fixedbugs/issue19182.go": {category: neverTerminates, desc: "needs GOMAXPROCS=2"},
	"fixedbugs/issue19040.go": {desc: `panicwrap error text:
			"runtime error: invalid memory address or nil pointer dereference"
		want:
			"value method main.T.F called using nil *T pointer"`},
	"fixedbugs/issue19246.go": {desc: "expected nil pointer dereference panic"},  
	"fixedbugs/issue21879.go": {desc: "incorrect output related to runtime.Callers, runtime.CallersFrames, etc."},
	"fixedbugs/issue21887.go": {desc: "incorrect output (although within spec, not worth fixing) for println(^uint64(0)). got: { '$high': 4294967295, '$low': 4294967295, '$val': [Circular] } want: 18446744073709551615"},
	"fixedbugs/issue22083.go": {category: requiresSourceMapSupport},  
	"fixedbugs/issue22660.go": {category: notApplicable, desc: "test of gc compiler, uses os/exec.Command"},
	"fixedbugs/issue23305.go": {desc: "GopherJS fails to compile println(0xffffffff), maybe because 32-bit arch"},
	"fixedbugs/issue21221.go":  {category: usesUnsupportedPackage, desc: "uses unsafe package and compares nil pointers"},
	"fixedbugs/issue22662.go":  {desc: "line directives not fully working. Error: got /private/var/folders/b8/66r1c5856mqds1mrf2tjtq8w0000gn/T:1; want ??:1"},
	"fixedbugs/issue22662b.go": {category: usesUnsupportedPackage, desc: "os/exec.Command unsupported"},
	"fixedbugs/issue23188.go":  {desc: "incorrect order of evaluation of index operations"},
	"fixedbugs/issue24547.go":  {desc: "incorrect computing method sets with shadowed methods"},
	"fixedbugs/issue28688.go": {category: notApplicable, desc: "testing runtime optimisations"},
	"fixedbugs/issue23837.go":  {desc: "missing panic on nil pointer-to-empty-struct dereference"},
	"fixedbugs/issue27201.go":  {desc: "incorrect stack trace for nil dereference in inlined function"},
	"fixedbugs/issue27518b.go": {desc: "sigpanic can make dead pointer live again"},
	"fixedbugs/issue29190.go":  {desc: "append does not fail when length overflows"},
	"fixedbugs/issue15002.go":  {desc: "native function not implemented: syscall.Getpagesize"},
	"fixedbugs/issue15992.go":  {desc: "native function not implemented: syscall.Getpagesize"},
	"fixedbugs/issue19113.go":  {desc: "did not panic"},
	"fixedbugs/issue22326.go":  {desc: "incorrect output for print"},
	"fixedbugs/issue28748.go":  {desc: "reflect error"},
	"fixedbugs/issue29504.go":  {desc: "did not panic"},
	"fixedbugs/issue30116.go":  {desc: "index out of range"},
	"fixedbugs/issue30116u.go": {desc: "index out of range"},
	"fixedbugs/issue30977.go":  {category: neverTerminates, desc: "timeout"},
	"fixedbugs/issue31546.go":  {desc: "throw error"},
	"fixedbugs/issue32477.go":  {desc: "heap object finalized at the wrong time"},
	"fixedbugs/issue32680.go":  {desc: "unknown shorthand flag"},
	"fixedbugs/issue15277.go": {category: neverTerminates, desc: "skip amd64"},
	"fixedbugs/issue34395.go": {category: neverTerminates, desc: "FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory"},
	"fixedbugs/issue35027.go": {desc: "unknown shorthand flag: 'g' in -gcflags=-d=checkptr"},
	"fixedbugs/issue35073.go": {desc: "unknown shorthand flag: 'g' in -gcflags=-d=checkptr"},
	"fixedbugs/issue35576.go": {desc: "unknown shorthand flag: 'g' in -gcflags=-d=checkptr"},
	"fixedbugs/issue40917.go": {desc: "unknown shorthand flag: 'g' in -gcflags=-d=checkptr"},
	"fixedbugs/issue40629.go": {desc: "throw err"},
	"fixedbugs/issue24491a.go": {desc: "throw err"},
	"fixedbugs/issue24491b.go": {desc: "throw err"},
}
var knownFailsWindows = map[string]failReason{
	"fixedbugs/bug130.go":     {desc: "fatal error: all goroutines are asleep - deadlock!"},
	"fixedbugs/issue18725.go": {desc: "fatal error: all goroutines are asleep - deadlock!"},
	"fixedbugs/issue29190.go": {category: neverTerminates, desc: " make([]T, maxInt) time out"},
	"fixedbugs/issue29215.go": {category: neverTerminates, desc: "time out"},
	"fixedbugs/issue7525.go":  {category: neverTerminates, desc: "initialization cycle"},
	"fixedbugs/issue7525b.go": {category: neverTerminates, desc: "initialization cycle"},
	"fixedbugs/issue7525c.go": {category: neverTerminates, desc: "initialization cycle"},
	"fixedbugs/issue7525d.go": {category: neverTerminates, desc: "initialization cycle"},
	"fixedbugs/issue7525e.go": {category: neverTerminates, desc: "initialization cycle"},
	"fixedbugs/issue7538a.go": {category: neverTerminates, desc: "label _ not declared"},
	"fixedbugs/issue7538b.go": {category: neverTerminates, desc: "panic: interface conversion: types.Object is nil, not *types.Label"},
	"fixedbugs/issue7547.go":  {category: neverTerminates, desc: "time out"},
	"fixedbugs/issue7550.go":  {category: neverTerminates, desc: "time out"},
}
type failCategory uint8
const (
	other                    failCategory = iota
	neverTerminates                        
	usesUnsupportedPackage                 
	requiresSourceMapSupport               
	compilerPanic
	unsureIfGopherJSSupportsThisFeature
	notApplicable  
)
type failReason struct {
	category failCategory
	desc     string
}
var (
	verbose        = flag.Bool("v", false, "verbose. if set, parallelism is set to 1.")
	numParallel    = flag.Int("n", runtime.NumCPU(), "number of parallel tests to run")
	summary        = flag.Bool("summary", false, "show summary of results")
	showSkips      = flag.Bool("show_skips", false, "show skipped tests")
	showKnownFails = flag.Bool("show_known_fails", false, "show full error output of known fails")
	updateErrors   = flag.Bool("update_errors", false, "update error messages in test file based on compiler output")
	runoutputLimit = flag.Int("l", defaultRunOutputLimit(), "number of parallel runoutput tests to run")
	shard  = flag.Int("shard", 0, "shard index to run. Only applicable if -shards is non-zero.")
	shards = flag.Int("shards", 0, "number of shards. If 0, all tests are run. This is used by the continuous build.")
)
var (
	goos, goarch string
	dirs = []string{".", "ken", "chan", "interface", "syntax", "dwarf", "fixedbugs"}
	ratec chan bool
	toRun chan *test
	rungatec chan bool
)
const maxTests = 5000
func main() {
	flag.Parse()
	err := os.Chdir(filepath.Join(runtime.GOROOT(), "test"))
	if err != nil {
		log.Fatalln(err)
	}
	goos = getenv("GOOS", runtime.GOOS)
	goarch = getenv("GOARCH", "js")  
	if *verbose {
		fmt.Printf("goos: %q, goarch: %q\n", goos, goarch)
	}
	if goos == "windows" {
		for k, v := range knownFailsWindows {
			knownFails[k] = v
		}
	}
	findExecCmd()
	if *verbose || len(findExecCmd()) > 0 {
		*numParallel = 1
	}
	ratec = make(chan bool, *numParallel)
	rungatec = make(chan bool, *runoutputLimit)
	var tests []*test
	if flag.NArg() > 0 {
		for _, arg := range flag.Args() {
			if arg == "-" || arg == "--" {
				continue
			}
			if fi, err := os.Stat(arg); err == nil && fi.IsDir() {
				for _, baseGoFile := range goFiles(arg) {
					tests = append(tests, startTest(arg, baseGoFile))
				}
			} else if strings.HasSuffix(arg, ".go") {
				dir, file := filepath.Split(arg)
				tests = append(tests, startTest(dir, file))
			} else {
				log.Fatalf("can't yet deal with non-directory and non-go file %q", arg)
			}
		}
	} else {
		for _, dir := range dirs {
			for _, baseGoFile := range goFiles(dir) {
				tests = append(tests, startTest(dir, baseGoFile))
			}
		}
	}
	failed := false
	resCount := map[string]int{}
	for _, test := range tests {
		<-test.donec
		if test.action == "skip" && !*showSkips {
			continue
		}
		status := "ok  "
		errStr := ""
		if _, ok := knownFails[filepath.ToSlash(test.goFileName())]; ok && test.err != nil {
			errStr = test.err.Error()
			test.err = nil
			status = "knfl"  
		} else if ok && test.err == nil {
			status = "unok"
		}
		if _, isSkip := test.err.(skipError); isSkip {
			test.err = nil
			errStr = "unexpected skip for " + path.Join(test.dir, test.gofile) + ": " + errStr
			status = "FAIL"
		}
		if test.err != nil {
			status = "FAIL"
			errStr = test.err.Error()
		}
		if status == "FAIL" {
			failed = true
		}
		if status == "unok" {
			failed = true
		}
		resCount[status]++
		if status == "skip" && !*verbose && !*showSkips {
			continue
		}
		dt := fmt.Sprintf("%.3fs", test.dt.Seconds())
		if status == "FAIL" {
			fmt.Printf("# go run run.go -- %s\n%s\nFAIL\t%s\t%s\n",
				path.Join(test.dir, test.gofile),
				errStr, test.goFileName(), dt)
			continue
		}
		if status == "knfl" && *showKnownFails {
			fmt.Printf("# go run run.go -show_known_fails -- %s\n%s\nknfl\t%s\t%s\n",
				path.Join(test.dir, test.gofile),
				errStr, test.goFileName(), dt)
			continue
		}
		if !*verbose && status != "unok" {
			continue
		}
		fmt.Printf("%s\t%s\t%s\n", status, test.goFileName(), dt)
	}
	if *summary {
		for k, v := range resCount {
			fmt.Printf("%5d %s\n", v, k)
		}
	}
	if failed {
		os.Exit(1)
	}
}
func toolPath(name string) string {
	p := filepath.Join(os.Getenv("GOROOT"), "bin", "tool", name)
	if _, err := os.Stat(p); err != nil {
		log.Fatalf("didn't find binary at %s", p)
	}
	return p
}
func shardMatch(name string) bool {
	if *shards == 0 {
		return true
	}
	h := fnv.New32()
	io.WriteString(h, name)
	return int(h.Sum32()%uint32(*shards)) == *shard
}
func goFiles(dir string) []string {
	f, err := os.Open(dir)
	check(err)
	dirnames, err := f.Readdirnames(-1)
	check(err)
	names := []string{}
	for _, name := range dirnames {
		if !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") && shardMatch(name) {
			names = append(names, name)
		}
	}
	sort.Strings(names)
	return names
}
type runCmd func(...string) ([]byte, error)
func compileFile(runcmd runCmd, longname string) (out []byte, err error) {
	return runcmd("go", "tool", "compile", "-e", longname)
}
func compileInDir(runcmd runCmd, dir string, names ...string) (out []byte, err error) {
	cmd := []string{"go", "tool", "compile", "-e", "-D", ".", "-I", "."}
	for _, name := range names {
		cmd = append(cmd, filepath.Join(dir, name))
	}
	return runcmd(cmd...)
}
func linkFile(runcmd runCmd, goname string) (err error) {
	pfile := strings.Replace(goname, ".go", ".o", -1)
	_, err = runcmd("go", "tool", "link", "-w", "-o", "a.exe", "-L", ".", pfile)
	return
}
type skipError string
func (s skipError) Error() string { return string(s) }
func check(err error) {
	if err != nil {
		log.Fatal(err)
	}
}
type test struct {
	dir, gofile string
	donec       chan bool  
	dt          time.Duration
	src    string
	action string  
	tempDir string
	err     error
}
func startTest(dir, gofile string) *test {
	t := &test{
		dir:    dir,
		gofile: gofile,
		donec:  make(chan bool, 1),
	}
	if toRun == nil {
		toRun = make(chan *test, maxTests)
		go runTests()
	}
	select {
	case toRun <- t:
	default:
		panic("toRun buffer size (maxTests) is too small")
	}
	return t
}
func runTests() {
	for {
		ratec <- true
		t := <-toRun
		go func() {
			t.run()
			<-ratec
		}()
	}
}
var cwd, _ = os.Getwd()
func (t *test) goFileName() string {
	return filepath.Join(t.dir, t.gofile)
}
func (t *test) goDirName() string {
	return filepath.Join(t.dir, strings.Replace(t.gofile, ".go", ".dir", -1))
}
func goDirFiles(longdir string) (filter []os.FileInfo, err error) {
	files, dirErr := ioutil.ReadDir(longdir)
	if dirErr != nil {
		return nil, dirErr
	}
	for _, gofile := range files {
		if filepath.Ext(gofile.Name()) == ".go" {
			filter = append(filter, gofile)
		}
	}
	return
}
var packageRE = regexp.MustCompile(`(?m)^package (\w+)`)
func goDirPackages(longdir string) ([][]string, error) {
	files, err := goDirFiles(longdir)
	if err != nil {
		return nil, err
	}
	var pkgs [][]string
	m := make(map[string]int)
	for _, file := range files {
		name := file.Name()
		data, err := ioutil.ReadFile(filepath.Join(longdir, name))
		if err != nil {
			return nil, err
		}
		pkgname := packageRE.FindStringSubmatch(string(data))
		if pkgname == nil {
			return nil, fmt.Errorf("cannot find package name in %s", name)
		}
		i, ok := m[pkgname[1]]
		if !ok {
			i = len(pkgs)
			pkgs = append(pkgs, nil)
			m[pkgname[1]] = i
		}
		pkgs[i] = append(pkgs[i], name)
	}
	return pkgs, nil
}
type context struct {
	GOOS   string
	GOARCH string
}
func shouldTest(src string, goos, goarch string) (ok bool, whyNot string) {
	if goarch == "js" {
		goarch = "nacl"
	}
	for _, line := range strings.Split(src, "\n") {
		line = strings.TrimSpace(line)
		if strings.HasPrefix(line, "//") {
			line = line[2:]
		} else {
			continue
		}
		line = strings.TrimSpace(line)
		if len(line) == 0 || line[0] != '+' {
			continue
		}
		ctxt := &context{
			GOOS:   goos,
			GOARCH: goarch,
		}
		words := strings.Fields(line)
		if words[0] == "+build" {
			ok := false
			for _, word := range words[1:] {
				if ctxt.match(word) {
					ok = true
					break
				}
			}
			if !ok {
				return false, line
			}
		}
	}
	return true, ""
}
func (ctxt *context) match(name string) bool {
	if name == "" {
		return false
	}
	if i := strings.Index(name, ","); i >= 0 {
		return ctxt.match(name[:i]) && ctxt.match(name[i+1:])
	}
	if strings.HasPrefix(name, "!!") {  
		return false
	}
	if strings.HasPrefix(name, "!") {  
		if name[1:] == "js" {
			return false
		}
		return len(name) > 1 && !ctxt.match(name[1:])
	}
	for _, c := range name {
		if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' {
			return false
		}
	}
	if name == ctxt.GOOS || name == ctxt.GOARCH {
		return true
	}
	return false
}
func init() { checkShouldTest() }