Пример #1
0
func printIncReturnsVerbose(fset *token.FileSet, v map[*ast.ReturnStmt]*ast.FuncType) {
	for ret, ftyp := range v {
		fmt.Print("FUNC TYPE: ")
		ast.Print(fset, ftyp)
		fmt.Print("   RETURN: ")
		ast.Print(fset, ret)
		fmt.Println()
	}
}
Пример #2
0
func main() {
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "parsing.go", nil, 0)
	if err != nil {
		log.Fatalf("failed parsing file: %s", err)
	}
	ast.Print(fset, f)

	expr, err := parser.ParseExpr(`foo.Bar(1, "argument", something())`)
	if err != nil {
		log.Fatal("failed parsing expression: %s", err)
	}
	ast.Print(nil, expr)
}
Пример #3
0
func (v *GoAstVisitor) Visit(node ast.Node) (w ast.Visitor) {
	if node != nil {
		fmt.Println(reflect.TypeOf(node))
		if typeSpec, ok := node.(*ast.TypeSpec); ok {
			ast.Print(fset, typeSpec)
			v.TypeName = typeSpec.Name.Name
		}
		if funcSpec, ok := node.(*ast.FuncDecl); ok {
			ast.Print(fset, funcSpec.Recv)
			ast.Print(fset, funcSpec.Type)
			v.Funcs = append(v.Funcs, funcSpec)
			// funcSpec.Type.Params.List[0].Names[0].Name
		}
	}
	return v
}
Пример #4
0
func main() {
	fileSet := token.NewFileSet()
	astFile, err := parser.ParseFile(fileSet, "minimal.go", nil, parser.ParseComments)
	if err != nil {
		panic(err)
	}
	ast.Print(fileSet, astFile)

	return

	astFile.Decls = append(astFile.Decls[:0], append([]ast.Decl{&ast.FuncDecl{
		Name: ast.NewIdent("MyNewFunc"),
		Type: &ast.FuncType{
			Func: 15,
			Params: &ast.FieldList{
				Opening: 29,
				Closing: 30,
			},
		},
	}}, astFile.Decls[0:]...)...)

	offset := astFile.Decls[0].End() - astFile.Decls[0].Pos()
	intoffset := int(offset)
	fmt.Println("offset", offset)
	astFile.Comments[0].List[0].Slash += offset
	// astFile.Comments[0].List[0].Slash = 18
	astFile.Decls[1].(*ast.GenDecl).TokPos += offset
	astFile.Decls[1].(*ast.GenDecl).Lparen += offset
	astFile.Decls[1].(*ast.GenDecl).Rparen += offset
	fileSetFile := fileSet.File(1)
	newFileSet := token.NewFileSet()
	newFileSetFile := newFileSet.AddFile("whatever", 1, fileSetFile.Size()+int(offset))
	newFileSetFile.SetLines([]int{
		0,
		13,
		14,
		15,
		15 + intoffset,
		20 + intoffset,
		21 + intoffset,
		32 + intoffset,
		33 + intoffset,
	}) // hardcoded for now

	fmt.Println("astFile:")
	spew.Dump(astFile)
	fmt.Println()
	fmt.Println()
	fmt.Println("fileSet:")
	spew.Dump(fileSet)
	buf := new(bytes.Buffer)

	err = printer.Fprint(buf, newFileSet, astFile)
	if err != nil {
		panic(err)
	}

	fmt.Println(buf)

}
Пример #5
0
func NewTypeExpr(pkgName, importPath string, imports map[string]string, expr ast.Expr) (string, TypeExpr) {
	switch t := expr.(type) {
	case *ast.Ident:
		if IsBultinType(t.Name) {
			pkgName = ""
			importPath = ""
		}
		return importPath, TypeExpr{t.Name, pkgName, 0, true}
	case *ast.SelectorExpr:
		_, e := NewTypeExpr(pkgName, importPath, imports, t.X)
		return imports[e.Expr], TypeExpr{t.Sel.Name, e.Expr, e.PkgIdx, e.Valid}
	case *ast.StarExpr:
		i, e := NewTypeExpr(pkgName, importPath, imports, t.X)
		return i, TypeExpr{"*" + e.Expr, e.PkgName, e.PkgIdx + 1, e.Valid}
	case *ast.ArrayType:
		i, e := NewTypeExpr(pkgName, importPath, imports, t.Elt)
		return i, TypeExpr{"[]" + e.Expr, e.PkgName, e.PkgIdx + 2, e.Valid}
	case *ast.Ellipsis:
		i, e := NewTypeExpr(pkgName, importPath, imports, t.Elt)
		return i, TypeExpr{"[]" + e.Expr, e.PkgName, e.PkgIdx + 3, e.Valid}
	default:
		log.Println("Failed to generate name for field.")
		ast.Print(nil, expr)
	}
	return "", TypeExpr{Valid: false}
}
Пример #6
0
func TestCheck(t *testing.T) {
	// src is the input for which we want to print the AST.
	src := `
package main

// T comment
type T struct {
	// S1 comment
	S1 string

	// S2 comment
	S2 string

	// S3 comment
	S3 string
}

// E is a type E
type E int
const (
	E1 E = 1
	E2 E = 2
)
`

	// Create the AST by parsing src.
	fset := token.NewFileSet() // positions are relative to fset
	f, err := parser.ParseFile(fset, "", src, parser.ParseComments)
	if err != nil {
		panic(err)
	}

	ast.Print(fset, f)
}
Пример #7
0
// This returns the syntactic expression for referencing this type in Go.
func NewTypeExpr(pkgName string, expr ast.Expr) TypeExpr {
	switch t := expr.(type) {
	case *ast.Ident:
		if IsBuiltinType(t.Name) {
			pkgName = ""
		}
		return TypeExpr{t.Name, pkgName, 0}
	case *ast.SelectorExpr:
		e := NewTypeExpr(pkgName, t.X)
		return TypeExpr{t.Sel.Name, e.Expr, 0}
	case *ast.StarExpr:
		e := NewTypeExpr(pkgName, t.X)
		return TypeExpr{"*" + e.Expr, e.PkgName, e.pkgIndex + 1}
	case *ast.ArrayType:
		e := NewTypeExpr(pkgName, t.Elt)
		return TypeExpr{"[]" + e.Expr, e.PkgName, e.pkgIndex + 2}
	case *ast.Ellipsis:
		e := NewTypeExpr(pkgName, t.Elt)
		return TypeExpr{"[]" + e.Expr, e.PkgName, e.pkgIndex + 2}
	default:
		log.Println("Failed to generate name for field.")
		ast.Print(nil, expr)
	}
	return TypeExpr{}
}
Пример #8
0
func main() {
	var err error
	var p *ast.Object
	var pp []*ast.Object = make([]*ast.Object, 0)

	for _, s := range packages {
		p, err = types.GcImport(imports, s)
		if err != nil {
			panic(err)
		}
		pp = append(pp, p)
	}

	fset := token.NewFileSet()
	for i, pkg := range pp {
		Printf("\n")
		Printf("%s: \n", packages[i])
		Printf("\n")
		Printf("pkg=%#v\n", pkg)
		Printf("\n")
		Printf("pkg.Data=%#v\n", pkg.Data)
		Printf("\n")
		ast.Print(fset, pkg)
		Printf("\n")
		Printf("\n")
	}

}
Пример #9
0
func Transform(src *ast.File) *ast.File {
	// find the golex import...
	var toplevel ToplevelVisitor

	for _, spec := range src.Imports {
		ast.Print(nil, spec)
		if conv, err := strconv.Unquote(spec.Path.Value); err != nil || conv != "golex" {
			continue
		}
		if spec.Name != nil {
			toplevel.golexPackage = spec.Name.Name
		} else {
			toplevel.golexPackage = "golex"
		}
		break
	}
	if toplevel.golexPackage == "" {
		log.Print("Not a lex input")

		return src
	}

	ast.Walk(&toplevel, src)
	// Now, find switch statemnts...
	return src
}
Пример #10
0
func dumpAst(files ...string) {
	for _, arg := range files {
		// Ensure file exists and not a directory
		st, e := os.Stat(arg)
		if e != nil {
			fmt.Fprintf(os.Stderr, "Skipping: %s - %s\n", arg, e)
			continue
		}
		if st.IsDir() {
			fmt.Fprintf(os.Stderr, "Skipping: %s - directory\n", arg)
			continue
		}

		// Create the AST by parsing src.
		fset := token.NewFileSet() // positions are relative to fset
		f, err := parser.ParseFile(fset, arg, nil, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Unable to parse file %s\n", err)
			continue
		}

		// Print the AST.
		ast.Print(fset, f)
	}
}
Пример #11
0
func main() {
	flag.Parse()
	if len(flag.Args()) != 1 {
		log.Fatal("Usage: go run goprint.go path")
	}
	bpkg, err := build.Default.Import(flag.Args()[0], ".", 0)
	if err != nil {
		log.Fatal(err)
	}
	fset := token.NewFileSet()
	files := make(map[string]*ast.File)
	for _, fname := range bpkg.GoFiles {
		p, err := ioutil.ReadFile(filepath.Join(bpkg.SrcRoot, bpkg.ImportPath, fname))
		if err != nil {
			log.Fatal(err)
		}
		file, err := parser.ParseFile(fset, fname, p, parser.ParseComments)
		if err != nil {
			log.Fatal(err)
		}
		files[fname] = file
	}
	c := spew.NewDefaultConfig()
	c.DisableMethods = true
	apkg, _ := ast.NewPackage(fset, files, importer, nil)
	c.Dump(apkg)
	ast.Print(fset, apkg)
	dpkg := doc.New(apkg, bpkg.ImportPath, 0)
	c.Dump(dpkg)
}
Пример #12
0
func main() {
	// src is the input for which we want to print the AST.
	src := `
	package main

	func anon(a int, b int) {
	}

	func named(a: int, b: int) {
	}

func main() {
	named(a: 3 + 2, b: 5)
}
`

	// Create the AST by parsing src.
	fset := token.NewFileSet() // positions are relative to fset
	f, err := parser.ParseFile(fset, "", src, 0)
	if err != nil {
		panic(err)
	}

	// Print the AST.
	ast.Print(fset, f)

	fmt.Printf("%s\n", parser.RenderFile(f, fset))
}
Пример #13
0
Файл: gsp.go Проект: 8l/gsp
func main() {
	if len(os.Args) > 1 {
		args(os.Args[1])
		return
	}

	r := bufio.NewReader(os.Stdin)

	for {
		fmt.Print(">> ")
		line, _, _ := r.ReadLine()
		p := parser.ParseFromString("<REPL>", string(line)+"\n")
		fmt.Println(p)

		// a := generator.GenerateAST(p)
		a := generator.EvalExprs(p)
		fset := token.NewFileSet()

		ast.Print(fset, a)

		var buf bytes.Buffer
		printer.Fprint(&buf, fset, a)
		fmt.Printf("%s\n", buf.String())
	}
}
Пример #14
0
func ProcessFunc(cur *Cursor, node *ast.FuncDecl) Candidates {

	ast.Print(cur.FSet, GetOutNode(cur.Node, cur.Offset))

	if cur.LeftWords != nil && len(cur.LeftWords) > 0 {
		cands := Candidates{}
		lastw := strings.ToLower(cur.GetLastWord())
		pkg := cur.Asist.GetPackage(cur.PackagePath)
		if lastw == "func" && cur.LastLetter == ' ' { //begin of func
			file := pkg.GetFile(cur.File.GetPath())
			if file == nil {
				return nil
			}
			for _, t := range file.Types {
				fmt.Println(t.Name, t.Type)
				tmp := "(" + strings.ToLower(string(t.Name[0])) + " " + t.Name + ")"
				cand := Candidate{Name: tmp}
				if t.Type == "struct" {
					cand.Perc = 50
				}
				cands = append(cands, cand)
			}
			return cands
		}
	}
	return nil
}
Пример #15
0
// compiles source consisting of a number of statements. E.g.:
// 	src = "a = 1; b = sin(x)"
// 	code, err := world.Compile(src)
// 	code.Eval()
func (w *World) Compile(src string) (code *BlockStmt, e error) {
	// parse
	exprSrc := "func(){\n" + src + "\n}" // wrap in func to turn into expression
	tree, err := parser.ParseExpr(exprSrc)
	if err != nil {
		return nil, fmt.Errorf("script line %v: ", err)
	}

	// catch compile errors and decode line number
	if !Debug {
		defer func() {
			err := recover()
			if err == nil {
				return
			}
			if compErr, ok := err.(*compileErr); ok {
				code = nil
				e = fmt.Errorf("script %v: %v", pos2line(compErr.pos, exprSrc), compErr.msg)
			} else {
				panic(err)
			}
		}()
	}

	// compile
	stmts := tree.(*ast.FuncLit).Body.List // strip func again
	if Debug {
		ast.Print(nil, stmts)
	}
	block := new(BlockStmt)
	for _, s := range stmts {
		block.append(w.compile(s), s)
	}
	return block, nil
}
Пример #16
0
// Compiles an expression, which can then be evaluated. E.g.:
// 	expr, err := world.CompileExpr("1+1")
// 	expr.Eval()   // returns 2
func (w *World) CompileExpr(src string) (code Expr, e error) {
	// parse
	tree, err := parser.ParseExpr(src)
	if err != nil {
		return nil, fmt.Errorf(`parse "%s": %v`, src, err)
	}
	if Debug {
		ast.Print(nil, tree)
	}

	// catch compile errors
	if !Debug {
		defer func() {
			err := recover()
			if err == nil {
				return
			}
			if er, ok := err.(*compileErr); ok {
				code = nil
				e = fmt.Errorf(`parse "%s": %v`, src, er)
			} else {
				panic(err)
			}
		}()
	}
	return w.compile(tree), nil
}
Пример #17
0
func main() {
	// src is the input for which we want to print the AST.
	src := `
package main

func hello(a, b Any, rest ...Any) Any {
	return a
}

func main() {
	f := 10
	f.(func(int)Any)
}
`

	// Create the AST by parsing src.
	fset := token.NewFileSet() // positions are relative to fset
	f, err := parser.ParseFile(fset, "", src, 0)
	if err != nil {
		panic(err)
	}

	// (f.Decls[0].(*ast.GenDecl)).Specs[0].Name.Obj = nil
	// ((f.Decls[0].(*ast.GenDecl)).Specs[0].(*ast.TypeSpec).Name.Obj) = nil
	// f.Imports = nil
	ast.Print(fset, f)

	// Print the AST.
	var buf bytes.Buffer
	printer.Fprint(&buf, fset, f)
	fmt.Println(buf.String())

}
Пример #18
0
// AstCommand implements the debugger command: ast
//
// ast
//
// Prints AST for current function.
func AstCommand(args []string) {
	var syntax ast.Node
	var err error
	fr := gub.CurFrame()
	fn := fr.Fn()
	if len(args) > 1 {
		name := args[1]
		fn, err = gub.FuncLookup(name)
		if err != nil {
			gub.Errmsg(err.Error())
			return
		} else if fn == nil {
			gub.Errmsg("function '%s' not found", name)
			return
		} else {
			syntax = fn.Syntax()
		}
	} else {
		syntax = fn.Syntax()
		switch s := (*gub.Instr).(type) {
		case *ssa2.Trace:
			syntax = s.Syntax()
		}
	}
	if syntax != nil {
		ast.Print(fn.Prog.Fset, syntax)
		fmt.Println("")
	} else {
		gub.Msg("Sorry, we don't have an AST for this")
	}
}
Пример #19
0
// Parse the app directory and return a list of the controller types found.
// Returns a CompileError if the parsing fails.
func ScanControllers(path string) (specs []*ControllerSpec, compileError *rev.Error) {
	// Parse files within the path.
	var pkgs map[string]*ast.Package
	fset := token.NewFileSet()
	pkgs, err := parser.ParseDir(fset, path, func(f os.FileInfo) bool {
		return !f.IsDir() && !strings.HasPrefix(f.Name(), ".")
	}, 0)
	if err != nil {
		if errList, ok := err.(scanner.ErrorList); ok {
			var pos token.Position = errList[0].Pos
			return nil, &rev.Error{
				SourceType:  ".go source",
				Title:       "Go Compilation Error",
				Path:        pos.Filename,
				Description: errList[0].Msg,
				Line:        pos.Line,
				Column:      pos.Column,
				SourceLines: rev.MustReadLines(pos.Filename),
			}
		}
		ast.Print(nil, err)
		log.Fatalf("Failed to parse dir: %s", err)
	}

	// For each package... (often only "controllers")
	for _, pkg := range pkgs {
		var structSpecs []*ControllerSpec
		methodSpecs := make(methodMap)

		// For each source file in the package...
		for _, file := range pkg.Files {

			// Imports maps the package key to the full import path.
			// e.g. import "sample/app/models" => "models": "sample/app/models"
			imports := map[string]string{}

			// For each declaration in the source file...
			for _, decl := range file.Decls {

				// Match and add both structs and methods
				addImports(imports, decl)
				structSpecs = appendStruct(structSpecs, pkg, decl)
				appendMethod(fset, methodSpecs, decl, pkg.Name, imports)
			}
		}

		// Filter the struct specs to just the ones that embed rev.Controller.
		structSpecs = filterControllers(structSpecs)

		// Add the method specs to them.
		for _, spec := range structSpecs {
			spec.MethodSpecs = methodSpecs[spec.StructName]
		}

		// Add the prepared ControllerSpecs to the list.
		specs = append(specs, structSpecs...)
	}
	return
}
Пример #20
0
func main() {
	fileSet := token.NewFileSet()
	astFile, err := parser.ParseFile(fileSet, os.Args[1], nil, 0)
	if err != nil {
		panic(err)
	}
	ast.Print(fileSet, astFile)
}
Пример #21
0
func main() {
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "src.go", os.Stdin, 0)
	if err != nil {
		fmt.Println(err)
	}
	ast.Print(fset, f)
}
Пример #22
0
func dump(filename string) {
	fileSet := token.NewFileSet()
	file, err := parser.ParseFile(fileSet, filename, nil, 0)
	if err != nil {
		fmt.Fprintf(os.Stderr, "parse error: %s\n", err)
		os.Exit(1)
	}
	ast.Print(fileSet, file)
}
Пример #23
0
func PrintAst(file string) error {
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, file, nil, parser.ParseComments)
	if err != nil {
		return err

	}
	ast.Print(fset, f)
	return nil
}
Пример #24
0
// parse may be called concurrently
func parse(filename string, src interface{}) (*ast.File, error) {
	if *verbose {
		fmt.Println(filename)
	}
	file, err := parser.ParseFile(fset, filename, src, parserMode) // ok to access fset concurrently
	if *printAST {
		ast.Print(fset, file)
	}
	return file, err
}
Пример #25
0
func compileGomezToLLVM(filename string) (string, error) {
	fset := token.NewFileSet()
	tree, err := parser.ParseFile(fset, filename, nil, 0)
	if err != nil {
		return "", err
	}

	ast.Print(fset, tree)
	return libgomez.GenerateLLVM(fset, tree)
}
Пример #26
0
// PrintTree prints the ast of the source in filename.
func PrintTree(filename string) error {
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, filename, nil, 0)
	if err != nil {
		return err
	}

	ast.Print(fset, f)
	return nil
}
Пример #27
0
func TestRewrite(t *testing.T) {
	fset := token.NewFileSet()
	fl, err := os.Open("dummy/models.go")
	if err != nil {
		t.Error(err)
	}
	defer fl.Close()
	f, err := parser.ParseFile(fset, "dummy/models.go", fl, parser.ParseComments)
	ast.Print(fset, f)
	t.Errorf("%+v, %+v", f, err)
}
Пример #28
0
func InfoNodeSubcmd(args []string) {
	fr := gub.CurFrame()
	scope := fr.Scope()
	if scope == nil {
		gub.Errmsg("No scope recorded here")
		return
	}
	if scope.Node() != nil {
		ast.Print(fr.Fset(), scope.Node())
	}
}
Пример #29
0
func DumpAst(output io.Writer, inputFileSpecs []string) error {
	fs := token.NewFileSet()
	for _, f := range inputFileSpecs {
		astFile, err := parser.ParseFile(fs, f, nil, parser.ParseComments)
		if err != nil {
			return err
		}
		ast.Print(fs, astFile)
	}
	return nil
}
Пример #30
0
func main() {
	var file *ast.File
	var err error

	if file, err = json2go.Json2Ast(os.Stdin); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	ast.Print(nil, file)

	printer.Fprint(os.Stdout, token.NewFileSet(), file)
}