structs in go.ast package

See also https://golang.org/pkg/go/ast.

Declaration

GenDecl

import, constant, type or variable declaration.

type GenDecl struct {
    Doc    *CommentGroup // associated documentation; or nil
    TokPos token.Pos     // position of Tok
    Tok    token.Token   // IMPORT, CONST, TYPE, VAR
    Lparen token.Pos     // position of '(', if any
    Specs  []Spec
    Rparen token.Pos // position of ')', if any
}
  • TokPos : file path, line, column. ex) example/example.go:3:1
  • Tok : type of def
    • token.IMPORT import "fmt"
    • token.CONST const constant string := "hoge"
    • token.VAR var variable int
    • token.TYPE type Hex int
  • Lparen, Rparen : see later.
  • Specs : for any of ImportSpec, ValueSpec, and TypeSpec

FuncDecl

function declaration using func

type FuncDecl struct {
    Doc  *CommentGroup // associated documentation; or nil
    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
}
  • Recv : field (almost struct) infomation if methods, func (*struct) funcName(){}
  • Name: func name (type ast.Ident)
  • Type : params and return fields
    • Params : ast.FieldList (position and ast.Field)
    • Results : position and ast.Field
  • Body : function body:: main process of this func. see BlockStmt later

Spec

detail spec of import, variables, type. used by GenDecl

ImportSpec

type ImportSpec struct {
        Doc     *CommentGroup // associated documentation; or nil
        Name    *Ident        // local package name (including "."); or nil
        Path    *BasicLit     // import path
        Comment *CommentGroup // line comments; or nil
        EndPos  token.Pos     // end of spec (overrides Path.Pos if nonzero)
}
  • Name : I cannot detect when this field isnt nil. Evenif use "./localpackage", never appeared:(
  • Path : BasicLit
    • ValuePos : position this package included
    • Kind : "STRING" (I think importSpec is to need this Kind: STRING)
    • Value : string. like "\"fmt\""

ValueSpec

constant or variable declaration using var, const.

type ValueSpec struct {
    Doc     *CommentGroup // associated documentation; or nil
    Names   []*Ident      // value names (len(Names) > 0)
    Type    Expr          // value type; or nil
    Values  []Expr        // initial values; or nil
    Comment *CommentGroup // line comments; or nil
}
  • Names : value names ex) var var1, var2 int -> {var1, var2}`
  • Type : ex) ast.Ident *ast.Ident { NamePos: example/example.go:3:16 Name: "int"
  • Values : Expr(BinaryExpr, BasicLit, ...)

TypeSpec

represents a Type declaration

type TypeSpec struct {
        Doc     *CommentGroup // associated documentation; or nil
        Name    *Ident        // type name
        Assign  token.Pos     // position of '=', if any; added in Go 1.9
        Type    Expr          // *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes
        Comment *CommentGroup // line comments; or nil
}
  • Assign : Type Alias. position of = if exists.
   type fuga int
    type hoge = fuga
    var x1 fuga = 2
    var x2 hoge = x1 // ok
  • Type
    • int : ast.Ident
    • func(...){...} : ast.FuncType
    • struct{...} : ast.StructType
    • type hoge = fuga : ast.Ident
    • TODO ParenExpr, SelectorExpr, StarExpr

Stmt

BlockStmt

{} block.

type BlockStmt struct {
        Lbrace token.Pos // position of "{"
        List   []Stmt
        Rbrace token.Pos // position of "}"
}

ExprStmt

expression. TODO see Expr later.

type ExprStmt struct {
        X Expr // expression
}

DeclStmt

declaration in a function as follow.

func main () {
    const a = 3
}
type DeclStmt struct {
        Decl Decl // *GenDecl with CONST, TYPE, or VAR token
}

AssignStmt

assignment or a short variable declaration using :=.

type AssignStmt struct {
    Lhs    []Expr
    TokPos token.Pos   // position of Tok
    Tok    token.Token // assignment token, DEFINE
    Rhs    []Expr
}
  • Lhs,Rhs : (left) c := 4 (right)
  • Tok : :=, other hasnt been found for me.

ReturnStmt

return statement.

type ReturnStmt struct {
    Return  token.Pos // position of "return" keyword
    Results []Expr    // result expressions; or nil
}
  • Return : position
  • Result :
    • return 1 : Expr[] -> BasicLit 1
    • return : nil

IncDecStmt

i++ or i-- statements.

type IncDecStmt struct {
        X      Expr
        TokPos token.Pos   // position of Tok
        Tok    token.Token // INC or DEC
}
  • X : target variable.
  • Tok : ++ or --

ForStmt

for statement exept for range.

When for {} (infinity), all of three Init, Cond, Post are nil.

type ForStmt struct {
        For  token.Pos // position of "for" keyword
        Init Stmt      // initialization statement; or nil
        Cond Expr      // condition; or nil
        Post Stmt      // post iteration statement; or nil
        Body *BlockStmt
}
  • For : posision
  • Init
    • for i := 0; i < 10; i++ {} : AssignStmt i := 0
  • Cond
    • for i := 0; i < 10; i++ {} : BinaryExpr i < 10
    • for coundown > 0 {} : BinaryExpr coundown > 0
  • Post
    • for i := 0; i < 10; i++ {} : IncDecStmt i++
  • Body : inner {}

RangeStmt

for range statement

type RangeStmt struct {
        For        token.Pos   // position of "for" keyword
        Key, Value Expr        // Key, Value may be nil
        TokPos     token.Pos   // position of Tok; invalid if Key == nil
        Tok        token.Token // ILLEGAL if Key == nil, ASSIGN, DEFINE
        X          Expr        // value to range over
        Body       *BlockStmt
}
  • For : position
  • Key, Value : for i, v := range arr {}
    189  .  .  .  .  Key: *ast.Ident {
       190  .  .  .  .  .  NamePos: example/stmt.go:14:6
       191  .  .  .  .  .  Name: "i"
       192  .  .  .  .  .  Obj: *ast.Object {
       193  .  .  .  .  .  .  Kind: var
       194  .  .  .  .  .  .  Name: "i"
       195  .  .  .  .  .  .  Decl: *ast.AssignStmt {
       196  .  .  .  .  .  .  .  Lhs: []ast.Expr (len = 2) {
       197  .  .  .  .  .  .  .  .  0: *(obj @ 189)
       198  .  .  .  .  .  .  .  .  1: *ast.Ident {
       199  .  .  .  .  .  .  .  .  .  NamePos: example/stmt.go:14:9
       200  .  .  .  .  .  .  .  .  .  Name: "s"
       201  .  .  .  .  .  .  .  .  .  Obj: *ast.Object {
       202  .  .  .  .  .  .  .  .  .  .  Kind: var
       203  .  .  .  .  .  .  .  .  .  .  Name: "s"
       204  .  .  .  .  .  .  .  .  .  .  Decl: *(obj @ 195)
       205  .  .  .  .  .  .  .  .  .  }
       206  .  .  .  .  .  .  .  .  }
       207  .  .  .  .  .  .  .  }
       208  .  .  .  .  .  .  .  TokPos: example/stmt.go:14:11
       209  .  .  .  .  .  .  .  Tok: :=
       210  .  .  .  .  .  .  .  Rhs: []ast.Expr (len = 1) {
       211  .  .  .  .  .  .  .  .  0: *ast.UnaryExpr {
       212  .  .  .  .  .  .  .  .  .  OpPos: example/stmt.go:14:14
       213  .  .  .  .  .  .  .  .  .  Op: range
       214  .  .  .  .  .  .  .  .  .  X: *ast.Ident {
       215  .  .  .  .  .  .  .  .  .  .  NamePos: example/stmt.go:14:20
       216  .  .  .  .  .  .  .  .  .  .  Name: "strArray"
       217  .  .  .  .  .  .  .  .  .  .  Obj: *(obj @ 131)
       218  .  .  .  .  .  .  .  .  .  }
       219  .  .  .  .  .  .  .  .  }
       220  .  .  .  .  .  .  .  }
       221  .  .  .  .  .  .  }
       222  .  .  .  .  .  }
       223  .  .  .  .  }
       224  .  .  .  .  Value: *(obj @ 198)
  • Tok : like :=
  • X : for i, v := range arr{} -> ast.Ident -> UnaryExpr arr
  • Body : inner {}

IfStmt

if, if-else statement. if-else if statement calls IfStmt recrusive.

type IfStmt struct {
        If   token.Pos // position of "if" keyword
        Init Stmt      // initialization statement; or nil
        Cond Expr      // condition
        Body *BlockStmt
        Else Stmt // else branch; or nil
}
  • If : position
  • Init : if a := true; a {} AssignStmt a := true;
  • Cond
    • if a > 3 {} -> BinaryExpr a > 3
    • if a := true; a {} -> Ident a
  • Body : inner {}
  • Else
    • if a {} else {...} -> BlockStmt {...}
    • if a {} else if {...} -> IfStmt if {...}

SwitchStmt

switch ...{} statement.

type SwitchStmt struct {
    Switch token.Pos  // position of "switch" keyword
    Init   Stmt       // initialization statement; or nil
    Tag    Expr       // tag expression; or nil
    Body   *BlockStmt // CaseClauses only
}
  • Switch : position
  • Init : switch i := 1; i{} AssignStmt i := 1
  • Tag :
    • switch i {} -> Ident i
    • switch {} -> nil
  • Body : inner {}
    • case 1,2,3: -> CaseClause when default, List is nil.
     type CaseClause struct {
            Case  token.Pos // position of "case" or "default" keyword
            List  []Expr    // list of expressions or types; nil means default case
            Colon token.Pos // position of ":"
            Body  []Stmt    // statement list; or nil
        }
- List : it's able to have multi variables like `1,2,3` 

TypeSwitchStmt

type switch statement as follow.

switch v := value.(type) {
    case nil:
    case int:
    default:
}
type TypeSwitchStmt struct {
        Switch token.Pos  // position of "switch" keyword
        Init   Stmt       // initialization statement; or nil
        Assign Stmt       // x := y.(type) or y.(type)
        Body   *BlockStmt // CaseClauses only
}
  • Switch : position
  • Init : same as SwitchStmt
  • Assign : v := value.(type) -> AssignStmt -> Ident := TypeAssertExpr
  • Body : inner {}. same as SwitchStmt

LabeledStmt

label statement like jump: and succeeding one block(statement). not case 1:.

type LabeledStmt struct {
        Label *Ident
        Colon token.Pos // position of ":"
        Stmt  Stmt
}
  • Label :
    44  .  .  .  1: *ast.LabeledStmt {
    45  .  .  .  .  Label: *ast.Ident {
    46  .  .  .  .  .  NamePos: example/label-stmt.go:7:1
    47  .  .  .  .  .  Name: "FOR_LABEL"
    48  .  .  .  .  .  Obj: *ast.Object {
    49  .  .  .  .  .  .  Kind: label
    50  .  .  .  .  .  .  Name: "FOR_LABEL"
    51  .  .  .  .  .  .  Decl: *(obj @ 44)
    52  .  .  .  .  .  }
    53  .  .  .  .  }
  • Colon : position
  • Stmt : succeeding one statement. for example as follow, Stmt -> fmt.Println("hello")
   FOR_LABEL:
        fmt.Println("hello")
        fmt.Println("world")

BranchStmt

break, continue, goto, or fallthrough statement.

type BranchStmt struct {
        TokPos token.Pos   // position of Tok
        Tok    token.Token // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH)
        Label  *Ident      // label name; or nil
}
  • TokPos : position
  • Tok
    • break [LABEL_NAME]
    • continue [LABEL_NAME]
    • goto LABEL_NAME
    • fallthrough : goto next case X: block in current switch statement
  • Label
    • break : label-assigned statement have to be ForStmt, SwitchStmt or SelectStmt
    • continue : label-assigned statement have to be ForStmt
    • fallthrough : not semantics but syntax error occured when fallthrough LABEL_NAME...why...
    • if label is nil, I guess most inner ForStmt (or Switch, Select when break) is automatically assigned.

DeferStmt

defer statement

type DeferStmt struct {
        Defer token.Pos // position of "defer" keyword
        Call  *CallExpr
}
  • Defer : position
  • Call : FunctionCall

GoStmt

go functionName() statement.

type GoStmt struct {
        Go   token.Pos // position of "go" keyword
        Call *CallExpr
}
  • Go : position
  • Call : FunctionCall

SelectStmt

channel select statement.

   select {
    case ch <- v:
    default:
    }
type SelectStmt struct {
        Select token.Pos  // position of "select" keyword
        Body   *BlockStmt // CommClauses only
}
  • Select : position
  • Body : CommClauses type CommClause struct { Case token.Pos // position of "case" or "default" keyword Comm Stmt // send or receive statement; nil means default case Colon token.Pos // position of ":" Body []Stmt // statement list; or nil }
    • Case : position
    • Comm :
      • case ch <- v: -> SendStmt
      • case a := <- ch: -> AssignStmt -> Ident := UnaryExpr
      • case 2: -> ExprStmt. I dont know whether semantcally true.
      • cannot use more than 1 statements like case ch <- v, ch <- u
    • Colon : position
    • Body : between current and next case line.

SendStmt

channel sending and receiving like ch <- a.

type SendStmt struct {
        Chan  Expr
        Arrow token.Pos // position of "<-"
        Value Expr
}
  • Chan : ch <- a -> Ident ch
  • Arrow : position
  • Value : ch <- a -> Ident a

EmptyStmt

nop! To use for removing implicit ;?

type EmptyStmt struct {
        Semicolon token.Pos // position of following ";"
        Implicit  bool      // if set, ";" was omitted in the source; added in Go 1.5
}

Type

Type structs are used by FuncDecl, \*Spec.

FuncType

type FuncType struct {
        Func    token.Pos  // position of "func" keyword (token.NoPos if there is no "func")
        Params  *FieldList // (incoming) parameters; non-nil
        Results *FieldList // (outgoing) results; or nil
}

StructType

type StructType struct {
        Struct     token.Pos  // position of "struct" keyword
        Fields     *FieldList // list of field declarations
        Incomplete bool       // true if (source) fields are missing in the Fields list
}
  • Fields : defined fields

InterfaceType

type InterfaceType struct {
        Interface  token.Pos  // position of "interface" keyword
        Methods    *FieldList // list of methods
        Incomplete bool       // true if (source) methods are missing in the Methods list
}
  • Methods : defined methods

ArrayType

type ArrayType struct {
        Lbrack token.Pos // position of "["
        Len    Expr      // Ellipsis node for [...]T array types, nil for slice types
        Elt    Expr      // element type
}
  • Len
    • []int -> nil
    • [3]int -> BasicLit "3"
  • Elt
    • []int -> Ident int

MapType

type MapType struct {
        Map   token.Pos // position of "map" keyword
        Key   Expr
        Value Expr
}
  • Key : map[string]int -> Ident string
  • Value : map[string]int -> Ident int

ChanType

type ChanType struct {
        Begin token.Pos // position of "chan" keyword or "<-" (whichever comes first)
        Arrow token.Pos // position of "<-" (token.NoPos if there is no "<-"); added in Go 1.1
        Dir   ChanDir   // channel direction
        Value Expr      // value type
}
  • Dir : I found Dir : 3, I dont know why.
   const (
            SEND ChanDir = 1 << iota
            RECV
    )
  • Value : c chan int -> Ident int

Literal

BasicLit

Integer, Float, Imaginary(虚数), Char, String literal used by Field struct.

type BasicLit struct {
        ValuePos token.Pos   // literal position
        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`
}

CompositeLit

Composite literals.

type fuga struct {
    a int
    b string
}

var fooo = fuga{1} // here

var arr = []int{1, 2, 3} // here
type CompositeLit struct {
        Type       Expr      // literal type; or nil
        Lbrace     token.Pos // position of "{"
        Elts       []Expr    // list of composite elements; or nil
        Rbrace     token.Pos // position of "}"
        Incomplete bool      // true if (source) expressions are missing in the Elts list; added in Go 1.11
}
  • Type : type of this struct
  • Elts : var fooo = fuga{1} -> BasicLit 1

FuncLit

Function Literal (non-name func)

var f = func(src string) string { return "<<" + src + ">>" }
type FuncLit struct {
        Type *FuncType  // function type
        Body *BlockStmt // function body
}

Expr

BinaryExpr

1+3, x == 2

type BinaryExpr struct {
    X     Expr        // left operand
    OpPos token.Pos   // position of Op
    Op    token.Token // operator
    Y     Expr        // right operand
}

CallExpr

func(1,2)

type CallExpr struct {
    Fun      Expr      // function expression
    Lparen   token.Pos // position of "("
    Args     []Expr    // function arguments; or nil
    Ellipsis token.Pos // position of "..." (token.NoPos if there is no "...")
    Rparen   token.Pos // position of ")"
}

IndexExpr

arr[2]

type IndexExpr struct {
    X      Expr      // expression
    Lbrack token.Pos // position of "["
    Index  Expr      // index expression
    Rbrack token.Pos // position of "]"
}

KeyValueExpr

var s = MyStruct{key: "value"}

type KeyValueExpr struct {
        Key   Expr
        Colon token.Pos // position of ":"
        Value Expr
}

ParenExpr

(1+2)/3

type ParenExpr struct {
    Lparen token.Pos // position of "("
    X      Expr      // parenthesized expression
    Rparen token.Pos // position of ")"
}

SelectorExpr

fmt.Println("")

type SelectorExpr struct {
        X   Expr   // expression
        Sel *Ident // field selector
}
  • X : fmt.Println("🍣") -> "fmt"
  • Sel : fmt.Println("🍖") -> "Println"

SliceExpr

c := a[2:4]

type SliceExpr struct {
        X      Expr      // expression
        Lbrack token.Pos // position of "["
        Low    Expr      // begin of slice range; or nil
        High   Expr      // end of slice range; or nil
        Max    Expr      // maximum capacity of slice; or nil; added in Go 1.2
        Slice3 bool      // true if 3-index slice (2 colons present); added in Go 1.2
        Rbrack token.Pos // position of "]"
}
  • X : c := a[2:4] -> Ident a
  • Low : c := a[2:4] -> BasicLit 2
  • High : c := a[2:4] -> BasicLit 4
  • Max : c := a[2:4:3] -> BasicLit 3
  • Slice3 : 3-index means a[low : high : max], maybe!

StarExpr

*Hoge

type StarExpr struct {
        Star token.Pos // position of "*"
        X    Expr      // operand
}
  • Star : position
  • X : *Hoge -> Expr of Hoge (ex, CompositeLit)

TypeAssertExpr

3.00.(int)

type TypeAssertExpr struct {
        X      Expr      // expression
        Lparen token.Pos // position of "("; added in Go 1.2
        Type   Expr      // asserted type; nil means type switch X.(type)
        Rparen token.Pos // position of ")"; added in Go 1.2
}
  • X : 3.00.(int) -> BasicLit 3.00(FLOAT)
  • Type :3.00.(int) -> Ident int

UnaryExpr

represents a unary expression exept * (StarExpr).

(ex, !true, var b = &a, ^2)

type UnaryExpr struct {
        OpPos token.Pos   // position of Op
        Op    token.Token // operator
        X     Expr        // operand
}
  • Op : &a -> "&"
  • X : &a -> Ident a