Commit 4ce79096 authored by Rob Pike's avatar Rob Pike

go/types: delete from main repo; part of move to go.exp

See also https://golang.org/cl/7656044

R=golang-dev, gri, rsc
CC=golang-dev
https://golang.org/cl/7625048
parent bfe80e21
......@@ -5,13 +5,16 @@
// +build gotypes
// This file contains the pieces of the tool that require the go/types package.
// To compile this file, you must first run
// $ go get code.google.com/p/go.exp/go/types
package main
import (
"go/ast"
"go/token"
"go/types"
"code.google.com/p/go.exp/go/types"
)
// Type is equivalent to go/types.Type. Repeating it here allows us to avoid
......
......@@ -134,15 +134,14 @@ echo
if [ "$GOHOSTARCH" != "$GOARCH" -o "$GOHOSTOS" != "$GOOS" ]; then
echo "# Building packages and commands for host, $GOHOSTOS/$GOHOSTARCH."
# TODO: Drop the -tags gotypes before releasing Go 1.1. It is to allow type checking in go vet.
GOOS=$GOHOSTOS GOARCH=$GOHOSTARCH \
"$GOTOOLDIR"/go_bootstrap install -ccflags "$GO_CCFLAGS" -gcflags "$GO_GCFLAGS" -ldflags "$GO_LDFLAGS" -tags gotypes -v std
"$GOTOOLDIR"/go_bootstrap install -ccflags "$GO_CCFLAGS" -gcflags "$GO_GCFLAGS" -ldflags "$GO_LDFLAGS" -v std
echo
fi
echo "# Building packages and commands for $GOOS/$GOARCH."
# TODO: Drop the -tags gotypes before releasing Go 1.1. It is to allow type checking in go vet.
"$GOTOOLDIR"/go_bootstrap install $GO_FLAGS -ccflags "$GO_CCFLAGS" -gcflags "$GO_GCFLAGS" -ldflags "$GO_LDFLAGS" -tags gotypes -v std
"$GOTOOLDIR"/go_bootstrap install $GO_FLAGS -ccflags "$GO_CCFLAGS" -gcflags "$GO_GCFLAGS" -ldflags "$GO_LDFLAGS" -v std
echo
rm -f "$GOTOOLDIR"/go_bootstrap
......
......@@ -90,16 +90,14 @@ echo # Building tools for local system. %GOHOSTOS%/%GOHOSTARCH%
setlocal
set GOOS=%GOHOSTOS%
set GOARCH=%GOHOSTARCH%
:: TODO: Drop the -tags gotypes before releasing Go 1.1. It is to allow type checking in go vet.
"%GOTOOLDIR%\go_bootstrap" install -gcflags "%GO_GCFLAGS%" -ldflags "%GO_LDFLAGS%" -tags gotypes -v std
"%GOTOOLDIR%\go_bootstrap" install -gcflags "%GO_GCFLAGS%" -ldflags "%GO_LDFLAGS%" -v std
endlocal
if errorlevel 1 goto fail
echo.
:mainbuild
echo # Building packages and commands.
:: TODO: Drop the -tags gotypes before releasing Go 1.1. It is to allow type checking in go vet.
"%GOTOOLDIR%\go_bootstrap" install -gcflags "%GO_GCFLAGS%" -ldflags "%GO_LDFLAGS%" -a -tags gotypes -v std
"%GOTOOLDIR%\go_bootstrap" install -gcflags "%GO_GCFLAGS%" -ldflags "%GO_LDFLAGS%" -a -v std
if errorlevel 1 goto fail
del "%GOTOOLDIR%\go_bootstrap.exe"
echo.
......
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package types declares the data structures for representing
// Go types and implements typechecking of package files.
//
// WARNING: THE TYPES API IS SUBJECT TO CHANGE.
//
package types
import (
"go/ast"
"go/token"
)
// A Context specifies the supporting context for type checking.
// An empty Context is a ready-to-use default context.
type Context struct {
// If Error != nil, it is called with each error found
// during type checking. The error strings of errors with
// detailed position information are formatted as follows:
// filename:line:column: message
Error func(err error)
// If Ident != nil, it is called for each identifier id
// denoting an Object in the files provided to Check, and
// obj is the denoted object.
// Ident is not called for fields and methods in struct or
// interface types or composite literals, or for blank (_)
// or dot (.) identifiers in dot-imports.
// TODO(gri) Consider making Fields and Methods ordinary
// Objects - than we could lift this restriction.
Ident func(id *ast.Ident, obj Object)
// If Expr != nil, it is called exactly once for each expression x
// that is type-checked: typ is the expression type, and val is the
// value if x is constant, val is nil otherwise.
//
// If x is a literal value (constant, composite literal), typ is always
// the dynamic type of x (never an interface type). Otherwise, typ is x's
// static type (possibly an interface type).
//
// Constants are represented as follows:
//
// bool -> bool
// numeric -> int64, *big.Int, *big.Rat, Complex
// string -> string
// nil -> NilType
//
// Constant values are normalized, that is, they are represented
// using the "smallest" possible type that can represent the value.
// For instance, 1.0 is represented as an int64 because it can be
// represented accurately as an int64.
Expr func(x ast.Expr, typ Type, val interface{})
// If Import != nil, it is called for each imported package.
// Otherwise, GcImporter is called.
Import Importer
// If Alignof != nil, it is called to determine the alignment
// of the given type. Otherwise DefaultAlignmentof is called.
// Alignof must implement the alignment guarantees required by
// the spec.
Alignof func(Type) int64
// If Offsetsof != nil, it is called to determine the offsets
// of the given struct fields, in bytes. Otherwise DefaultOffsetsof
// is called. Offsetsof must implement the offset guarantees
// required by the spec.
Offsetsof func(fields []*Field) []int64
// If Sizeof != nil, it is called to determine the size of the
// given type. Otherwise, DefaultSizeof is called. Sizeof must
// implement the size guarantees required by the spec.
Sizeof func(Type) int64
}
// An Importer resolves import paths to Package objects.
// The imports map records the packages already imported,
// indexed by package id (canonical import path).
// An Importer must determine the canonical import path and
// check the map to see if it is already present in the imports map.
// If so, the Importer can return the map entry. Otherwise, the
// Importer should load the package data for the given path into
// a new *Package, record pkg in the imports map, and then
// return pkg.
type Importer func(imports map[string]*Package, path string) (pkg *Package, err error)
// Check resolves and typechecks a set of package files within the given
// context. It returns the package and the first error encountered, if
// any. If the context's Error handler is nil, Check terminates as soon
// as the first error is encountered; otherwise it continues until the
// entire package is checked. If there are errors, the package may be
// only partially type-checked, and the resulting package may be incomplete
// (missing objects, imports, etc.).
func (ctxt *Context) Check(fset *token.FileSet, files []*ast.File) (*Package, error) {
return check(ctxt, fset, files)
}
// Check is shorthand for ctxt.Check where ctxt is a default (empty) context.
func Check(fset *token.FileSet, files []*ast.File) (*Package, error) {
var ctxt Context
return ctxt.Check(fset, files)
}
This diff is collapsed.
This diff is collapsed.
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file implements a typechecker test harness. The packages specified
// in tests are typechecked. Error messages reported by the typechecker are
// compared against the error messages expected in the test files.
//
// Expected errors are indicated in the test files by putting a comment
// of the form /* ERROR "rx" */ immediately following an offending token.
// The harness will verify that an error matching the regular expression
// rx is reported at that source position. Consecutive comments may be
// used to indicate multiple errors for the same token position.
//
// For instance, the following test file indicates that a "not declared"
// error should be reported for the undeclared variable x:
//
// package p
// func f() {
// _ = x /* ERROR "not declared" */ + 1
// }
package types
import (
"flag"
"fmt"
"go/ast"
"go/parser"
"go/scanner"
"go/token"
"io/ioutil"
"os"
"regexp"
"testing"
)
var listErrors = flag.Bool("list", false, "list errors")
// The test filenames do not end in .go so that they are invisible
// to gofmt since they contain comments that must not change their
// positions relative to surrounding tokens.
var tests = []struct {
name string
files []string
}{
{"decls0", []string{"testdata/decls0.src"}},
{"decls1", []string{"testdata/decls1.src"}},
{"decls2", []string{"testdata/decls2a.src", "testdata/decls2b.src"}},
{"decls3", []string{"testdata/decls3.src"}},
{"const0", []string{"testdata/const0.src"}},
{"expr0", []string{"testdata/expr0.src"}},
{"expr1", []string{"testdata/expr1.src"}},
{"expr2", []string{"testdata/expr2.src"}},
{"expr3", []string{"testdata/expr3.src"}},
{"shifts", []string{"testdata/shifts.src"}},
{"builtins", []string{"testdata/builtins.src"}},
{"conversions", []string{"testdata/conversions.src"}},
{"stmt0", []string{"testdata/stmt0.src"}},
{"stmt1", []string{"testdata/stmt1.src"}},
}
var fset = token.NewFileSet()
// Positioned errors are of the form filename:line:column: message .
var posMsgRx = regexp.MustCompile(`^(.*:[0-9]+:[0-9]+): *(.*)`)
// splitError splits an error's error message into a position string
// and the actual error message. If there's no position information,
// pos is the empty string, and msg is the entire error message.
//
func splitError(err error) (pos, msg string) {
msg = err.Error()
if m := posMsgRx.FindStringSubmatch(msg); len(m) == 3 {
pos = m[1]
msg = m[2]
}
return
}
func parseFiles(t *testing.T, testname string, filenames []string) ([]*ast.File, []error) {
var files []*ast.File
var errlist []error
for _, filename := range filenames {
file, err := parser.ParseFile(fset, filename, nil, parser.DeclarationErrors|parser.AllErrors)
if file == nil {
t.Fatalf("%s: could not parse file %s", testname, filename)
}
files = append(files, file)
if err != nil {
if list, _ := err.(scanner.ErrorList); len(list) > 0 {
for _, err := range list {
errlist = append(errlist, err)
}
} else {
errlist = append(errlist, err)
}
}
}
return files, errlist
}
// ERROR comments must be of the form /* ERROR "rx" */ and rx is
// a regular expression that matches the expected error message.
//
var errRx = regexp.MustCompile(`^/\* *ERROR *"([^"]*)" *\*/$`)
// errMap collects the regular expressions of ERROR comments found
// in files and returns them as a map of error positions to error messages.
//
func errMap(t *testing.T, testname string, files []*ast.File) map[string][]string {
// map of position strings to lists of error message patterns
errmap := make(map[string][]string)
for _, file := range files {
filename := fset.Position(file.Package).Filename
src, err := ioutil.ReadFile(filename)
if err != nil {
t.Fatalf("%s: could not read %s", testname, filename)
}
var s scanner.Scanner
s.Init(fset.AddFile(filename, fset.Base(), len(src)), src, nil, scanner.ScanComments)
var prev string // position string of last non-comment, non-semicolon token
scanFile:
for {
pos, tok, lit := s.Scan()
switch tok {
case token.EOF:
break scanFile
case token.COMMENT:
if s := errRx.FindStringSubmatch(lit); len(s) == 2 {
errmap[prev] = append(errmap[prev], s[1])
}
case token.SEMICOLON:
// ignore automatically inserted semicolon
if lit == "\n" {
continue scanFile
}
fallthrough
default:
prev = fset.Position(pos).String()
}
}
}
return errmap
}
func eliminate(t *testing.T, errmap map[string][]string, errlist []error) {
for _, err := range errlist {
pos, gotMsg := splitError(err)
list := errmap[pos]
index := -1 // list index of matching message, if any
// we expect one of the messages in list to match the error at pos
for i, wantRx := range list {
rx, err := regexp.Compile(wantRx)
if err != nil {
t.Errorf("%s: %v", pos, err)
continue
}
if rx.MatchString(gotMsg) {
index = i
break
}
}
if index >= 0 {
// eliminate from list
if n := len(list) - 1; n > 0 {
// not the last entry - swap in last element and shorten list by 1
list[index] = list[n]
errmap[pos] = list[:n]
} else {
// last entry - remove list from map
delete(errmap, pos)
}
} else {
t.Errorf("%s: no error expected: %q", pos, gotMsg)
}
}
}
func checkFiles(t *testing.T, testname string, testfiles []string) {
// parse files and collect parser errors
files, errlist := parseFiles(t, testname, testfiles)
// typecheck and collect typechecker errors
var ctxt Context
ctxt.Error = func(err error) { errlist = append(errlist, err) }
ctxt.Check(fset, files)
if *listErrors {
t.Errorf("--- %s: %d errors found:", testname, len(errlist))
for _, err := range errlist {
t.Error(err)
}
return
}
// match and eliminate errors;
// we are expecting the following errors
errmap := errMap(t, testname, files)
eliminate(t, errmap, errlist)
// there should be no expected errors left
if len(errmap) > 0 {
t.Errorf("--- %s: %d source positions with expected (but not reported) errors:", testname, len(errmap))
for pos, list := range errmap {
for _, rx := range list {
t.Errorf("%s: %q", pos, rx)
}
}
}
}
var testBuiltinsDeclared = false
func TestCheck(t *testing.T) {
// Declare builtins for testing.
// Not done in an init func to avoid an init race with
// the construction of the Universe var.
if !testBuiltinsDeclared {
testBuiltinsDeclared = true
// Pkg == nil for Universe objects
def(&Func{Name: "assert", Type: &builtin{_Assert, "assert", 1, false, true}})
def(&Func{Name: "trace", Type: &builtin{_Trace, "trace", 0, true, true}})
}
// For easy debugging w/o changing the testing code,
// if there is a local test file, only test that file.
const testfile = "testdata/test.go"
if fi, err := os.Stat(testfile); err == nil && !fi.IsDir() {
fmt.Printf("WARNING: Testing only %s (remove it to run all tests)\n", testfile)
checkFiles(t, testfile, []string{testfile})
return
}
// Otherwise, run all the tests.
for _, test := range tests {
checkFiles(t, test.name, test.files)
}
}
This diff is collapsed.
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file implements typechecking of conversions.
package types
import (
"go/ast"
)
// conversion typechecks the type conversion conv to type typ. iota is the current
// value of iota or -1 if iota doesn't have a value in the current context. The result
// of the conversion is returned via x. If the conversion has type errors, the returned
// x is marked as invalid (x.mode == invalid).
//
func (check *checker) conversion(x *operand, conv *ast.CallExpr, typ Type, iota int) {
// all conversions have one argument
if len(conv.Args) != 1 {
check.invalidOp(conv.Pos(), "%s conversion requires exactly one argument", conv)
goto Error
}
// evaluate argument
check.expr(x, conv.Args[0], nil, iota)
if x.mode == invalid {
goto Error
}
if x.mode == constant && isConstType(typ) {
// constant conversion
typ := underlying(typ).(*Basic)
// For now just implement string(x) where x is an integer,
// as a temporary work-around for issue 4982, which is a
// common issue.
if typ.Kind == String {
switch {
case x.isInteger():
codepoint, ok := x.val.(int64)
if !ok {
// absolute value too large (or unknown) for conversion;
// same as converting any other out-of-range value - let
// string(codepoint) do the work
codepoint = -1
}
x.val = string(codepoint)
case isString(x.typ):
// nothing to do
default:
goto ErrorMsg
}
}
// TODO(gri) verify the remaining conversions.
} else {
// non-constant conversion
if !x.isConvertible(check.ctxt, typ) {
goto ErrorMsg
}
x.mode = value
}
// the conversion argument types are final
check.updateExprType(x.expr, x.typ, true)
check.conversions[conv] = true // for cap/len checking
x.expr = conv
x.typ = typ
return
ErrorMsg:
check.invalidOp(conv.Pos(), "cannot convert %s to %s", x, typ)
Error:
x.mode = invalid
x.expr = conv
}
func (x *operand) isConvertible(ctxt *Context, T Type) bool {
// "x is assignable to T"
if x.isAssignable(ctxt, T) {
return true
}
// "x's type and T have identical underlying types"
V := x.typ
Vu := underlying(V)
Tu := underlying(T)
if IsIdentical(Vu, Tu) {
return true
}
// "x's type and T are unnamed pointer types and their pointer base types have identical underlying types"
if V, ok := V.(*Pointer); ok {
if T, ok := T.(*Pointer); ok {
if IsIdentical(underlying(V.Base), underlying(T.Base)) {
return true
}
}
}
// "x's type and T are both integer or floating point types"
if (isInteger(V) || isFloat(V)) && (isInteger(T) || isFloat(T)) {
return true
}
// "x's type and T are both complex types"
if isComplex(V) && isComplex(T) {
return true
}
// "x is an integer or a slice of bytes or runes and T is a string type"
if (isInteger(V) || isBytesOrRunes(Vu)) && isString(T) {
return true
}
// "x is a string and T is a slice of bytes or runes"
if isString(V) && isBytesOrRunes(Tu) {
return true
}
// package unsafe:
// "any pointer or value of underlying type uintptr can be converted into a unsafe.Pointer"
if (isPointer(Vu) || isUintptr(Vu)) && isUnsafePointer(T) {
return true
}
// "and vice versa"
if isUnsafePointer(V) && (isPointer(Tu) || isUintptr(Tu)) {
return true
}
return false
}
func isUintptr(typ Type) bool {
t, ok := typ.(*Basic)
return ok && t.Kind == Uintptr
}
func isUnsafePointer(typ Type) bool {
t, ok := typ.(*Basic)
return ok && t.Kind == UnsafePointer
}
func isPointer(typ Type) bool {
_, ok := typ.(*Pointer)
return ok
}
func isBytesOrRunes(typ Type) bool {
if s, ok := typ.(*Slice); ok {
t, ok := underlying(s.Elt).(*Basic)
return ok && (t.Kind == Byte || t.Kind == Rune)
}
return false
}
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file implements various error reporters.
package types
import (
"bytes"
"fmt"
"go/ast"
"go/token"
)
// TODO(gri) eventually assert and unimplemented should disappear.
func assert(p bool) {
if !p {
panic("assertion failed")
}
}
func unreachable() {
panic("unreachable")
}
func (check *checker) printTrace(format string, args []interface{}) {
const dots = ". . . . . . . . . . . . . . . . . . . . "
n := len(check.pos) - 1
i := 3 * n
for i > len(dots) {
fmt.Print(dots)
i -= len(dots)
}
// i <= len(dots)
fmt.Printf("%s:\t", check.fset.Position(check.pos[n]))
fmt.Print(dots[0:i])
fmt.Println(check.formatMsg(format, args))
}
func (check *checker) trace(pos token.Pos, format string, args ...interface{}) {
check.pos = append(check.pos, pos)
check.printTrace(format, args)
}
func (check *checker) untrace(format string, args ...interface{}) {
if len(format) > 0 {
check.printTrace(format, args)
}
check.pos = check.pos[:len(check.pos)-1]
}
func (check *checker) formatMsg(format string, args []interface{}) string {
for i, arg := range args {
switch a := arg.(type) {
case token.Pos:
args[i] = check.fset.Position(a).String()
case ast.Expr:
args[i] = exprString(a)
case Type:
args[i] = typeString(a)
case operand:
panic("internal error: should always pass *operand")
}
}
return fmt.Sprintf(format, args...)
}
// dump is only needed for debugging
func (check *checker) dump(format string, args ...interface{}) {
fmt.Println(check.formatMsg(format, args))
}
func (check *checker) err(err error) {
if check.firsterr == nil {
check.firsterr = err
}
f := check.ctxt.Error
if f == nil {
panic(bailout{}) // report only first error
}
f(err)
}
func (check *checker) errorf(pos token.Pos, format string, args ...interface{}) {
check.err(fmt.Errorf("%s: %s", check.fset.Position(pos), check.formatMsg(format, args)))
}
func (check *checker) invalidAST(pos token.Pos, format string, args ...interface{}) {
check.errorf(pos, "invalid AST: "+format, args...)
}
func (check *checker) invalidArg(pos token.Pos, format string, args ...interface{}) {
check.errorf(pos, "invalid argument: "+format, args...)
}
func (check *checker) invalidOp(pos token.Pos, format string, args ...interface{}) {
check.errorf(pos, "invalid operation: "+format, args...)
}
// exprString returns a (simplified) string representation for an expression.
func exprString(expr ast.Expr) string {
var buf bytes.Buffer
writeExpr(&buf, expr)
return buf.String()
}
// TODO(gri) Need to merge with typeString since some expressions are types (try: ([]int)(a))
func writeExpr(buf *bytes.Buffer, expr ast.Expr) {
switch x := expr.(type) {
case *ast.Ident:
buf.WriteString(x.Name)
case *ast.BasicLit:
buf.WriteString(x.Value)
case *ast.FuncLit:
buf.WriteString("(func literal)")
case *ast.CompositeLit:
buf.WriteString("(composite literal)")
case *ast.ParenExpr:
buf.WriteByte('(')
writeExpr(buf, x.X)
buf.WriteByte(')')
case *ast.SelectorExpr:
writeExpr(buf, x.X)
buf.WriteByte('.')
buf.WriteString(x.Sel.Name)
case *ast.IndexExpr:
writeExpr(buf, x.X)
buf.WriteByte('[')
writeExpr(buf, x.Index)
buf.WriteByte(']')
case *ast.SliceExpr:
writeExpr(buf, x.X)
buf.WriteByte('[')
if x.Low != nil {
writeExpr(buf, x.Low)
}
buf.WriteByte(':')
if x.High != nil {
writeExpr(buf, x.High)
}
buf.WriteByte(']')
case *ast.TypeAssertExpr:
writeExpr(buf, x.X)
buf.WriteString(".(...)")
case *ast.CallExpr:
writeExpr(buf, x.Fun)
buf.WriteByte('(')
for i, arg := range x.Args {
if i > 0 {
buf.WriteString(", ")
}
writeExpr(buf, arg)
}
buf.WriteByte(')')
case *ast.StarExpr:
buf.WriteByte('*')
writeExpr(buf, x.X)
case *ast.UnaryExpr:
buf.WriteString(x.Op.String())
writeExpr(buf, x.X)
case *ast.BinaryExpr:
// The AST preserves source-level parentheses so there is
// no need to introduce parentheses here for correctness.
writeExpr(buf, x.X)
buf.WriteByte(' ')
buf.WriteString(x.Op.String())
buf.WriteByte(' ')
writeExpr(buf, x.Y)
default:
fmt.Fprintf(buf, "<expr %T>", x)
}
}
// typeString returns a string representation for typ.
func typeString(typ Type) string {
var buf bytes.Buffer
writeType(&buf, typ)
return buf.String()
}
func writeParams(buf *bytes.Buffer, params []*Var, isVariadic bool) {
buf.WriteByte('(')
for i, par := range params {
if i > 0 {
buf.WriteString(", ")
}
if par.Name != "" {
buf.WriteString(par.Name)
buf.WriteByte(' ')
}
if isVariadic && i == len(params)-1 {
buf.WriteString("...")
}
writeType(buf, par.Type)
}
buf.WriteByte(')')
}
func writeSignature(buf *bytes.Buffer, sig *Signature) {
writeParams(buf, sig.Params, sig.IsVariadic)
if len(sig.Results) == 0 {
// no result
return
}
buf.WriteByte(' ')
if len(sig.Results) == 1 && sig.Results[0].Name == "" {
// single unnamed result
writeType(buf, sig.Results[0].Type.(Type))
return
}
// multiple or named result(s)
writeParams(buf, sig.Results, false)
}
func writeType(buf *bytes.Buffer, typ Type) {
switch t := typ.(type) {
case nil:
buf.WriteString("<nil>")
case *Basic:
buf.WriteString(t.Name)
case *Array:
fmt.Fprintf(buf, "[%d]", t.Len)
writeType(buf, t.Elt)
case *Slice:
buf.WriteString("[]")
writeType(buf, t.Elt)
case *Struct:
buf.WriteString("struct{")
for i, f := range t.Fields {
if i > 0 {
buf.WriteString("; ")
}
if !f.IsAnonymous {
buf.WriteString(f.Name)
buf.WriteByte(' ')
}
writeType(buf, f.Type)
if f.Tag != "" {
fmt.Fprintf(buf, " %q", f.Tag)
}
}
buf.WriteByte('}')
case *Pointer:
buf.WriteByte('*')
writeType(buf, t.Base)
case *Result:
writeParams(buf, t.Values, false)
case *Signature:
buf.WriteString("func")
writeSignature(buf, t)
case *builtin:
fmt.Fprintf(buf, "<type of %s>", t.name)
case *Interface:
buf.WriteString("interface{")
for i, m := range t.Methods {
if i > 0 {
buf.WriteString("; ")
}
buf.WriteString(m.Name)
writeSignature(buf, m.Type)
}
buf.WriteByte('}')
case *Map:
buf.WriteString("map[")
writeType(buf, t.Key)
buf.WriteByte(']')
writeType(buf, t.Elt)
case *Chan:
var s string
switch t.Dir {
case ast.SEND:
s = "chan<- "
case ast.RECV:
s = "<-chan "
default:
s = "chan "
}
buf.WriteString(s)
writeType(buf, t.Elt)
case *NamedType:
s := "<NamedType w/o object>"
if obj := t.Obj; obj != nil {
if obj.Pkg != nil && obj.Pkg.Path != "" {
buf.WriteString(obj.Pkg.Path)
buf.WriteString(".")
}
s = t.Obj.GetName()
}
buf.WriteString(s)
default:
fmt.Fprintf(buf, "<type %T>", t)
}
}
func (t *Array) String() string { return typeString(t) }
func (t *Basic) String() string { return typeString(t) }
func (t *Chan) String() string { return typeString(t) }
func (t *Interface) String() string { return typeString(t) }
func (t *Map) String() string { return typeString(t) }
func (t *NamedType) String() string { return typeString(t) }
func (t *Pointer) String() string { return typeString(t) }
func (t *Result) String() string { return typeString(t) }
func (t *Signature) String() string { return typeString(t) }
func (t *Slice) String() string { return typeString(t) }
func (t *Struct) String() string { return typeString(t) }
func (t *builtin) String() string { return typeString(t) }
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file implements FindGcExportData.
package types
import (
"bufio"
"errors"
"fmt"
"io"
"strconv"
"strings"
)
func readGopackHeader(r *bufio.Reader) (name string, size int, err error) {
// See $GOROOT/include/ar.h.
hdr := make([]byte, 16+12+6+6+8+10+2)
_, err = io.ReadFull(r, hdr)
if err != nil {
return
}
// leave for debugging
if false {
fmt.Printf("header: %s", hdr)
}
s := strings.TrimSpace(string(hdr[16+12+6+6+8:][:10]))
size, err = strconv.Atoi(s)
if err != nil || hdr[len(hdr)-2] != '`' || hdr[len(hdr)-1] != '\n' {
err = errors.New("invalid archive header")
return
}
name = strings.TrimSpace(string(hdr[:16]))
return
}
// FindGcExportData positions the reader r at the beginning of the
// export data section of an underlying GC-created object/archive
// file by reading from it. The reader must be positioned at the
// start of the file before calling this function.
//
func FindGcExportData(r *bufio.Reader) (err error) {
// Read first line to make sure this is an object file.
line, err := r.ReadSlice('\n')
if err != nil {
return
}
if string(line) == "!<arch>\n" {
// Archive file. Scan to __.PKGDEF, which should
// be second archive entry.
var name string
var size int
// First entry should be __.GOSYMDEF.
// Older archives used __.SYMDEF, so allow that too.
// Read and discard.
if name, size, err = readGopackHeader(r); err != nil {
return
}
if name != "__.SYMDEF" && name != "__.GOSYMDEF" {
err = errors.New("go archive does not begin with __.SYMDEF or __.GOSYMDEF")
return
}
const block = 4096
tmp := make([]byte, block)
for size > 0 {
n := size
if n > block {
n = block
}
if _, err = io.ReadFull(r, tmp[:n]); err != nil {
return
}
size -= n
}
// Second entry should be __.PKGDEF.
if name, size, err = readGopackHeader(r); err != nil {
return
}
if name != "__.PKGDEF" {
err = errors.New("go archive is missing __.PKGDEF")
return
}
// Read first line of __.PKGDEF data, so that line
// is once again the first line of the input.
if line, err = r.ReadSlice('\n'); err != nil {
return
}
}
// Now at __.PKGDEF in archive or still at beginning of file.
// Either way, line should begin with "go object ".
if !strings.HasPrefix(string(line), "go object ") {
err = errors.New("not a go object file")
return
}
// Skip over object header to export data.
// Begins after first line with $$.
for line[0] != '$' {
if line, err = r.ReadSlice('\n'); err != nil {
return
}
}
return
}
This diff is collapsed.
This diff is collapsed.
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
import (
"go/ast"
"go/build"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
var gcPath string // Go compiler path
func init() {
// determine compiler
var gc string
switch runtime.GOARCH {
case "386":
gc = "8g"
case "amd64":
gc = "6g"
case "arm":
gc = "5g"
default:
gcPath = "unknown-GOARCH-compiler"
return
}
gcPath = filepath.Join(build.ToolDir, gc)
}
func compile(t *testing.T, dirname, filename string) string {
cmd := exec.Command(gcPath, filename)
cmd.Dir = dirname
out, err := cmd.CombinedOutput()
if err != nil {
t.Logf("%s", out)
t.Fatalf("%s %s failed: %s", gcPath, filename, err)
}
archCh, _ := build.ArchChar(runtime.GOARCH)
// filename should end with ".go"
return filepath.Join(dirname, filename[:len(filename)-2]+archCh)
}
// Use the same global imports map for all tests. The effect is
// as if all tested packages were imported into a single package.
var imports = make(map[string]*Package)
func testPath(t *testing.T, path string) bool {
t0 := time.Now()
_, err := GcImport(imports, path)
if err != nil {
t.Errorf("testPath(%s): %s", path, err)
return false
}
t.Logf("testPath(%s): %v", path, time.Since(t0))
return true
}
const maxTime = 30 * time.Second
func testDir(t *testing.T, dir string, endTime time.Time) (nimports int) {
dirname := filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_"+runtime.GOARCH, dir)
list, err := ioutil.ReadDir(dirname)
if err != nil {
t.Fatalf("testDir(%s): %s", dirname, err)
}
for _, f := range list {
if time.Now().After(endTime) {
t.Log("testing time used up")
return
}
switch {
case !f.IsDir():
// try extensions
for _, ext := range pkgExts {
if strings.HasSuffix(f.Name(), ext) {
name := f.Name()[0 : len(f.Name())-len(ext)] // remove extension
if testPath(t, filepath.Join(dir, name)) {
nimports++
}
}
}
case f.IsDir():
nimports += testDir(t, filepath.Join(dir, f.Name()), endTime)
}
}
return
}
func TestGcImport(t *testing.T) {
// On cross-compile builds, the path will not exist.
// Need to use GOHOSTOS, which is not available.
if _, err := os.Stat(gcPath); err != nil {
t.Skipf("skipping test: %v", err)
}
if outFn := compile(t, "testdata", "exports.go"); outFn != "" {
defer os.Remove(outFn)
}
nimports := 0
if testPath(t, "./testdata/exports") {
nimports++
}
nimports += testDir(t, "", time.Now().Add(maxTime)) // installed packages
t.Logf("tested %d imports", nimports)
}
var importedObjectTests = []struct {
name string
kind ast.ObjKind
typ string
}{
{"unsafe.Pointer", ast.Typ, "Pointer"},
{"math.Pi", ast.Con, "untyped float"},
{"io.Reader", ast.Typ, "interface{Read(p []byte) (n int, err error)}"},
{"io.ReadWriter", ast.Typ, "interface{Read(p []byte) (n int, err error); Write(p []byte) (n int, err error)}"},
{"math.Sin", ast.Fun, "func(x·2 float64) (_ float64)"},
// TODO(gri) add more tests
}
func TestGcImportedTypes(t *testing.T) {
// This package does not yet know how to read gccgo export data.
if runtime.Compiler == "gccgo" {
return
}
for _, test := range importedObjectTests {
s := strings.Split(test.name, ".")
if len(s) != 2 {
t.Fatal("inconsistent test data")
}
importPath := s[0]
objName := s[1]
pkg, err := GcImport(imports, importPath)
if err != nil {
t.Error(err)
continue
}
obj := pkg.Scope.Lookup(objName)
// TODO(gri) should define an accessor on Object
var kind ast.ObjKind
var typ Type
switch obj := obj.(type) {
case *Const:
kind = ast.Con
typ = obj.Type
case *TypeName:
kind = ast.Typ
typ = obj.Type
case *Var:
kind = ast.Var
typ = obj.Type
case *Func:
kind = ast.Fun
typ = obj.Type
default:
unreachable()
}
if kind != test.kind {
t.Errorf("%s: got kind = %q; want %q", test.name, kind, test.kind)
}
str := typeString(underlying(typ))
if str != test.typ {
t.Errorf("%s: got type = %q; want %q", test.name, typ, test.typ)
}
}
}
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
import (
"go/ast"
"go/token"
)
// An Object describes a named language entity such as a package,
// constant, type, variable, function (incl. methods), or label.
// All objects implement the Object interface.
//
type Object interface {
GetPkg() *Package
GetName() string
GetType() Type
GetPos() token.Pos
anObject()
}
// A Package represents the contents (objects) of a Go package.
type Package struct {
Name string
Path string // import path, "" for current (non-imported) package
Scope *Scope // package-level scope
Imports map[string]*Package // map of import paths to imported packages
Complete bool // if set, this package was imported completely
spec *ast.ImportSpec
}
// A Const represents a declared constant.
type Const struct {
Pkg *Package
Name string
Type Type
Val interface{} // nil means unknown constant value due to type error
visited bool // for initialization cycle detection
spec *ast.ValueSpec
}
// A TypeName represents a declared type.
type TypeName struct {
Pkg *Package
Name string
Type Type // *NamedType or *Basic
spec *ast.TypeSpec
}
// A Variable represents a declared variable (including function parameters and results).
type Var struct {
Pkg *Package // nil for parameters
Name string
Type Type
visited bool // for initialization cycle detection
decl interface{}
}
// A Func represents a declared function.
type Func struct {
Pkg *Package
Name string
Type Type // *Signature or *Builtin
decl *ast.FuncDecl
}
func (obj *Package) GetPkg() *Package { return obj }
func (obj *Const) GetPkg() *Package { return obj.Pkg }
func (obj *TypeName) GetPkg() *Package { return obj.Pkg }
func (obj *Var) GetPkg() *Package { return obj.Pkg }
func (obj *Func) GetPkg() *Package { return obj.Pkg }
func (obj *Package) GetName() string { return obj.Name }
func (obj *Const) GetName() string { return obj.Name }
func (obj *TypeName) GetName() string { return obj.Name }
func (obj *Var) GetName() string { return obj.Name }
func (obj *Func) GetName() string { return obj.Name }
func (obj *Package) GetType() Type { return Typ[Invalid] }
func (obj *Const) GetType() Type { return obj.Type }
func (obj *TypeName) GetType() Type { return obj.Type }
func (obj *Var) GetType() Type { return obj.Type }
func (obj *Func) GetType() Type { return obj.Type }
func (obj *Package) GetPos() token.Pos {
if obj.spec != nil {
return obj.spec.Pos()
}
return token.NoPos
}
func (obj *Const) GetPos() token.Pos {
for _, n := range obj.spec.Names {
if n.Name == obj.Name {
return n.Pos()
}
}
return token.NoPos
}
func (obj *TypeName) GetPos() token.Pos {
if obj.spec != nil {
return obj.spec.Pos()
}
return token.NoPos
}
func (obj *Var) GetPos() token.Pos {
switch d := obj.decl.(type) {
case *ast.Field:
for _, n := range d.Names {
if n.Name == obj.Name {
return n.Pos()
}
}
case *ast.ValueSpec:
for _, n := range d.Names {
if n.Name == obj.Name {
return n.Pos()
}
}
case *ast.AssignStmt:
for _, x := range d.Lhs {
if ident, isIdent := x.(*ast.Ident); isIdent && ident.Name == obj.Name {
return ident.Pos()
}
}
}
return token.NoPos
}
func (obj *Func) GetPos() token.Pos {
if obj.decl != nil && obj.decl.Name != nil {
return obj.decl.Name.Pos()
}
return token.NoPos
}
func (*Package) anObject() {}
func (*Const) anObject() {}
func (*TypeName) anObject() {}
func (*Var) anObject() {}
func (*Func) anObject() {}
// newObj returns a new Object for a given *ast.Object.
// It does not canonicalize them (it always returns a new one).
// For canonicalization, see check.lookup.
//
// TODO(gri) Once we do identifier resolution completely in
// in the typechecker, this functionality can go.
//
func newObj(pkg *Package, astObj *ast.Object) Object {
assert(pkg != nil)
name := astObj.Name
typ, _ := astObj.Type.(Type)
switch astObj.Kind {
case ast.Bad:
// ignore
case ast.Pkg:
unreachable()
case ast.Con:
return &Const{Pkg: pkg, Name: name, Type: typ, Val: astObj.Data, spec: astObj.Decl.(*ast.ValueSpec)}
case ast.Typ:
return &TypeName{Pkg: pkg, Name: name, Type: typ, spec: astObj.Decl.(*ast.TypeSpec)}
case ast.Var:
switch astObj.Decl.(type) {
case *ast.Field: // function parameters
case *ast.ValueSpec: // proper variable declarations
case *ast.AssignStmt: // short variable declarations
default:
unreachable() // everything else is not ok
}
return &Var{Pkg: pkg, Name: name, Type: typ, decl: astObj.Decl}
case ast.Fun:
return &Func{Pkg: pkg, Name: name, Type: typ, decl: astObj.Decl.(*ast.FuncDecl)}
case ast.Lbl:
unreachable() // for now
}
unreachable()
return nil
}
This diff is collapsed.
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file implements commonly used type predicates.
package types
func isNamed(typ Type) bool {
if _, ok := typ.(*Basic); ok {
return ok
}
_, ok := typ.(*NamedType)
return ok
}
func isBoolean(typ Type) bool {
t, ok := underlying(typ).(*Basic)
return ok && t.Info&IsBoolean != 0
}
func isInteger(typ Type) bool {
t, ok := underlying(typ).(*Basic)
return ok && t.Info&IsInteger != 0
}
func isUnsigned(typ Type) bool {
t, ok := underlying(typ).(*Basic)
return ok && t.Info&IsUnsigned != 0
}
func isFloat(typ Type) bool {
t, ok := underlying(typ).(*Basic)
return ok && t.Info&IsFloat != 0
}
func isComplex(typ Type) bool {
t, ok := underlying(typ).(*Basic)
return ok && t.Info&IsComplex != 0
}
func isNumeric(typ Type) bool {
t, ok := underlying(typ).(*Basic)
return ok && t.Info&IsNumeric != 0
}
func isString(typ Type) bool {
t, ok := underlying(typ).(*Basic)
return ok && t.Info&IsString != 0
}
func isUntyped(typ Type) bool {
t, ok := underlying(typ).(*Basic)
return ok && t.Info&IsUntyped != 0
}
func isOrdered(typ Type) bool {
t, ok := underlying(typ).(*Basic)
return ok && t.Info&IsOrdered != 0
}
func isConstType(typ Type) bool {
t, ok := underlying(typ).(*Basic)
return ok && t.Info&IsConstType != 0
}
func isComparable(typ Type) bool {
switch t := underlying(typ).(type) {
case *Basic:
return t.Kind != Invalid && t.Kind != UntypedNil
case *Pointer, *Interface, *Chan:
// assumes types are equal for pointers and channels
return true
case *Struct:
for _, f := range t.Fields {
if !isComparable(f.Type) {
return false
}
}
return true
case *Array:
return isComparable(t.Elt)
}
return false
}
func hasNil(typ Type) bool {
switch underlying(typ).(type) {
case *Slice, *Pointer, *Signature, *Interface, *Map, *Chan:
return true
}
return false
}
// IsIdentical returns true if x and y are identical.
func IsIdentical(x, y Type) bool {
if x == y {
return true
}
switch x := x.(type) {
case *Basic:
// Basic types are singletons except for the rune and byte
// aliases, thus we cannot solely rely on the x == y check
// above.
if y, ok := y.(*Basic); ok {
return x.Kind == y.Kind
}
case *Array:
// Two array types are identical if they have identical element types
// and the same array length.
if y, ok := y.(*Array); ok {
return x.Len == y.Len && IsIdentical(x.Elt, y.Elt)
}
case *Slice:
// Two slice types are identical if they have identical element types.
if y, ok := y.(*Slice); ok {
return IsIdentical(x.Elt, y.Elt)
}
case *Struct:
// Two struct types are identical if they have the same sequence of fields,
// and if corresponding fields have the same names, and identical types,
// and identical tags. Two anonymous fields are considered to have the same
// name. Lower-case field names from different packages are always different.
if y, ok := y.(*Struct); ok {
if len(x.Fields) == len(y.Fields) {
for i, f := range x.Fields {
g := y.Fields[i]
if !f.QualifiedName.IsSame(g.QualifiedName) ||
!IsIdentical(f.Type, g.Type) ||
f.Tag != g.Tag ||
f.IsAnonymous != g.IsAnonymous {
return false
}
}
return true
}
}
case *Pointer:
// Two pointer types are identical if they have identical base types.
if y, ok := y.(*Pointer); ok {
return IsIdentical(x.Base, y.Base)
}
case *Signature:
// Two function types are identical if they have the same number of parameters
// and result values, corresponding parameter and result types are identical,
// and either both functions are variadic or neither is. Parameter and result
// names are not required to match.
if y, ok := y.(*Signature); ok {
return identicalTypes(x.Params, y.Params) &&
identicalTypes(x.Results, y.Results) &&
x.IsVariadic == y.IsVariadic
}
case *Interface:
// Two interface types are identical if they have the same set of methods with
// the same names and identical function types. Lower-case method names from
// different packages are always different. The order of the methods is irrelevant.
if y, ok := y.(*Interface); ok {
return identicalMethods(x.Methods, y.Methods) // methods are sorted
}
case *Map:
// Two map types are identical if they have identical key and value types.
if y, ok := y.(*Map); ok {
return IsIdentical(x.Key, y.Key) && IsIdentical(x.Elt, y.Elt)
}
case *Chan:
// Two channel types are identical if they have identical value types
// and the same direction.
if y, ok := y.(*Chan); ok {
return x.Dir == y.Dir && IsIdentical(x.Elt, y.Elt)
}
case *NamedType:
// Two named types are identical if their type names originate
// in the same type declaration.
if y, ok := y.(*NamedType); ok {
return x.Obj == y.Obj
}
}
return false
}
// identicalTypes returns true if both lists a and b have the
// same length and corresponding objects have identical types.
func identicalTypes(a, b []*Var) bool {
if len(a) != len(b) {
return false
}
for i, x := range a {
y := b[i]
if !IsIdentical(x.Type, y.Type) {
return false
}
}
return true
}
// identicalMethods returns true if both lists a and b have the
// same length and corresponding methods have identical types.
// TODO(gri) make this more efficient
func identicalMethods(a, b []*Method) bool {
if len(a) != len(b) {
return false
}
m := make(map[QualifiedName]*Method)
for _, x := range a {
assert(m[x.QualifiedName] == nil) // method list must not have duplicate entries
m[x.QualifiedName] = x
}
for _, y := range b {
if x := m[y.QualifiedName]; x == nil || !IsIdentical(x.Type, y.Type) {
return false
}
}
return true
}
// underlying returns the underlying type of typ.
func underlying(typ Type) Type {
// Basic types are representing themselves directly even though they are named.
if typ, ok := typ.(*NamedType); ok {
return typ.Underlying // underlying types are never NamedTypes
}
return typ
}
// deref returns a pointer's base type; otherwise it returns typ.
func deref(typ Type) Type {
if typ, ok := underlying(typ).(*Pointer); ok {
return typ.Base
}
return typ
}
// defaultType returns the default "typed" type for an "untyped" type;
// it returns the incoming type for all other types. If there is no
// corresponding untyped type, the result is Typ[Invalid].
//
func defaultType(typ Type) Type {
if t, ok := typ.(*Basic); ok {
k := Invalid
switch t.Kind {
// case UntypedNil:
// There is no default type for nil. For a good error message,
// catch this case before calling this function.
case UntypedBool:
k = Bool
case UntypedInt:
k = Int
case UntypedRune:
k = Rune
case UntypedFloat:
k = Float64
case UntypedComplex:
k = Complex128
case UntypedString:
k = String
}
typ = Typ[k]
}
return typ
}
// missingMethod returns (nil, false) if typ implements T, otherwise
// it returns the first missing method required by T and whether it
// is missing or simply has the wrong type.
//
func missingMethod(typ Type, T *Interface) (method *Method, wrongType bool) {
// TODO(gri): this needs to correctly compare method names (taking package into account)
// TODO(gri): distinguish pointer and non-pointer receivers
// an interface type implements T if it has no methods with conflicting signatures
// Note: This is stronger than the current spec. Should the spec require this?
if ityp, _ := underlying(typ).(*Interface); ityp != nil {
for _, m := range T.Methods {
res := lookupField(ityp, m.QualifiedName) // TODO(gri) no need to go via lookupField
if res.mode != invalid && !IsIdentical(res.typ, m.Type) {
return m, true
}
}
return
}
// a concrete type implements T if it implements all methods of T.
for _, m := range T.Methods {
res := lookupField(typ, m.QualifiedName)
if res.mode == invalid {
return m, false
}
if !IsIdentical(res.typ, m.Type) {
return m, true
}
}
return
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment