dst

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2018 License: MIT Imports: 10 Imported by: 237

README

dst

Decorated Syntax Tree

The dst package enables manipulation of a Go syntax tree in high fidelity. Decorations (e.g. comments and newlines) remain attached to the correct nodes as the tree is modified.

See: golang issue.

How is go/ast broken?

Consider this example where we want to reverse the order of the two declarations. As you can see the comments don't remain attached to the correct nodes:

code := `package a

var a int    // foo
var b string // bar
`
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "a.go", code, parser.ParseComments)
if err != nil {
	panic(err)
}
apply := func(c *astutil.Cursor) bool {
	switch n := c.Node().(type) {
	case *ast.File:
		n.Decls = []ast.Decl{n.Decls[1], n.Decls[0]}
	}
	return true
}
f = astutil.Apply(f, apply, nil).(*ast.File)
if err := format.Node(os.Stdout, fset, f); err != nil {
	panic(err)
}

//Output:
//package a
//
//// foo
//var b string
//var a int
//
//// bar

Here's the same example using dst:

code := `package a

var a int    // foo
var b string // bar
`
f, err := decorator.Parse(code)
if err != nil {
	panic(err)
}
apply := func(c *dstutil.Cursor) bool {
	switch n := c.Node().(type) {
	case *dst.File:
		n.Decls = []dst.Decl{n.Decls[1], n.Decls[0]}
	}
	return true
}
f = dstutil.Apply(f, apply, nil).(*dst.File)
if err := decorator.Print(f); err != nil {
	panic(err)
}

//Output:
//package a
//
//var b string // bar
//var a int    // foo
Example:

This would be very difficult using the go/ast package:

code := `package main

func main() {
	var a int
	a++
	print(a)
}`
f, err := decorator.Parse(code)
if err != nil {
	panic(err)
}
apply := func(c *dstutil.Cursor) bool {
	switch n := c.Node().(type) {
	case *dst.DeclStmt:
		n.Decs.End.Replace("// foo")
	case *dst.IncDecStmt:
		n.Decs.AfterX.Add("/* bar */")
	case *dst.CallExpr:
		n.Decs.AfterLparen.Add("\n")
		n.Decs.AfterArgs.Add("\n")
	}
	return true
}
f = dstutil.Apply(f, apply, nil).(*dst.File)
if err := decorator.Print(f); err != nil {
	panic(err)
}

//Output:
//package main
//
//func main() {
//	var a int // foo
//	a /* bar */ ++
//	print(
//		a,
//	)
//}
Status

This is an experimental package under development, so the API and behaviour is expected to change frequently. However I'm now inviting people to use it and give feedback.

Chat?

Feel free to create an issue or chat in the #dst Gophers Slack channel.

Documentation

Overview

package dst declares the types used to represent syntax trees for Go packages.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Fprint

func Fprint(w io.Writer, x interface{}, f FieldFilter) error

Fprint prints the (sub-)tree starting at AST node x to w. If fset != nil, position information is interpreted relative to that file set. Otherwise positions are printed as integer values (file set specific offsets).

A non-nil FieldFilter f may be provided to control the output: struct fields for which f(fieldname, fieldvalue) is true are printed; all others are filtered from the output. Unexported struct fields are never printed.

func Inspect

func Inspect(node Node, f func(Node) bool)

Inspect traverses an AST in depth-first order: It starts by calling f(node); node must not be nil. If f returns true, Inspect invokes f recursively for each of the non-nil children of node, followed by a call of f(nil).

Example

This example demonstrates how to inspect the AST of a Go program.

package main

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
)

func main() {
	// src is the input for which we want to inspect the AST.
	src := `
package p
const c = 1.0
var X = f(3.14)*2 + c
`

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

	// Inspect the AST and print all identifiers and literals.
	ast.Inspect(f, func(n ast.Node) bool {
		var s string
		switch x := n.(type) {
		case *ast.BasicLit:
			s = x.Value
		case *ast.Ident:
			s = x.Name
		}
		if s != "" {
			fmt.Printf("%s:\t%s\n", fset.Position(n.Pos()), s)
		}
		return true
	})

}
Output:

src.go:2:9:	p
src.go:3:7:	c
src.go:3:11:	1.0
src.go:4:5:	X
src.go:4:9:	f
src.go:4:11:	3.14
src.go:4:17:	2
src.go:4:21:	c

func IsExported

func IsExported(name string) bool

IsExported reports whether name is an exported Go symbol (that is, whether it begins with an upper-case letter).

func NotNilFilter

func NotNilFilter(_ string, v reflect.Value) bool

NotNilFilter returns true for field values that are not nil; it returns false otherwise.

func Print

func Print(x interface{}) error

Print prints x to standard output, skipping nil fields. Print(fset, x) is the same as Fprint(os.Stdout, fset, x, NotNilFilter).

Example

This example shows what an AST looks like when printed for debugging.

package main

import (
	"go/ast"
	"go/parser"
	"go/token"
)

func main() {
	// src is the input for which we want to print the AST.
	src := `
package main
func main() {
	println("Hello, World!")
}
`

	// 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)

}
Output:

     0  *ast.File {
     1  .  Package: 2:1
     2  .  Name: *ast.Ident {
     3  .  .  NamePos: 2:9
     4  .  .  Name: "main"
     5  .  }
     6  .  Decls: []ast.Decl (len = 1) {
     7  .  .  0: *ast.FuncDecl {
     8  .  .  .  Name: *ast.Ident {
     9  .  .  .  .  NamePos: 3:6
    10  .  .  .  .  Name: "main"
    11  .  .  .  .  Obj: *ast.Object {
    12  .  .  .  .  .  Kind: func
    13  .  .  .  .  .  Name: "main"
    14  .  .  .  .  .  Decl: *(obj @ 7)
    15  .  .  .  .  }
    16  .  .  .  }
    17  .  .  .  Type: *ast.FuncType {
    18  .  .  .  .  Func: 3:1
    19  .  .  .  .  Params: *ast.FieldList {
    20  .  .  .  .  .  Opening: 3:10
    21  .  .  .  .  .  Closing: 3:11
    22  .  .  .  .  }
    23  .  .  .  }
    24  .  .  .  Body: *ast.BlockStmt {
    25  .  .  .  .  Lbrace: 3:13
    26  .  .  .  .  List: []ast.Stmt (len = 1) {
    27  .  .  .  .  .  0: *ast.ExprStmt {
    28  .  .  .  .  .  .  X: *ast.CallExpr {
    29  .  .  .  .  .  .  .  Fun: *ast.Ident {
    30  .  .  .  .  .  .  .  .  NamePos: 4:2
    31  .  .  .  .  .  .  .  .  Name: "println"
    32  .  .  .  .  .  .  .  }
    33  .  .  .  .  .  .  .  Lparen: 4:9
    34  .  .  .  .  .  .  .  Args: []ast.Expr (len = 1) {
    35  .  .  .  .  .  .  .  .  0: *ast.BasicLit {
    36  .  .  .  .  .  .  .  .  .  ValuePos: 4:10
    37  .  .  .  .  .  .  .  .  .  Kind: STRING
    38  .  .  .  .  .  .  .  .  .  Value: "\"Hello, World!\""
    39  .  .  .  .  .  .  .  .  }
    40  .  .  .  .  .  .  .  }
    41  .  .  .  .  .  .  .  Ellipsis: -
    42  .  .  .  .  .  .  .  Rparen: 4:25
    43  .  .  .  .  .  .  }
    44  .  .  .  .  .  }
    45  .  .  .  .  }
    46  .  .  .  .  Rbrace: 5:1
    47  .  .  .  }
    48  .  .  }
    49  .  }
    50  .  Scope: *ast.Scope {
    51  .  .  Objects: map[string]*ast.Object (len = 1) {
    52  .  .  .  "main": *(obj @ 11)
    53  .  .  }
    54  .  }
    55  .  Unresolved: []*ast.Ident (len = 1) {
    56  .  .  0: *(obj @ 29)
    57  .  }
    58  }

func Walk

func Walk(v Visitor, node Node)

Walk traverses an AST in depth-first order: It starts by calling v.Visit(node); node must not be nil. If the visitor w returned by v.Visit(node) is not nil, Walk is invoked recursively with visitor w for each of the non-nil children of node, followed by a call of w.Visit(nil).

Types

type ArrayType

type ArrayType struct {
	Len  Expr // Ellipsis node for [...]T array types, nil for slice types
	Elt  Expr // element type
	Decs ArrayTypeDecorations
}

An ArrayType node represents an array or slice type.

type ArrayTypeDecorations

type ArrayTypeDecorations struct {
	Start       Decorations
	AfterLbrack Decorations
	AfterLen    Decorations
	End         Decorations
}

ArrayTypeDecorations holds decorations for ArrayType:

type R /*Start*/ [ /*AfterLbrack*/ 1] /*AfterLen*/ int /*End*/

type AssignStmt

type AssignStmt struct {
	Lhs  []Expr
	Tok  token.Token // assignment token, DEFINE
	Rhs  []Expr
	Decs AssignStmtDecorations
}

An AssignStmt node represents an assignment or a short variable declaration.

type AssignStmtDecorations

type AssignStmtDecorations struct {
	Start    Decorations
	AfterLhs Decorations
	AfterTok Decorations
	End      Decorations
}

AssignStmtDecorations holds decorations for AssignStmt:

/*Start*/
i /*AfterLhs*/ = /*AfterTok*/ 1 /*End*/

type BadDecl

type BadDecl struct {
	Length int // position range of bad declaration
	Decs   BadDeclDecorations
}

A BadDecl node is a placeholder for declarations containing syntax errors for which no correct declaration nodes can be created.

type BadDeclDecorations

type BadDeclDecorations struct{}

BadDeclDecorations holds decorations for BadDecl:

type BadExpr

type BadExpr struct {
	Length int // position range of bad expression
	Decs   BadExprDecorations
}

A BadExpr node is a placeholder for expressions containing syntax errors for which no correct expression nodes can be created.

type BadExprDecorations

type BadExprDecorations struct{}

BadExprDecorations holds decorations for BadExpr:

type BadStmt

type BadStmt struct {
	Length int // position range of bad statement
	Decs   BadStmtDecorations
}

A BadStmt node is a placeholder for statements containing syntax errors for which no correct statement nodes can be created.

type BadStmtDecorations

type BadStmtDecorations struct{}

BadStmtDecorations holds decorations for BadStmt:

type BasicLit

type BasicLit struct {
	Kind  token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING
	Value string      // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f', "foo" or `\m\n\o`
	Decs  BasicLitDecorations
}

A BasicLit node represents a literal of basic type.

type BasicLitDecorations

type BasicLitDecorations struct {
	Start Decorations
	End   Decorations
}

BasicLitDecorations holds decorations for BasicLit:

type BinaryExpr

type BinaryExpr struct {
	X    Expr        // left operand
	Op   token.Token // operator
	Y    Expr        // right operand
	Decs BinaryExprDecorations
}

A BinaryExpr node represents a binary expression.

type BinaryExprDecorations

type BinaryExprDecorations struct {
	Start   Decorations
	AfterX  Decorations
	AfterOp Decorations
	End     Decorations
}

BinaryExprDecorations holds decorations for BinaryExpr:

var P = /*Start*/ 1 /*AfterX*/ & /*AfterOp*/ 2 /*End*/

type BlockStmt

type BlockStmt struct {
	List []Stmt
	Decs BlockStmtDecorations
}

A BlockStmt node represents a braced statement list.

type BlockStmtDecorations

type BlockStmtDecorations struct {
	Start       Decorations
	AfterLbrace Decorations
	End         Decorations
}

BlockStmtDecorations holds decorations for BlockStmt:

if true /*Start*/ { /*AfterLbrace*/
	i++
} /*End*/

func() /*Start*/ { /*AfterLbrace*/ i++ } /*End*/ ()

type BranchStmt

type BranchStmt struct {
	Tok   token.Token // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH)
	Label *Ident      // label name; or nil
	Decs  BranchStmtDecorations
}

A BranchStmt node represents a break, continue, goto, or fallthrough statement.

type BranchStmtDecorations

type BranchStmtDecorations struct {
	Start    Decorations
	AfterTok Decorations
	End      Decorations
}

BranchStmtDecorations holds decorations for BranchStmt:

/*Start*/
goto /*AfterTok*/ A /*End*/

type CallExpr

type CallExpr struct {
	Fun      Expr   // function expression
	Args     []Expr // function arguments; or nil
	Ellipsis bool
	Decs     CallExprDecorations
}

A CallExpr node represents an expression followed by an argument list.

type CallExprDecorations

type CallExprDecorations struct {
	Start         Decorations
	AfterFun      Decorations
	AfterLparen   Decorations
	AfterArgs     Decorations
	AfterEllipsis Decorations
	End           Decorations
}

CallExprDecorations holds decorations for CallExpr:

var L = /*Start*/ C /*AfterFun*/ ( /*AfterLparen*/ 0, []int{} /*AfterArgs*/ ... /*AfterEllipsis*/) /*End*/

type CaseClause

type CaseClause struct {
	List []Expr // list of expressions or types; nil means default case
	Body []Stmt // statement list; or nil
	Decs CaseClauseDecorations
}

A CaseClause represents a case of an expression or type switch statement.

type CaseClauseDecorations

type CaseClauseDecorations struct {
	Start      Decorations
	AfterCase  Decorations
	AfterList  Decorations
	AfterColon Decorations
}

CaseClauseDecorations holds decorations for CaseClause:

switch i {
/*Start*/ case /*AfterCase*/ 1 /*AfterList*/ : /*AfterColon*/
	i++
}

type ChanDir

type ChanDir int

The direction of a channel type is indicated by a bit mask including one or both of the following constants.

const (
	SEND ChanDir = 1 << iota
	RECV
)

type ChanType

type ChanType struct {
	Dir   ChanDir // channel direction
	Value Expr    // value type
	Decs  ChanTypeDecorations
}

A ChanType node represents a channel type.

type ChanTypeDecorations

type ChanTypeDecorations struct {
	Start      Decorations
	AfterBegin Decorations
	AfterArrow Decorations
	End        Decorations
}

ChanTypeDecorations holds decorations for ChanType:

type W /*Start*/ chan /*AfterBegin*/ int /*End*/

type X /*Start*/ <-chan /*AfterBegin*/ int /*End*/

type Y /*Start*/ chan /*AfterBegin*/ <- /*AfterArrow*/ int /*End*/

type CommClause

type CommClause struct {
	Comm Stmt   // send or receive statement; nil means default case
	Body []Stmt // statement list; or nil
	Decs CommClauseDecorations
}

A CommClause node represents a case of a select statement.

type CommClauseDecorations

type CommClauseDecorations struct {
	Start      Decorations
	AfterCase  Decorations
	AfterComm  Decorations
	AfterColon Decorations
}

CommClauseDecorations holds decorations for CommClause:

select {
/*Start*/ case /*AfterCase*/ a := <-c /*AfterComm*/ : /*AfterColon*/
	print(a)
}

type CompositeLit

type CompositeLit struct {
	Type       Expr   // literal type; or nil
	Elts       []Expr // list of composite elements; or nil
	Incomplete bool   // true if (source) expressions are missing in the Elts list
	Decs       CompositeLitDecorations
}

A CompositeLit node represents a composite literal.

type CompositeLitDecorations

type CompositeLitDecorations struct {
	Start       Decorations
	AfterType   Decorations
	AfterLbrace Decorations
	End         Decorations
}

CompositeLitDecorations holds decorations for CompositeLit:

var D = /*Start*/ A /*AfterType*/ { /*AfterLbrace*/ A: 0} /*End*/

type Decl

type Decl interface {
	Node
	// contains filtered or unexported methods
}

All declaration nodes implement the Decl interface.

type DeclStmt

type DeclStmt struct {
	Decl Decl // *GenDecl with CONST, TYPE, or VAR token
	Decs DeclStmtDecorations
}

A DeclStmt node represents a declaration in a statement list.

type DeclStmtDecorations

type DeclStmtDecorations struct {
	Start Decorations
	End   Decorations
}

DeclStmtDecorations holds decorations for DeclStmt:

type DecorationDecl

type DecorationDecl struct {
	Decs DecorationDeclDecorations
}

DecorationDecl is for comments in a declaration list that are separated from other declarations by a blank line.

type DecorationDeclDecorations

type DecorationDeclDecorations struct {
	Start Decorations
}

type DecorationStmt

type DecorationStmt struct {
	Decs DecorationStmtDecorations
}

DecorationStmt is for comments in a statement list that are separated from other statements by a blank line.

type DecorationStmtDecorations

type DecorationStmtDecorations struct {
	Start Decorations
}

type Decorations

type Decorations []string
Example
package main

import (
	"github.com/dave/dst"
	"github.com/dave/dst/decorator"
	"github.com/dave/dst/dstutil"
)

func main() {
	code := `package main

	func main() {
		var a int
		a++
		print(a)
	}`
	f, err := decorator.Parse(code)
	if err != nil {
		panic(err)
	}
	apply := func(c *dstutil.Cursor) bool {
		switch n := c.Node().(type) {
		case *dst.DeclStmt:
			n.Decs.End.Replace("// foo")
		case *dst.IncDecStmt:
			n.Decs.AfterX.Add("/* bar */")
		case *dst.CallExpr:
			n.Decs.AfterLparen.Add("\n")
			n.Decs.AfterArgs.Add("\n")
		}
		return true
	}
	f = dstutil.Apply(f, apply, nil).(*dst.File)
	if err := decorator.Print(f); err != nil {
		panic(err)
	}

}
Output:

package main

func main() {
	var a int // foo
	a /* bar */ ++
	print(
		a,
	)
}

func (*Decorations) Add

func (d *Decorations) Add(decs ...string)

func (*Decorations) Clear

func (d *Decorations) Clear()

func (*Decorations) Replace

func (d *Decorations) Replace(decs ...string)

type DeferStmt

type DeferStmt struct {
	Call *CallExpr
	Decs DeferStmtDecorations
}

A DeferStmt node represents a defer statement.

type DeferStmtDecorations

type DeferStmtDecorations struct {
	Start      Decorations
	AfterDefer Decorations
	End        Decorations
}

DeferStmtDecorations holds decorations for DeferStmt:

/*Start*/
defer /*AfterDefer*/ func() {}() /*End*/

type Ellipsis

type Ellipsis struct {
	Elt  Expr // ellipsis element type (parameter lists only); or nil
	Decs EllipsisDecorations
}

An Ellipsis node stands for the "..." type in a parameter list or the "..." length in an array type.

type EllipsisDecorations

type EllipsisDecorations struct {
	Start         Decorations
	AfterEllipsis Decorations
	End           Decorations
}

EllipsisDecorations holds decorations for Ellipsis:

func B(a /*Start*/ ... /*AfterEllipsis*/ int /*End*/) {}

type EmptyStmt

type EmptyStmt struct {
	Implicit bool // if set, ";" was omitted in the source
	Decs     EmptyStmtDecorations
}

An EmptyStmt node represents an empty statement. The "position" of the empty statement is the position of the immediately following (explicit or implicit) semicolon.

type EmptyStmtDecorations

type EmptyStmtDecorations struct{}

EmptyStmtDecorations holds decorations for EmptyStmt:

type Expr

type Expr interface {
	Node
	// contains filtered or unexported methods
}

All expression nodes implement the Expr interface.

type ExprStmt

type ExprStmt struct {
	X    Expr // expression
	Decs ExprStmtDecorations
}

An ExprStmt node represents a (stand-alone) expression in a statement list.

type ExprStmtDecorations

type ExprStmtDecorations struct {
	Start Decorations
	End   Decorations
}

ExprStmtDecorations holds decorations for ExprStmt:

type Field

type Field struct {
	Names []*Ident  // field/method/parameter names; or nil
	Type  Expr      // field/method/parameter type
	Tag   *BasicLit // field tag; or nil
	Decs  FieldDecorations
}

A Field represents a Field declaration list in a struct type, a method list in an interface type, or a parameter/result declaration in a signature. Field.Names is nil for unnamed parameters (parameter lists which only contain types) and embedded struct fields. In the latter case, the field name is the type name.

type FieldDecorations

type FieldDecorations struct {
	Start      Decorations
	AfterNames Decorations
	AfterType  Decorations
	End        Decorations
}

FieldDecorations holds decorations for Field:

type A struct {
	/*Start*/ A /*AfterNames*/ int /*AfterType*/ `a:"a"` /*End*/
}

type FieldFilter

type FieldFilter func(name string, value reflect.Value) bool

A FieldFilter may be provided to Fprint to control the output.

type FieldList

type FieldList struct {
	Opening bool
	List    []*Field // field list; or nil
	Closing bool
	Decs    FieldListDecorations
}

A FieldList represents a list of Fields, enclosed by parentheses or braces.

func (*FieldList) NumFields

func (f *FieldList) NumFields() int

NumFields returns the number of parameters or struct fields represented by a FieldList.

type FieldListDecorations

type FieldListDecorations struct {
	Start        Decorations
	AfterOpening Decorations
	End          Decorations
}

FieldListDecorations holds decorations for FieldList:

type A1 struct /*Start*/ { /*AfterOpening*/
	a, b int
	c    string
} /*End*/

type File

type File struct {
	Name       *Ident        // package name
	Decls      []Decl        // top-level declarations; or nil
	Scope      *Scope        // package scope (this file only)
	Imports    []*ImportSpec // imports in this file
	Unresolved []*Ident      // unresolved identifiers in this file
	Decs       FileDecorations
}

A File node represents a Go source file.

The Comments list contains all comments in the source file in order of appearance, including the comments that are pointed to from other nodes via Doc and Comment fields.

For correct printing of source code containing comments (using packages go/format and go/printer), special care must be taken to update comments when a File's syntax tree is modified: For printing, comments are interspersed between tokens based on their position. If syntax tree nodes are removed or moved, relevant comments in their vicinity must also be removed (from the File.Comments list) or moved accordingly (by updating their positions). A CommentMap may be used to facilitate some of these operations.

Whether and how a comment is associated with a node depends on the interpretation of the syntax tree by the manipulating program: Except for Doc and Comment comments directly associated with nodes, the remaining comments are "free-floating" (see also issues #18593, #20744).

type FileDecorations

type FileDecorations struct {
	Start        Decorations
	AfterPackage Decorations
	AfterName    Decorations
}

FileDecorations holds decorations for File:

/*Start*/ package /*AfterPackage*/ postests /*AfterName*/

type ForStmt

type ForStmt struct {
	Init Stmt // initialization statement; or nil
	Cond Expr // condition; or nil
	Post Stmt // post iteration statement; or nil
	Body *BlockStmt
	Decs ForStmtDecorations
}

A ForStmt represents a for statement.

type ForStmtDecorations

type ForStmtDecorations struct {
	Start     Decorations
	AfterFor  Decorations
	AfterInit Decorations
	AfterCond Decorations
	AfterPost Decorations
	End       Decorations
}

ForStmtDecorations holds decorations for ForStmt:

/*Start*/
for /*AfterFor*/ {
	i++
} /*End*/

/*Start*/
for /*AfterFor*/ i < 1 /*AfterCond*/ {
	i++
} /*End*/

/*Start*/
for /*AfterFor*/ i = 0; /*AfterInit*/ i < 10; /*AfterCond*/ i++ /*AfterPost*/ {
	i++
} /*End*/

type FuncDecl

type FuncDecl struct {
	Recv *FieldList // receiver (methods); or nil (functions)
	Name *Ident     // function/method name
	Type *FuncType  // function signature: parameters, results, and position of "func" keyword
	Body *BlockStmt // function body; or nil for external (non-Go) function
	Decs FuncDeclDecorations
}

A FuncDecl node represents a function declaration.

type FuncDeclDecorations

type FuncDeclDecorations struct {
	Start        Decorations
	AfterFunc    Decorations
	AfterRecv    Decorations
	AfterName    Decorations
	AfterParams  Decorations
	AfterResults Decorations
	End          Decorations
}

FuncDeclDecorations holds decorations for FuncDecl:

/*Start*/
func /*AfterFunc*/ d /*AfterName*/ (d, e int) /*AfterParams*/ {
	return
} /*End*/

/*Start*/
func /*AfterFunc*/ (a *A) /*AfterRecv*/ e /*AfterName*/ (d, e int) /*AfterParams*/ {
	return
} /*End*/

/*Start*/
func /*AfterFunc*/ (a *A) /*AfterRecv*/ f /*AfterName*/ (d, e int) /*AfterParams*/ (f, g int) /*AfterResults*/ {
	return
}

type FuncLit

type FuncLit struct {
	Type *FuncType  // function type
	Body *BlockStmt // function body
	Decs FuncLitDecorations
}

A FuncLit node represents a function literal.

type FuncLitDecorations

type FuncLitDecorations struct {
	Start     Decorations
	AfterType Decorations
	End       Decorations
}

FuncLitDecorations holds decorations for FuncLit:

var C = /*Start*/ func(a int, b ...int) (c int) /*AfterType*/ { return 0 } /*End*/

type FuncType

type FuncType struct {
	Func    bool
	Params  *FieldList // (incoming) parameters; non-nil
	Results *FieldList // (outgoing) results; or nil
	Decs    FuncTypeDecorations
}

A FuncType node represents a function type.

type FuncTypeDecorations

type FuncTypeDecorations struct {
	Start       Decorations
	AfterFunc   Decorations
	AfterParams Decorations
	End         Decorations
}

FuncTypeDecorations holds decorations for FuncType:

type T /*Start*/ func /*AfterFunc*/ (a int) /*AfterParams*/ (b int) /*End*/

type GenDecl

type GenDecl struct {
	Tok    token.Token // IMPORT, CONST, TYPE, VAR
	Lparen bool
	Specs  []Spec
	Rparen bool
	Decs   GenDeclDecorations
}

A GenDecl node (generic declaration node) represents an import, constant, type or variable declaration. A valid Lparen position (Lparen.IsValid()) indicates a parenthesized declaration.

Relationship between Tok value and Specs element type:

token.IMPORT  *ImportSpec
token.CONST   *ValueSpec
token.TYPE    *TypeSpec
token.VAR     *ValueSpec

type GenDeclDecorations

type GenDeclDecorations struct {
	Start       Decorations
	AfterTok    Decorations
	AfterLparen Decorations
	End         Decorations
}

GenDeclDecorations holds decorations for GenDecl:

/*Start*/
const /*AfterTok*/ ( /*AfterLparen*/
	a, b = 1, 2
	c    = 3
) /*End*/

/*Start*/
const /*AfterTok*/ d = 1 /*End*/

}

type GoStmt

type GoStmt struct {
	Call *CallExpr
	Decs GoStmtDecorations
}

A GoStmt node represents a go statement.

type GoStmtDecorations

type GoStmtDecorations struct {
	Start   Decorations
	AfterGo Decorations
	End     Decorations
}

GoStmtDecorations holds decorations for GoStmt:

/*Start*/
go /*AfterGo*/ func() {}() /*End*/

type Ident

type Ident struct {
	Name string  // identifier name
	Obj  *Object // denoted object; or nil
	Decs IdentDecorations
}

An Ident node represents an identifier.

func NewIdent

func NewIdent(name string) *Ident

NewIdent creates a new Ident without position. Useful for ASTs generated by code other than the Go parser.

func (*Ident) IsExported

func (id *Ident) IsExported() bool

IsExported reports whether id is an exported Go symbol (that is, whether it begins with an uppercase letter).

func (*Ident) String

func (id *Ident) String() string

type IdentDecorations

type IdentDecorations struct {
	Start Decorations
	End   Decorations
}

IdentDecorations holds decorations for Ident:

type IfStmt

type IfStmt struct {
	Init Stmt // initialization statement; or nil
	Cond Expr // condition
	Body *BlockStmt
	Else Stmt // else branch; or nil
	Decs IfStmtDecorations
}

An IfStmt node represents an if statement.

type IfStmtDecorations

type IfStmtDecorations struct {
	Start     Decorations
	AfterIf   Decorations
	AfterInit Decorations
	AfterCond Decorations
	AfterElse Decorations
	End       Decorations
}

IfStmtDecorations holds decorations for IfStmt:

/*Start*/
if /*AfterIf*/ a := b; /*AfterInit*/ a /*AfterCond*/ {
	i++
} else /*AfterElse*/ {
	i++
} /*End*/

type ImportSpec

type ImportSpec struct {
	Name *Ident    // local package name (including "."); or nil
	Path *BasicLit // import path
	Decs ImportSpecDecorations
}

An ImportSpec node represents a single package import.

type ImportSpecDecorations

type ImportSpecDecorations struct {
	Start     Decorations
	AfterName Decorations
	End       Decorations
}

ImportSpecDecorations holds decorations for ImportSpec:

import (
	/*Start*/ fmt /*AfterName*/ "fmt" /*End*/
)

type Importer

type Importer func(imports map[string]*Object, path string) (pkg *Object, err error)

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 *Object (pkg), record pkg in the imports map, and then return pkg.

type IncDecStmt

type IncDecStmt struct {
	X    Expr
	Tok  token.Token // INC or DEC
	Decs IncDecStmtDecorations
}

An IncDecStmt node represents an increment or decrement statement.

type IncDecStmtDecorations

type IncDecStmtDecorations struct {
	Start  Decorations
	AfterX Decorations
	End    Decorations
}

IncDecStmtDecorations holds decorations for IncDecStmt:

/*Start*/
i /*AfterX*/ ++ /*End*/

type IndexExpr

type IndexExpr struct {
	X     Expr // expression
	Index Expr // index expression
	Decs  IndexExprDecorations
}

An IndexExpr node represents an expression followed by an index.

type IndexExprDecorations

type IndexExprDecorations struct {
	Start       Decorations
	AfterX      Decorations
	AfterLbrack Decorations
	AfterIndex  Decorations
	End         Decorations
}

IndexExprDecorations holds decorations for IndexExpr:

var G = /*Start*/ []int{0} /*AfterX*/ [ /*AfterLbrack*/ 0 /*AfterIndex*/] /*End*/

type InterfaceType

type InterfaceType struct {
	Methods    *FieldList // list of methods
	Incomplete bool       // true if (source) methods are missing in the Methods list
	Decs       InterfaceTypeDecorations
}

An InterfaceType node represents an interface type.

type InterfaceTypeDecorations

type InterfaceTypeDecorations struct {
	Start          Decorations
	AfterInterface Decorations
	End            Decorations
}

InterfaceTypeDecorations holds decorations for InterfaceType:

type U /*Start*/ interface /*AfterInterface*/ {
	A()
} /*End*/

type KeyValueExpr

type KeyValueExpr struct {
	Key   Expr
	Value Expr
	Decs  KeyValueExprDecorations
}

A KeyValueExpr node represents (key : value) pairs in composite literals.

type KeyValueExprDecorations

type KeyValueExprDecorations struct {
	Start      Decorations
	AfterKey   Decorations
	AfterColon Decorations
	End        Decorations
}

KeyValueExprDecorations holds decorations for KeyValueExpr:

var Q = map[string]string{
	/*Start*/ "a" /*AfterKey*/ : /*AfterColon*/ "a", /*End*/
}

type LabeledStmt

type LabeledStmt struct {
	Label *Ident
	Stmt  Stmt
	Decs  LabeledStmtDecorations
}

A LabeledStmt node represents a labeled statement.

type LabeledStmtDecorations

type LabeledStmtDecorations struct {
	Start      Decorations
	AfterLabel Decorations
	AfterColon Decorations
	End        Decorations
}

LabeledStmtDecorations holds decorations for LabeledStmt:

/*Start*/
A /*AfterLabel*/ : /*AfterColon*/
	print("Stmt") /*End*/

type MapType

type MapType struct {
	Key   Expr
	Value Expr
	Decs  MapTypeDecorations
}

A MapType node represents a map type.

type MapTypeDecorations

type MapTypeDecorations struct {
	Start    Decorations
	AfterMap Decorations
	AfterKey Decorations
	End      Decorations
}

MapTypeDecorations holds decorations for MapType:

type V /*Start*/ map[ /*AfterMap*/ int] /*AfterKey*/ int /*End*/

type Node

type Node interface {
	// contains filtered or unexported methods
}

All node types implement the Node interface.

type ObjKind

type ObjKind int

ObjKind describes what an object represents.

const (
	Bad ObjKind = iota // for error handling
	Pkg                // package
	Con                // constant
	Typ                // type
	Var                // variable
	Fun                // function or method
	Lbl                // label
)

The list of possible Object kinds.

func (ObjKind) String

func (kind ObjKind) String() string

type Object

type Object struct {
	Kind ObjKind
	Name string      // declared name
	Decl interface{} // corresponding Field, XxxSpec, FuncDecl, LabeledStmt, AssignStmt, Scope; or nil
	Data interface{} // object-specific data; or nil
	Type interface{} // placeholder for type information; may be nil
}

An Object describes a named language entity such as a package, constant, type, variable, function (incl. methods), or label.

The Data fields contains object-specific data:

Kind    Data type         Data value
Pkg     *Scope            package scope
Con     int               iota for the respective declaration

func NewObj

func NewObj(kind ObjKind, name string) *Object

NewObj creates a new object of a given kind and name.

type Package

type Package struct {
	Name    string             // package name
	Scope   *Scope             // package scope across all files
	Imports map[string]*Object // map of package id -> package object
	Files   map[string]*File   // Go source files by filename
}

A Package node represents a set of source files collectively building a Go package.

func NewPackage

func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error)

NewPackage creates a new Package node from a set of File nodes. It resolves unresolved identifiers across files and updates each file's Unresolved list accordingly. If a non-nil importer and universe scope are provided, they are used to resolve identifiers not declared in any of the package files. Any remaining unresolved identifiers are reported as undeclared. If the files belong to different packages, one package name is selected and files with different package names are reported and then ignored. The result is a package node and a scanner.ErrorList if there were errors.

type ParenExpr

type ParenExpr struct {
	X    Expr // parenthesized expression
	Decs ParenExprDecorations
}

A ParenExpr node represents a parenthesized expression.

type ParenExprDecorations

type ParenExprDecorations struct {
	Start       Decorations
	AfterLparen Decorations
	AfterX      Decorations
	End         Decorations
}

ParenExprDecorations holds decorations for ParenExpr:

var E = /*Start*/ ( /*AfterLparen*/ 1 + 1 /*AfterX*/) /*End*/ / 2

type RangeStmt

type RangeStmt struct {
	Key, Value Expr        // Key, Value may be nil
	Tok        token.Token // ILLEGAL if Key == nil, ASSIGN, DEFINE
	X          Expr        // value to range over
	Body       *BlockStmt
	Decs       RangeStmtDecorations
}

A RangeStmt represents a for statement with a range clause.

type RangeStmtDecorations

type RangeStmtDecorations struct {
	Start      Decorations
	AfterFor   Decorations
	AfterKey   Decorations
	AfterValue Decorations
	AfterRange Decorations
	AfterX     Decorations
	End        Decorations
}

RangeStmtDecorations holds decorations for RangeStmt:

/*Start*/
for range /*AfterRange*/ a /*AfterX*/ {
} /*End*/

/*Start*/
for /*AfterFor*/ k /*AfterKey*/ := range /*AfterRange*/ a /*AfterX*/ {
	print(k)
} /*End*/

/*Start*/
for /*AfterFor*/ k /*AfterKey*/, v /*AfterValue*/ := range /*AfterRange*/ a /*AfterX*/ {
	print(k, v)
} /*End*/

type ReturnStmt

type ReturnStmt struct {
	Results []Expr // result expressions; or nil
	Decs    ReturnStmtDecorations
}

A ReturnStmt node represents a return statement.

type ReturnStmtDecorations

type ReturnStmtDecorations struct {
	Start       Decorations
	AfterReturn Decorations
	End         Decorations
}

ReturnStmtDecorations holds decorations for ReturnStmt:

func() int {
	/*Start*/ return /*AfterReturn*/ 1 /*End*/
}()

type Scope

type Scope struct {
	Outer   *Scope
	Objects map[string]*Object
}

A Scope maintains the set of named language entities declared in the scope and a link to the immediately surrounding (outer) scope.

func NewScope

func NewScope(outer *Scope) *Scope

NewScope creates a new scope nested in the outer scope.

func (*Scope) Insert

func (s *Scope) Insert(obj *Object) (alt *Object)

Insert attempts to insert a named object obj into the scope s. If the scope already contains an object alt with the same name, Insert leaves the scope unchanged and returns alt. Otherwise it inserts obj and returns nil.

func (*Scope) Lookup

func (s *Scope) Lookup(name string) *Object

Lookup returns the object with the given name if it is found in scope s, otherwise it returns nil. Outer scopes are ignored.

func (*Scope) String

func (s *Scope) String() string

Debugging support

type SelectStmt

type SelectStmt struct {
	Body *BlockStmt // CommClauses only
	Decs SelectStmtDecorations
}

An SelectStmt node represents a select statement.

type SelectStmtDecorations

type SelectStmtDecorations struct {
	Start       Decorations
	AfterSelect Decorations
	End         Decorations
}

SelectStmtDecorations holds decorations for SelectStmt:

/*Start*/
select /*AfterSelect*/ {
} /*End*/

type SelectorExpr

type SelectorExpr struct {
	X    Expr   // expression
	Sel  *Ident // field selector
	Decs SelectorExprDecorations
}

A SelectorExpr node represents an expression followed by a selector.

type SelectorExprDecorations

type SelectorExprDecorations struct {
	Start  Decorations
	AfterX Decorations
	End    Decorations
}

SelectorExprDecorations holds decorations for SelectorExpr:

var F = /*Start*/ fmt. /*AfterX*/ Sprint /*End*/ (0)

type SendStmt

type SendStmt struct {
	Chan  Expr
	Value Expr
	Decs  SendStmtDecorations
}

A SendStmt node represents a send statement.

type SendStmtDecorations

type SendStmtDecorations struct {
	Start      Decorations
	AfterChan  Decorations
	AfterArrow Decorations
	End        Decorations
}

SendStmtDecorations holds decorations for SendStmt:

/*Start*/
c /*AfterChan*/ <- /*AfterArrow*/ 0 /*End*/

type SliceExpr

type SliceExpr struct {
	X      Expr // expression
	Low    Expr // begin of slice range; or nil
	High   Expr // end of slice range; or nil
	Max    Expr // maximum capacity of slice; or nil
	Slice3 bool // true if 3-index slice (2 colons present)
	Decs   SliceExprDecorations
}

An SliceExpr node represents an expression followed by slice indices.

type SliceExprDecorations

type SliceExprDecorations struct {
	Start       Decorations
	AfterX      Decorations
	AfterLbrack Decorations
	AfterLow    Decorations
	AfterHigh   Decorations
	AfterMax    Decorations
	End         Decorations
}

SliceExprDecorations holds decorations for SliceExpr:

var H = /*Start*/ []int{0} /*AfterX*/ [ /*AfterLbrack*/ 1: /*AfterLow*/ 2: /*AfterHigh*/ 3 /*AfterMax*/] /*End*/

var H1 = /*Start*/ []int{0} /*AfterX*/ [ /*AfterLbrack*/ 1: /*AfterLow*/ 2 /*AfterHigh*/] /*End*/

var H2 = /*Start*/ []int{0} /*AfterX*/ [: /*AfterLow*/] /*End*/

var H3 = /*Start*/ []int{0} /*AfterX*/ [ /*AfterLbrack*/ 1: /*AfterLow*/] /*End*/

var H4 = /*Start*/ []int{0} /*AfterX*/ [: /*AfterLow*/ 2 /*AfterHigh*/] /*End*/

var H5 = /*Start*/ []int{0} /*AfterX*/ [: /*AfterLow*/ 2: /*AfterHigh*/ 3 /*AfterMax*/] /*End*/

type Spec

type Spec interface {
	Node
	// contains filtered or unexported methods
}

The Spec type stands for any of *ImportSpec, *ValueSpec, and *TypeSpec.

type StarExpr

type StarExpr struct {
	X    Expr // operand
	Decs StarExprDecorations
}

A StarExpr node represents an expression of the form "*" Expression. Semantically it could be a unary "*" expression, or a pointer type.

type StarExprDecorations

type StarExprDecorations struct {
	Start     Decorations
	AfterStar Decorations
	End       Decorations
}

StarExprDecorations holds decorations for StarExpr:

var N = /*Start*/ * /*AfterStar*/ p /*End*/

type Stmt

type Stmt interface {
	Node
	// contains filtered or unexported methods
}

All statement nodes implement the Stmt interface.

type StructType

type StructType struct {
	Fields     *FieldList // list of field declarations
	Incomplete bool       // true if (source) fields are missing in the Fields list
	Decs       StructTypeDecorations
}

A StructType node represents a struct type.

type StructTypeDecorations

type StructTypeDecorations struct {
	Start       Decorations
	AfterStruct Decorations
	End         Decorations
}

StructTypeDecorations holds decorations for StructType:

type S /*Start*/ struct /*AfterStruct*/ {
	A int
} /*End*/

type SwitchStmt

type SwitchStmt struct {
	Init Stmt       // initialization statement; or nil
	Tag  Expr       // tag expression; or nil
	Body *BlockStmt // CaseClauses only
	Decs SwitchStmtDecorations
}

A SwitchStmt node represents an expression switch statement.

type SwitchStmtDecorations

type SwitchStmtDecorations struct {
	Start       Decorations
	AfterSwitch Decorations
	AfterInit   Decorations
	AfterTag    Decorations
	End         Decorations
}

SwitchStmtDecorations holds decorations for SwitchStmt:

/*Start*/
switch /*AfterSwitch*/ i /*AfterTag*/ {
} /*End*/

/*Start*/
switch /*AfterSwitch*/ a := i; /*AfterInit*/ a /*AfterTag*/ {
} /*End*/

type TypeAssertExpr

type TypeAssertExpr struct {
	X    Expr // expression
	Type Expr // asserted type; nil means type switch X.(type)
	Decs TypeAssertExprDecorations
}

A TypeAssertExpr node represents an expression followed by a type assertion.

type TypeAssertExprDecorations

type TypeAssertExprDecorations struct {
	Start       Decorations
	AfterX      Decorations
	AfterLparen Decorations
	AfterType   Decorations
	End         Decorations
}

TypeAssertExprDecorations holds decorations for TypeAssertExpr:

var J = /*Start*/ f. /*AfterX*/ ( /*AfterLparen*/ int /*AfterType*/) /*End*/

type TypeSpec

type TypeSpec struct {
	Name   *Ident // type name
	Assign bool   // position of '=', if any
	Type   Expr   // *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes
	Decs   TypeSpecDecorations
}

A TypeSpec node represents a type declaration (TypeSpec production).

type TypeSpecDecorations

type TypeSpecDecorations struct {
	Start     Decorations
	AfterName Decorations
	End       Decorations
}

TypeSpecDecorations holds decorations for TypeSpec:

type (
	/*Start*/ T1 /*AfterName*/ []int /*End*/
)

type (
	/*Start*/ T2 = /*AfterName*/ T1 /*End*/
)

type TypeSwitchStmt

type TypeSwitchStmt struct {
	Init   Stmt       // initialization statement; or nil
	Assign Stmt       // x := y.(type) or y.(type)
	Body   *BlockStmt // CaseClauses only
	Decs   TypeSwitchStmtDecorations
}

An TypeSwitchStmt node represents a type switch statement.

type TypeSwitchStmtDecorations

type TypeSwitchStmtDecorations struct {
	Start       Decorations
	AfterSwitch Decorations
	AfterInit   Decorations
	AfterAssign Decorations
	End         Decorations
}

TypeSwitchStmtDecorations holds decorations for TypeSwitchStmt:

/*Start*/
switch /*AfterSwitch*/ f.(type) /*AfterAssign*/ {
} /*End*/

/*Start*/
switch /*AfterSwitch*/ g := f.(type) /*AfterAssign*/ {
case int:
	print(g)
} /*End*/

/*Start*/
switch /*AfterSwitch*/ g := f; /*AfterInit*/ g := g.(type) /*AfterAssign*/ {
case int:
	print(g)
} /*End*/

type UnaryExpr

type UnaryExpr struct {
	Op   token.Token // operator
	X    Expr        // operand
	Decs UnaryExprDecorations
}

A UnaryExpr node represents a unary expression. Unary "*" expressions are represented via StarExpr nodes.

type UnaryExprDecorations

type UnaryExprDecorations struct {
	Start   Decorations
	AfterOp Decorations
	End     Decorations
}

UnaryExprDecorations holds decorations for UnaryExpr:

var O = /*Start*/ ^ /*AfterOp*/ 1 /*End*/

type ValueSpec

type ValueSpec struct {
	Names  []*Ident // value names (len(Names) > 0)
	Type   Expr     // value type; or nil
	Values []Expr   // initial values; or nil
	Decs   ValueSpecDecorations
}

A ValueSpec node represents a constant or variable declaration (ConstSpec or VarSpec production).

type ValueSpecDecorations

type ValueSpecDecorations struct {
	Start       Decorations
	AfterNames  Decorations
	AfterAssign Decorations
	End         Decorations
}

ValueSpecDecorations holds decorations for ValueSpec:

var (
	/*Start*/ j = /*AfterAssign*/ 1 /*End*/
)

var (
	/*Start*/ k, l = /*AfterAssign*/ 1, 2 /*End*/
)

var (
	/*Start*/ m, n /*AfterNames*/ int = /*AfterAssign*/ 1, 2 /*End*/
)

type Visitor

type Visitor interface {
	Visit(node Node) (w Visitor)
}

A Visitor's Visit method is invoked for each node encountered by Walk. If the result visitor w is not nil, Walk visits each of the children of node with the visitor w, followed by a call of w.Visit(nil).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL