ast

package
v1.21.7 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2023 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package ast はGoのパッケージの構文木を表すために使用される型を宣言します。

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func FileExports

func FileExports(src *File) bool

FileExportsは、GoのソースファイルのASTを現在の場所でトリムします。 エクスポートされたノードのみが残り、エクスポートされていないトップレベルの識別子とそれに関連する情報 (型、初期値、または関数本体など)は削除されます。エクスポートされた型の非エクスポートフィールドとメソッドも剥ぎ取られます。 File.Commentsリストは変更されません。

FileExportsは、エクスポートされた宣言があるかどうかを報告します。

func FilterDecl

func FilterDecl(decl Decl, f Filter) bool

FilterDeclはGoの宣言のASTを変更して、フィルターfを通過しない名前(構造体フィールドやインタフェースメソッドの名前を含むが、パラメーターリストからは除外)を削除します。

FilterDeclは、フィルタリング後に残された宣言された名前があるかどうかを報告します。

func FilterFile

func FilterFile(src *File, f Filter) bool

FilterFileは、フィルタfを通過しない(構造体のフィールドやインターフェースのメソッド名を含むが、パラメータリストからは含まれない)トップレベルの宣言からすべての名前を削除することで、GoファイルのASTを修正します。もし宣言が空になった場合、宣言はASTから削除されます。Import宣言は必ず削除されます。File.Commentsのリストは変更されません。 FilterFileは、フィルタリング後にトップレベルの宣言が残っているかどうかを報告します。

func FilterPackage

func FilterPackage(pkg *Package, f Filter) bool

FilterPackageは、フィルターfを通過しない(構造体フィールドやインターフェースメソッド名を含むが、パラメータリストからは除かれない)トップレベル宣言のすべての名前を削除することにより、GoパッケージのASTを修正します。 宣言がその後空になった場合、宣言はASTから削除されます。 pkg.Filesリストは変更されないため、ファイル名やトップレベルのパッケージコメントが失われることはありません。

FilterPackageは、フィルタリング後にトップレベルの宣言が残っているかどうかを報告します。

func Fprint

func Fprint(w io.Writer, fset *token.FileSet, x any, f FieldFilter) error

FprintはASTノードxから始まる(サブ)ツリーをwに出力します。 もしfset != nilなら、位置情報はそのファイルセットに対して相対的に解釈されます。 それ以外の場合は位置は整数値(ファイルセット固有のオフセット)として表示されます。

非nilのFieldFilter fが提供された場合、出力を制御するために使用されます: f(fieldname, fieldvalue)がtrueを返す構造体フィールドだけが出力されます。 それ以外のものは出力からフィルタリングされます。エクスポートされていない構造体フィールドは常に出力されません。

func Inspect

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

InspectはASTを深さ優先順で走査します:まずf(node)を呼び出します。nodeはnilであってはなりません。fがtrueを返す場合、Inspectはnodeの非nilな子のそれぞれに対して再帰的にfを呼び出し、その後にf(nil)を呼び出します。

Example

この例は、GoプログラムのASTを検査する方法を示しています。

package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/go/ast"
	"github.com/shogo82148/std/go/parser"
	"github.com/shogo82148/std/go/token"
)

func main() {
	// srcはASTを検査したい入力です。
	src := `
package p
const c = 1.0
var X = f(3.14)*2 + c
`

	// srcを解析してASTを作成する。
	fset := token.NewFileSet() // ポジションはfsetに対して相対的です。
	f, err := parser.ParseFile(fset, "src.go", src, 0)
	if err != nil {
		panic(err)
	}

	// AST を調査し、すべての識別子とリテラルを表示します。
	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は、名前が大文字で始まるかどうかを報告します。

func IsGenerated added in v1.21.0

func IsGenerated(file *File) bool

IsGeneratedは、プログラムによって生成されたファイルか、手書きではないかを報告します。 https://go.dev/s/generatedcodeに記載されている特殊コメントを検出します。

構文木は、ParseCommentsフラグを使用して解析されている必要があります。 例:

f, err := parser.ParseFile(fset, filename, src, parser.ParseComments|parser.PackageClauseOnly)
if err != nil { ... }
gen := ast.IsGenerated(f)

func NotNilFilter

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

NotNilFilterは、nilでないフィールド値に対してtrueを返します。 それ以外の場合はfalseを返します。

func PackageExports

func PackageExports(pkg *Package) bool

PackageExportsは、GoパッケージのASTを変更して、エクスポートされたノードのみが残るようにします。pkg.Filesリストは変更されず、ファイル名とトップレベルのパッケージコメントは失われません。

PackageExportsは、エクスポートされた宣言があるかどうかを報告します。エクスポートされた宣言がない場合、falseを返します。

func Print

func Print(fset *token.FileSet, x any) error

Print関数は、nilのフィールドをスキップしてxを標準出力に出力します。 Print(fset, x)は、Fprint(os.Stdout, fset, x, NotNilFilter)と同じです。

Example

この例では、デバッグ用に出力されるASTの形状を示しています。

package main

import (
	"github.com/shogo82148/std/go/ast"
	"github.com/shogo82148/std/go/parser"
	"github.com/shogo82148/std/go/token"
)

func main() {
	// srcはASTを出力したい入力です。
	src := `
package main
func main() {
	println("Hello, World!")
}
`

	// src を解析してASTを作成します。
	fset := token.NewFileSet() // ポジションはfsetに対して相対的です。
	f, err := parser.ParseFile(fset, "", src, 0)
	if err != nil {
		panic(err)
	}

	// 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  .  FileStart: 1:1
    51  .  FileEnd: 5:3
    52  .  Scope: *ast.Scope {
    53  .  .  Objects: map[string]*ast.Object (len = 1) {
    54  .  .  .  "main": *(obj @ 11)
    55  .  .  }
    56  .  }
    57  .  Unresolved: []*ast.Ident (len = 1) {
    58  .  .  0: *(obj @ 29)
    59  .  }
    60  .  GoVersion: ""
    61  }

func SortImports

func SortImports(fset *token.FileSet, f *File)

SortImportsはfのimportブロック内の連続したimport行をソートします。 データの損失なしに重複するimportを削除することも可能です。

func Walk

func Walk(v Visitor, node Node)

WalkはASTを深さ優先でトラバースします。最初にv.Visit(node)を呼び出します。nodeはnilであってはいけません。v.Visit(node)から返されるビジターwがnilでない場合、Walkはnodeのnilでない子要素ごとに再帰的にビジターwを用いて呼び出され、その後にw.Visit(nil)が呼び出されます。

Types

type ArrayType

type ArrayType struct {
	Lbrack token.Pos
	Len    Expr
	Elt    Expr
}

ArrayTypeノードは、配列またはスライスの型を表します。

func (*ArrayType) End

func (x *ArrayType) End() token.Pos

func (*ArrayType) Pos

func (x *ArrayType) Pos() token.Pos

type AssignStmt

type AssignStmt struct {
	Lhs    []Expr
	TokPos token.Pos
	Tok    token.Token
	Rhs    []Expr
}

AssignStmt ノードは、代入または短い変数宣言を表します。

func (*AssignStmt) End

func (s *AssignStmt) End() token.Pos

func (*AssignStmt) Pos

func (s *AssignStmt) Pos() token.Pos

type BadDecl

type BadDecl struct {
	From, To token.Pos
}

BadDeclノードは、正しい宣言ノードを作成できない構文エラーを含む宣言のプレースホルダです。

func (*BadDecl) End

func (d *BadDecl) End() token.Pos

func (*BadDecl) Pos

func (d *BadDecl) Pos() token.Pos

type BadExpr

type BadExpr struct {
	From, To token.Pos
}

BadExprノードは、正しい式ノードを作成できない構文エラーを含む式のプレースホルダーです。

func (*BadExpr) End

func (x *BadExpr) End() token.Pos

func (*BadExpr) Pos

func (x *BadExpr) Pos() token.Pos

type BadStmt

type BadStmt struct {
	From, To token.Pos
}

BadStmtノードは、構文エラーを含むステートメントのプレースホルダーであり、 正しいステートメントノードを作成することができません。

func (*BadStmt) End

func (s *BadStmt) End() token.Pos

func (*BadStmt) Pos

func (s *BadStmt) Pos() token.Pos

type BasicLit

type BasicLit struct {
	ValuePos token.Pos
	Kind     token.Token
	Value    string
}

BasicLitノードは基本型のリテラルを表します。

func (*BasicLit) End

func (x *BasicLit) End() token.Pos

func (*BasicLit) Pos

func (x *BasicLit) Pos() token.Pos

type BinaryExpr

type BinaryExpr struct {
	X     Expr
	OpPos token.Pos
	Op    token.Token
	Y     Expr
}

BinaryExprノードはバイナリ式を表します。

func (*BinaryExpr) End

func (x *BinaryExpr) End() token.Pos

func (*BinaryExpr) Pos

func (x *BinaryExpr) Pos() token.Pos

type BlockStmt

type BlockStmt struct {
	Lbrace token.Pos
	List   []Stmt
	Rbrace token.Pos
}

BlockStmtノードは中括弧で囲まれた文リストを表します。

func (*BlockStmt) End

func (s *BlockStmt) End() token.Pos

func (*BlockStmt) Pos

func (s *BlockStmt) Pos() token.Pos

type BranchStmt

type BranchStmt struct {
	TokPos token.Pos
	Tok    token.Token
	Label  *Ident
}

BranchStmtノードはbreak、continue、goto、またはfallthroughステートメントを表します。

func (*BranchStmt) End

func (s *BranchStmt) End() token.Pos

func (*BranchStmt) Pos

func (s *BranchStmt) Pos() token.Pos

type CallExpr

type CallExpr struct {
	Fun      Expr
	Lparen   token.Pos
	Args     []Expr
	Ellipsis token.Pos
	Rparen   token.Pos
}

A CallExpr node represents an expression followed by an argument list. CallExprノードは、式の後に引数リストが続くことを表します。

func (*CallExpr) End

func (x *CallExpr) End() token.Pos

func (*CallExpr) Pos

func (x *CallExpr) Pos() token.Pos

type CaseClause

type CaseClause struct {
	Case  token.Pos
	List  []Expr
	Colon token.Pos
	Body  []Stmt
}

CaseClauseは式や型switch文のケースを表します。

func (*CaseClause) End

func (s *CaseClause) End() token.Pos

func (*CaseClause) Pos

func (s *CaseClause) Pos() token.Pos

type ChanDir

type ChanDir int
const (
	SEND ChanDir = 1 << iota
	RECV
)

type ChanType

type ChanType struct {
	Begin token.Pos
	Arrow token.Pos
	Dir   ChanDir
	Value Expr
}

ChanTypeノードは、チャネルの型を表します。

func (*ChanType) End

func (x *ChanType) End() token.Pos

func (*ChanType) Pos

func (x *ChanType) Pos() token.Pos

type CommClause

type CommClause struct {
	Case  token.Pos
	Comm  Stmt
	Colon token.Pos
	Body  []Stmt
}

CommClauseノードは、select文のcaseを表します。

func (*CommClause) End

func (s *CommClause) End() token.Pos

func (*CommClause) Pos

func (s *CommClause) Pos() token.Pos

type Comment

type Comment struct {
	Slash token.Pos
	Text  string
}

Commentノードは、単一の//-スタイルまたは/*-スタイルのコメントを表します。

Textフィールドには、ソースに存在した可能性のあるキャリッジリターン(\r)を含まないコメントテキストが含まれます。コメントの終了位置はlen(Text)を使用して計算されるため、End()によって報告される位置は、キャリッジリターンを含むコメントの真のソース終了位置と一致しません。

func (*Comment) End

func (c *Comment) End() token.Pos

func (*Comment) Pos

func (c *Comment) Pos() token.Pos

type CommentGroup

type CommentGroup struct {
	List []*Comment
}

CommentGroupは、他のトークンや空の行がないコメントのシーケンスを表します。

func (*CommentGroup) End

func (g *CommentGroup) End() token.Pos

func (*CommentGroup) Pos

func (g *CommentGroup) Pos() token.Pos

func (*CommentGroup) Text

func (g *CommentGroup) Text() string

Textはコメントのテキストを返します。 コメントマーカー(//、/*、および*/)、行コメントの最初のスペース、および 先行および後続の空行は除去されます。 "//line"や"//go:noinline"のようなコメントディレクティブも削除されます。 複数の空行は1つに減らされ、行の末尾のスペースはトリムされます。 結果が空でない場合、改行で終わります。

type CommentMap added in v1.1.0

type CommentMap map[Node][]*CommentGroup

CommentMapはASTノードをそのノードに関連付けられたコメントグループのリストにマップします。 関連付けについては、NewCommentMapの説明を参照してください。

Example

この例は、ast.CommentMapを使用して、Goプログラムの変数宣言を削除しながら正しいコメントの関連を保持する方法を示しています。

package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/go/ast"
	"github.com/shogo82148/std/go/format"
	"github.com/shogo82148/std/go/parser"
	"github.com/shogo82148/std/go/token"
	"github.com/shogo82148/std/strings"
)

func main() {

	// src は、私たちが操作するためのASTを作成する入力です。
	src := `
// This is the package comment.
package main

// This comment is associated with the hello constant.
const hello = "Hello, World!" // line comment 1

// This comment is associated with the foo variable.
var foo = hello // line comment 2

// This comment is associated with the main function.
func main() {
	fmt.Println(hello) // line comment 3
}
`

	// src をパースしてASTを作成する。
	fset := token.NewFileSet() // positionsはfsetに対して相対的です。
	f, err := parser.ParseFile(fset, "src.go", src, parser.ParseComments)
	if err != nil {
		panic(err)
	}

	// ast.File のコメントから ast.CommentMap を作成します。
	// これにより、コメントと AST ノードの関連付けが保持されます。
	cmap := ast.NewCommentMap(fset, f, f.Comments)

	// 最初の変数宣言を宣言リストから削除します。
	for i, decl := range f.Decls {
		if gen, ok := decl.(*ast.GenDecl); ok && gen.Tok == token.VAR {
			copy(f.Decls[i:], f.Decls[i+1:])
			f.Decls = f.Decls[:len(f.Decls)-1]
			break
		}
	}

	// コメントマップを使用して、もはや必要でないコメント(変数宣言に関連するコメント)をフィルタリングし、新しいコメントリストを作成します。
	f.Comments = cmap.Filter(f).Comments()

	// 変更されたASTを出力します。
	var buf strings.Builder
	if err := format.Node(&buf, fset, f); err != nil {
		panic(err)
	}
	fmt.Printf("%s", buf.String())

}
Output:

// This is the package comment.
package main

// This comment is associated with the hello constant.
const hello = "Hello, World!" // line comment 1

// This comment is associated with the main function.
func main() {
	fmt.Println(hello) // line comment 3
}

func NewCommentMap added in v1.1.0

func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap

NewCommentMapは、コメントリストのコメントグループをASTのノードと関連付けて新しいコメントマップを作成します。 コメントグループgは、ノードnと関連付けられます。以下の条件を満たす場合です:

  • gは、nの終了する行と同じ行で開始します。
  • gは、nの直後の行で始まり、gと次のノードの間に少なくとも1つの空行がある場合。
  • gは、nよりも前に開始され、前のルールを介してnの前のノードに関連付けられていない場合。

NewCommentMapは、コメントグループを「最大の」ノードに関連付けようとします。たとえば、コメントが代入文の後に続く行コメントの場合、コメントは代入文全体ではなく、代入文の最後のオペランドに関連づけられます。

func (CommentMap) Comments added in v1.1.0

func (cmap CommentMap) Comments() []*CommentGroup

Commentsはコメントマップ内のコメントグループのリストを返します。 結果はソースの順にソートされます。

func (CommentMap) Filter added in v1.1.0

func (cmap CommentMap) Filter(node Node) CommentMap

Filterはnodeによって指定されたASTに対応するノードが存在する場合、cmapのエントリのみで構成される新しいコメントマップを返します。

func (CommentMap) String added in v1.1.0

func (cmap CommentMap) String() string

func (CommentMap) Update added in v1.1.0

func (cmap CommentMap) Update(old, new Node) Node

Updateはコメントマップ内の古いノードを新しいノードで置き換え、新しいノードを返します。 古いノードに関連付けられていたコメントは、新しいノードに関連付けられます。

type CompositeLit

type CompositeLit struct {
	Type       Expr
	Lbrace     token.Pos
	Elts       []Expr
	Rbrace     token.Pos
	Incomplete bool
}

CompositeLitノードは複合リテラルを表します。

func (*CompositeLit) End

func (x *CompositeLit) End() token.Pos

func (*CompositeLit) Pos

func (x *CompositeLit) Pos() token.Pos

type Decl

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

すべての宣言ノードはDeclインターフェースを実装します。

type DeclStmt

type DeclStmt struct {
	Decl Decl
}

DeclStmtノードは、文リスト内の宣言を表します。

func (*DeclStmt) End

func (s *DeclStmt) End() token.Pos

func (*DeclStmt) Pos

func (s *DeclStmt) Pos() token.Pos

type DeferStmt

type DeferStmt struct {
	Defer token.Pos
	Call  *CallExpr
}

DeferStmtノードは、defer文を表します。

func (*DeferStmt) End

func (s *DeferStmt) End() token.Pos

func (*DeferStmt) Pos

func (s *DeferStmt) Pos() token.Pos

type Ellipsis

type Ellipsis struct {
	Ellipsis token.Pos
	Elt      Expr
}

Ellipsis(省略符)ノードは、パラメータリスト内の "..." 型または配列型の "..." 長さを表します。

func (*Ellipsis) End

func (x *Ellipsis) End() token.Pos

func (*Ellipsis) Pos

func (x *Ellipsis) Pos() token.Pos

type EmptyStmt

type EmptyStmt struct {
	Semicolon token.Pos
	Implicit  bool
}

EmptyStmtノードは、空の文を表します。 空の文の「位置」は、直後の(明示的または暗黙の)セミコロンの位置です。

func (*EmptyStmt) End

func (s *EmptyStmt) End() token.Pos

func (*EmptyStmt) Pos

func (s *EmptyStmt) Pos() token.Pos

type Expr

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

すべての式のノードは、Exprインターフェースを実装しています。

type ExprStmt

type ExprStmt struct {
	X Expr
}

ExprStmtノードは、文リストの中で単独での式を表します。

func (*ExprStmt) End

func (s *ExprStmt) End() token.Pos

func (*ExprStmt) Pos

func (s *ExprStmt) Pos() token.Pos

type Field

type Field struct {
	Doc     *CommentGroup
	Names   []*Ident
	Type    Expr
	Tag     *BasicLit
	Comment *CommentGroup
}

Fieldは、struct型のフィールド宣言リスト、インタフェース型のメソッドリスト、またはシグネチャのパラメータ/結果の宣言を表します。 Field.Namesは、無名のパラメータ(型のみを含むパラメータリスト)や埋め込まれたstructフィールドの場合はnilです。 後者の場合、フィールド名は型名です。

func (*Field) End

func (f *Field) End() token.Pos

func (*Field) Pos

func (f *Field) Pos() token.Pos

type FieldFilter

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

出力を制御するために、FprintにFieldFilterを指定することができます。

type FieldList

type FieldList struct {
	Opening token.Pos
	List    []*Field
	Closing token.Pos
}

FieldList は、かっこ、中かっこ、又は角かっこで囲まれたフィールドのリストを表します。

func (*FieldList) End

func (f *FieldList) End() token.Pos

func (*FieldList) NumFields

func (f *FieldList) NumFields() int

NumFieldsはFieldListによって表されるパラメータまたは構造体のフィールドの数を返します。

func (*FieldList) Pos

func (f *FieldList) Pos() token.Pos

type File

type File struct {
	Doc     *CommentGroup
	Package token.Pos
	Name    *Ident
	Decls   []Decl

	FileStart, FileEnd token.Pos
	Scope              *Scope
	Imports            []*ImportSpec
	Unresolved         []*Ident
	Comments           []*CommentGroup
	GoVersion          string
}

FileノードはGoのソースファイルを表します。

Commentsリストには、出現順にソースファイル内のすべてのコメントが含まれており、 DocとCommentフィールドを介して他のノードから指し示されるコメントも含まれます。

コメントを含むソースコードを正しく出力するために(パッケージgo/formatとgo/printerを使用して)特別な注意が必要です: コメントは、位置に基づいてトークンの間に挿入されます。構文木ノードが削除または移動される場合、 その近くにある関連するコメントも削除(File.Commentsリストから)またはそれらの位置を更新して移動しなければなりません。 これらの操作の一部を容易にするために、CommentMapを使用することもできます。

コメントがノードとどのように関連付けられるかは、操作するプログラムによる構文木の解釈に依存します: DocとCommentコメント以外の残りのコメントは、「free-floating」です(#18593号、#20744号も参照)。

func MergePackageFiles

func MergePackageFiles(pkg *Package, mode MergeMode) *File

MergePackageFilesはパッケージに所属するファイルのASTをマージしてファイルASTを作成します。モードフラグはマージの動作を制御します。

func (*File) End

func (f *File) End() token.Pos

Endはファイル中の最後の宣言の終了位置を返します。 (ファイル全体の終了位置にはFileEndを使用してください。)

func (*File) Pos

func (f *File) Pos() token.Pos

Posはパッケージ宣言の位置を返します。 (ファイル全体の開始位置にはFileStartを使用してください。)

type Filter

type Filter func(string) bool

type ForStmt

type ForStmt struct {
	For  token.Pos
	Init Stmt
	Cond Expr
	Post Stmt
	Body *BlockStmt
}

ForStmt は for 文を表します。

func (*ForStmt) End

func (s *ForStmt) End() token.Pos

func (*ForStmt) Pos

func (s *ForStmt) Pos() token.Pos

type FuncDecl

type FuncDecl struct {
	Doc  *CommentGroup
	Recv *FieldList
	Name *Ident
	Type *FuncType
	Body *BlockStmt
}

FuncDeclノードは関数宣言を表します。

func (*FuncDecl) End

func (d *FuncDecl) End() token.Pos

func (*FuncDecl) Pos

func (d *FuncDecl) Pos() token.Pos

type FuncLit

type FuncLit struct {
	Type *FuncType
	Body *BlockStmt
}

FuncLitノードは関数リテラルを表します。

func (*FuncLit) End

func (x *FuncLit) End() token.Pos

func (*FuncLit) Pos

func (x *FuncLit) Pos() token.Pos

type FuncType

type FuncType struct {
	Func       token.Pos
	TypeParams *FieldList
	Params     *FieldList
	Results    *FieldList
}

FuncTypeノードは関数の型を表します。

func (*FuncType) End

func (x *FuncType) End() token.Pos

func (*FuncType) Pos

func (x *FuncType) Pos() token.Pos

type GenDecl

type GenDecl struct {
	Doc    *CommentGroup
	TokPos token.Pos
	Tok    token.Token
	Lparen token.Pos
	Specs  []Spec
	Rparen token.Pos
}

GenDeclノード(ジェネリック宣言ノード)は、import、constant、type、またはvariableの宣言を表します。有効なLparenの位置(Lparen.IsValid())は、括弧で囲まれた宣言を示します。

Tokの値とSpecs要素の型の関係:

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

func (*GenDecl) End

func (d *GenDecl) End() token.Pos

func (*GenDecl) Pos

func (d *GenDecl) Pos() token.Pos

type GoStmt

type GoStmt struct {
	Go   token.Pos
	Call *CallExpr
}

GoStmtノードは、go文を表します。

func (*GoStmt) End

func (s *GoStmt) End() token.Pos

func (*GoStmt) Pos

func (s *GoStmt) Pos() token.Pos

type Ident

type Ident struct {
	NamePos token.Pos
	Name    string
	Obj     *Object
}

Identノードは、識別子を表します。

func NewIdent

func NewIdent(name string) *Ident

NewIdentは位置情報のない新しいIdentを作成します。 Goパーサー以外のコードで生成されたASTに便利です。

func (*Ident) End

func (x *Ident) End() token.Pos

func (*Ident) IsExported

func (id *Ident) IsExported() bool

IsExported は、id が大文字で始まるかどうかを報告します。

func (*Ident) Pos

func (x *Ident) Pos() token.Pos

func (*Ident) String

func (id *Ident) String() string

type IfStmt

type IfStmt struct {
	If   token.Pos
	Init Stmt
	Cond Expr
	Body *BlockStmt
	Else Stmt
}

IfStmtノードはif文を表します。

func (*IfStmt) End

func (s *IfStmt) End() token.Pos

func (*IfStmt) Pos

func (s *IfStmt) Pos() token.Pos

type ImportSpec

type ImportSpec struct {
	Doc     *CommentGroup
	Name    *Ident
	Path    *BasicLit
	Comment *CommentGroup
	EndPos  token.Pos
}

ImportSpecノードは1つのパッケージのインポートを表します。

func (*ImportSpec) End

func (s *ImportSpec) End() token.Pos

func (*ImportSpec) Pos

func (s *ImportSpec) Pos() token.Pos

type Importer

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

Importerは、インポートパスをパッケージオブジェクトに変換します。 importsマップは、既にインポートされたパッケージを記録し、パッケージID(正規のインポートパス)で索引付けされます。 Importerは正規のインポートパスを決定し、importsマップに既に存在するかどうかを確認する必要があります。 もし存在する場合、Importerはマップのエントリを返すことができます。 そうでない場合、Importerは指定されたパスのパッケージデータを新しい*Object(pkg)に読み込み、 pkgをimportsマップに記録した後、pkgを返します。

type IncDecStmt

type IncDecStmt struct {
	X      Expr
	TokPos token.Pos
	Tok    token.Token
}

IncDecStmtノードは、増分または減分文を表します。

func (*IncDecStmt) End

func (s *IncDecStmt) End() token.Pos

func (*IncDecStmt) Pos

func (s *IncDecStmt) Pos() token.Pos

type IndexExpr

type IndexExpr struct {
	X      Expr
	Lbrack token.Pos
	Index  Expr
	Rbrack token.Pos
}

IndexExprノードは、インデックスに続く式を表します。

func (*IndexExpr) End

func (x *IndexExpr) End() token.Pos

func (*IndexExpr) Pos

func (x *IndexExpr) Pos() token.Pos

type IndexListExpr added in v1.18.0

type IndexListExpr struct {
	X       Expr
	Lbrack  token.Pos
	Indices []Expr
	Rbrack  token.Pos
}

IndexListExprノードは、複数のインデックスで続く式を表します。

func (*IndexListExpr) End added in v1.18.0

func (x *IndexListExpr) End() token.Pos

func (*IndexListExpr) Pos added in v1.18.0

func (x *IndexListExpr) Pos() token.Pos

type InterfaceType

type InterfaceType struct {
	Interface  token.Pos
	Methods    *FieldList
	Incomplete bool
}

InterfaceTypeノードは、インターフェースの型を表します。

func (*InterfaceType) End

func (x *InterfaceType) End() token.Pos

func (*InterfaceType) Pos

func (x *InterfaceType) Pos() token.Pos

type KeyValueExpr

type KeyValueExpr struct {
	Key   Expr
	Colon token.Pos
	Value Expr
}

KeyValueExprノードは、コンポジットリテラル内の(key: value)のペアを表します。

func (*KeyValueExpr) End

func (x *KeyValueExpr) End() token.Pos

func (*KeyValueExpr) Pos

func (x *KeyValueExpr) Pos() token.Pos

type LabeledStmt

type LabeledStmt struct {
	Label *Ident
	Colon token.Pos
	Stmt  Stmt
}

LabeledStmtノードは、ラベル付き文を表します。

func (*LabeledStmt) End

func (s *LabeledStmt) End() token.Pos

func (*LabeledStmt) Pos

func (s *LabeledStmt) Pos() token.Pos

type MapType

type MapType struct {
	Map   token.Pos
	Key   Expr
	Value Expr
}

MapType ノードはマップ型を表します。

func (*MapType) End

func (x *MapType) End() token.Pos

func (*MapType) Pos

func (x *MapType) Pos() token.Pos

type MergeMode

type MergeMode uint

MergePackageFilesの動作を制御するMergeModeフラグ。

const (
	// セットされている場合、重複する関数宣言は除外されます。
	FilterFuncDuplicates MergeMode = 1 << iota

	// セットされている場合、特定のASTノード(DocやCommentなど)に関連付けられていないコメントは除外されます。
	FilterUnassociatedComments
	// もし設定されていた場合、重複したインポート宣言は除外されます。
	FilterImportDuplicates
)

type Node

type Node interface {
	Pos() token.Pos
	End() token.Pos
}

すべてのノードタイプはNodeインターフェースを実装します。

type ObjKind

type ObjKind int

ObjKindはオブジェクトが表すものを説明します。

const (
	Bad ObjKind = iota
	Pkg
	Con
	Typ
	Var
	Fun
	Lbl
)

可能なオブジェクトの種類のリスト。

func (ObjKind) String

func (kind ObjKind) String() string

type Object

type Object struct {
	Kind ObjKind
	Name string
	Decl any
	Data any
	Type any
}

オブジェクトは、パッケージ、定数、型、変数、関数(メソッドを含む)、またはラベルなど、名前付きの言語エンティティを表します。

データフィールドには、オブジェクト固有のデータが含まれます:

	種類   データ型         データの値
 Pkg    *Scope           パッケージスコープ
 Con    int              対応する宣言のiota

func NewObj

func NewObj(kind ObjKind, name string) *Object

NewObjは指定された種類と名前の新しいオブジェクトを作成します。

func (*Object) Pos

func (obj *Object) Pos() token.Pos

Posはオブジェクト名の宣言のソース位置を計算します。 結果は計算できない場合は無効な位置になる可能性があります (obj.Declがnilであるか、正しくないかもしれません)。

type Package

type Package struct {
	Name    string
	Scope   *Scope
	Imports map[string]*Object
	Files   map[string]*File
}

パッケージノードは、Goパッケージを構築するために共に使用される 一連のソースファイルを表します。

func NewPackage

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

NewPackageは、一連のFileノードから新しいPackageノードを作成します。ファイル間の未解決の識別子を解決し、各ファイルの未解決リストを更新します。非nilのimporterとuniverseスコープが指定されている場合、パッケージファイルで宣言されていない識別子を解決するために使用されます。残りの未解決の識別子は宣言されていないとして報告されます。ファイルが異なるパッケージに属する場合、パッケージ名が選択され、パッケージ名が異なるファイルが報告された後、無視されます。 結果は、パッケージノードとscanner.ErrorListです。エラーがある場合にのみ返されます。

func (*Package) End

func (p *Package) End() token.Pos

func (*Package) Pos

func (p *Package) Pos() token.Pos

type ParenExpr

type ParenExpr struct {
	Lparen token.Pos
	X      Expr
	Rparen token.Pos
}

ParenExprノードは、括弧で囲まれた式を表します。

func (*ParenExpr) End

func (x *ParenExpr) End() token.Pos

func (*ParenExpr) Pos

func (x *ParenExpr) Pos() token.Pos

type RangeStmt

type RangeStmt struct {
	For        token.Pos
	Key, Value Expr
	TokPos     token.Pos
	Tok        token.Token
	Range      token.Pos
	X          Expr
	Body       *BlockStmt
}

RangeStmtはrange節を持つfor文を表します。

func (*RangeStmt) End

func (s *RangeStmt) End() token.Pos

func (*RangeStmt) Pos

func (s *RangeStmt) Pos() token.Pos

type ReturnStmt

type ReturnStmt struct {
	Return  token.Pos
	Results []Expr
}

ReturnStmtノードは、return文を表します。

func (*ReturnStmt) End

func (s *ReturnStmt) End() token.Pos

func (*ReturnStmt) Pos

func (s *ReturnStmt) Pos() token.Pos

type Scope

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

Scopeはスコープ内で宣言された名前付きの言語エンティティの集合と、直接の周囲(外側)のスコープへのリンクを維持します。

func NewScope

func NewScope(outer *Scope) *Scope

NewScopeは外部スコープにネストされた新しいスコープを作成します。

func (*Scope) Insert

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

Insertは名前付きオブジェクトobjをスコープsに挿入しようとします。 もしスコープに同じ名前のオブジェクトaltが既に存在する場合、 Insertはスコープを変更せずにaltを返します。そうでなければ、 objを挿入し、nilを返します。

func (*Scope) Lookup

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

Lookupは、与えられた名前のオブジェクトがスコープsに存在すればそのオブジェクトを返します。見つからない場合はnilを返します。外部のスコープは無視されます。

func (*Scope) String

func (s *Scope) String() string

デバッグサポート

type SelectStmt

type SelectStmt struct {
	Select token.Pos
	Body   *BlockStmt
}

SelectStmtノードは、select文を表します。

func (*SelectStmt) End

func (s *SelectStmt) End() token.Pos

func (*SelectStmt) Pos

func (s *SelectStmt) Pos() token.Pos

type SelectorExpr

type SelectorExpr struct {
	X   Expr
	Sel *Ident
}

SelectorExprノードは、セレクターに続く式を表します。

func (*SelectorExpr) End

func (x *SelectorExpr) End() token.Pos

func (*SelectorExpr) Pos

func (x *SelectorExpr) Pos() token.Pos

type SendStmt

type SendStmt struct {
	Chan  Expr
	Arrow token.Pos
	Value Expr
}

SendStmtノードは、送信文を表します。

func (*SendStmt) End

func (s *SendStmt) End() token.Pos

func (*SendStmt) Pos

func (s *SendStmt) Pos() token.Pos

type SliceExpr

type SliceExpr struct {
	X      Expr
	Lbrack token.Pos
	Low    Expr
	High   Expr
	Max    Expr
	Slice3 bool
	Rbrack token.Pos
}

SliceExprノードはスライスのインデックスが続いた式を表します。

func (*SliceExpr) End

func (x *SliceExpr) End() token.Pos

func (*SliceExpr) Pos

func (x *SliceExpr) Pos() token.Pos

type Spec

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

Spec型は、*ImportSpec、*ValueSpec、および*TypeSpecのいずれかを表します。

type StarExpr

type StarExpr struct {
	Star token.Pos
	X    Expr
}

StarExprノードは、"*" Expressionの形式の式を表します。 意味的には、単項"*"式またはポインタータイプのいずれかになります。

func (*StarExpr) End

func (x *StarExpr) End() token.Pos

func (*StarExpr) Pos

func (x *StarExpr) Pos() token.Pos

type Stmt

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

すべてのステートメントノードは、Stmtインターフェースを実装しています。

type StructType

type StructType struct {
	Struct     token.Pos
	Fields     *FieldList
	Incomplete bool
}

StructTypeノードはstruct型を表します。

func (*StructType) End

func (x *StructType) End() token.Pos

func (*StructType) Pos

func (x *StructType) Pos() token.Pos

type SwitchStmt

type SwitchStmt struct {
	Switch token.Pos
	Init   Stmt
	Tag    Expr
	Body   *BlockStmt
}

SwitchStmtノードは、式を使ったスイッチ文を表します。

func (*SwitchStmt) End

func (s *SwitchStmt) End() token.Pos

func (*SwitchStmt) Pos

func (s *SwitchStmt) Pos() token.Pos

type TypeAssertExpr

type TypeAssertExpr struct {
	X      Expr
	Lparen token.Pos
	Type   Expr
	Rparen token.Pos
}

TypeAssertExprノードは、式の後に型アサーションが続くことを表します。

func (*TypeAssertExpr) End

func (x *TypeAssertExpr) End() token.Pos

func (*TypeAssertExpr) Pos

func (x *TypeAssertExpr) Pos() token.Pos

type TypeSpec

type TypeSpec struct {
	Doc        *CommentGroup
	Name       *Ident
	TypeParams *FieldList
	Assign     token.Pos
	Type       Expr
	Comment    *CommentGroup
}

TypeSpecノードは、型の宣言を表します (TypeSpecの生成)。

func (*TypeSpec) End

func (s *TypeSpec) End() token.Pos

func (*TypeSpec) Pos

func (s *TypeSpec) Pos() token.Pos

type TypeSwitchStmt

type TypeSwitchStmt struct {
	Switch token.Pos
	Init   Stmt
	Assign Stmt
	Body   *BlockStmt
}

TypeSwitchStmtノードは、型スイッチ文を表します。

func (*TypeSwitchStmt) End

func (s *TypeSwitchStmt) End() token.Pos

func (*TypeSwitchStmt) Pos

func (s *TypeSwitchStmt) Pos() token.Pos

type UnaryExpr

type UnaryExpr struct {
	OpPos token.Pos
	Op    token.Token
	X     Expr
}

UnaryExprノードは単項式を表します。 単項の "*" 式はStarExprノードを介して表されます。

func (*UnaryExpr) End

func (x *UnaryExpr) End() token.Pos

func (*UnaryExpr) Pos

func (x *UnaryExpr) Pos() token.Pos

type ValueSpec

type ValueSpec struct {
	Doc     *CommentGroup
	Names   []*Ident
	Type    Expr
	Values  []Expr
	Comment *CommentGroup
}

ValueSpecノードは定数または変数宣言を表します。 (ConstSpecまたはVarSpecプロダクション)。

func (*ValueSpec) End

func (s *ValueSpec) End() token.Pos

func (*ValueSpec) Pos

func (s *ValueSpec) Pos() token.Pos

type Visitor

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

Walk によって遭遇したノードごとに Visitor の Visit メソッドが呼び出されます。 もし結果の visitor w が nil でない場合、Walk はノードの各子ノードを visitor w と共に訪問し、その後に w.Visit(nil) の呼び出しを行います。

Jump to

Keyboard shortcuts

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