ason

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2024 License: BSD-3-Clause Imports: 8 Imported by: 1

README

ASON

The library is a tool for serializing abstract syntax trees (AST) in Go and deserializing them back into Go code. This tool is designed to simplify working with AST in Go, enabling easy conversion of code structures into a serialized format and vice versa. This provides a convenient mechanism for analyzing, modifying, and generating Go code.

Serialize Mode

pass := ason.NewSerPass(fset, SkipComments)
Default

Serialize everything

CacheRef

Cache large nodes. Use this mode when you carry out some manual manipulations with the source AST tree. For example, you duplicate nodes, which can create nodes that have the same references to the original object in memory. Only large nodes can be cached, such as specifications, types and declarations.

SkipComments

Will not serialize any comments declarations

ResolveObject

ResolveObject identifiers to objects

ResolveScope

ResolveScope file and package scope and identifiers objects

ResolveLoc

ResolveLoc allow to resolve start and end position for all AST nodes.

Example

Serialize

Full example: example/deserialize/main.go

Target
/*
Hello World
*/
var test2 = "test2Value"

Code
import (
	"encoding/json"
	"fmt"
	"go/parser"
	"go/token"
	"log"

	"github.com/g10z3r/ason"
)

func main() {
	fset := token.NewFileSet()

	f, err := parser.ParseFile(fset, "../testdata/main.go", nil, parser.ParseComments)
	if err != nil {
		log.Fatal(err)
	}

	pass := ason.NewSerPass(fset)
	fileAstJson := ason.SerializeFile(pass, f)

	jsonData, err := json.Marshal(fileAstJson)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(jsonData))
}
Output
{
  "Doc": null,
  "Name": {
    "NamePos": { "Location": [8, 1, 9], "Filename": "../testdata/main.go" },
    "Name": "main",
    "Obj": null,
    "_ref": 0,
    "_type": "Ident",
    "_loc": null
  },
  "Decls": [
    {
      "Doc": {
        "List": [
          {
            "Slash": {
              "Location": [14, 3, 1],
              "Filename": "../testdata/main.go"
            },
            "Text": "/*\nHello World\n*/",
            "_ref": 0,
            "_type": "Comment",
            "_loc": null
          }
        ],
        "_ref": 0,
        "_type": "CommentGroup",
        "_loc": null
      },
      "TokenPos": { "Location": [32, 6, 1], "Filename": "../testdata/main.go" },
      "Tok": "var",
      "Lparen": 0,
      "Specs": [
        {
          "Doc": null,
          "Names": [
            {
              "NamePos": {
                "Location": [36, 6, 5],
                "Filename": "../testdata/main.go"
              },
              "Name": "test2",
              "Obj": null,
              "_ref": 0,
              "_type": "Ident",
              "_loc": null
            }
          ],
          "Type": null,
          "Values": [
            {
              "ValuePos": {
                "Location": [44, 6, 13],
                "Filename": "../testdata/main.go"
              },
              "Kind": "STRING",
              "Value": "\"test2Value\"",
              "_ref": 0,
              "_type": "BasicLit",
              "_loc": null
            }
          ],
          "Comment": null,
          "_ref": 0,
          "_type": "ValueSpec",
          "_loc": null
        }
      ],
      "Rparen": 0,
      "_ref": 0,
      "_type": "GenDecl",
      "_loc": null
    }
  ],
  "Size": 57,
  "FileStart": { "Location": [0, 1, 1], "Filename": "../testdata/main.go" },
  "FileEnd": { "Location": [57, 6, 26], "Filename": "../testdata/main.go" },
  "Scope": null,
  "Imports": null,
  "Unresolved": null,
  "Package": { "Location": [0, 1, 1], "Filename": "../testdata/main.go" },
  "Comments": [
    {
      "List": [
        {
          "Slash": {
            "Location": [14, 3, 1],
            "Filename": "../testdata/main.go"
          },
          "Text": "/*\nHello World\n*/",
          "_ref": 0,
          "_type": "Comment",
          "_loc": null
        }
      ],
      "_ref": 0,
      "_type": "CommentGroup",
      "_loc": null
    }
  ],
  "GoVersion": "",
  "_ref": 0,
  "_type": "File",
  "_loc": null
}

Deserialize

Full example: example/deserialize/main.go

Code
func main(){
    file, err := serialize("../testdata/main.go")
	if err != nil {
		log.Fatal(err)
	}

	fset := token.NewFileSet()
	pass := ason.NewDePass(fset)
	f, err := ason.DeserializeFile(pass, file)
	if err != nil {
		log.Fatal(err)
	}
}
Output
package main /*
Hello World
*/
var test2 = "test2Value"

Documentation

Index

Constants

View Source
const (
	NodeTypeInvalid        = "Invalid"
	NodeTypeFile           = "File"
	NodeTypeComment        = "Comment"
	NodeTypeCommentGroup   = "CommentGroup"
	NodeTypeIdent          = "Ident"
	NodeTypeBasicLit       = "BasicLit"
	NodeTypeFuncLit        = "FuncLit"
	NodeTypeCompositeLit   = "CompositeLit"
	NodeTypeField          = "Field"
	NodeTypeFieldList      = "FieldList"
	NodeTypeEllipsis       = "Ellipsis"
	NodeTypeBadExpr        = "BadExpr"
	NodeTypeParenExpr      = "ParenExpr"
	NodeTypeSelectorExpr   = "SelectorExpr"
	NodeTypeIndexExpr      = "IndexExpr"
	NodeTypeIndexListExpr  = "IndexListExpr"
	NodeTypeSliceExpr      = "SliceExpr"
	NodeTypeTypeAssertExpr = "TypeAssertExpr"
	NodeTypeCallExpr       = "CallExpr"
	NodeTypeStarExpr       = "StarExpr"
	NodeTypeUnaryExpr      = "UnaryExpr"
	NodeTypeBinaryExpr     = "BinaryExpr"
	NodeTypeKeyValueExpr   = "KeyValueExpr"
	NodeTypeArrayType      = "ArrayType"
	NodeTypeStructType     = "StructType"
	NodeTypeFuncType       = "FuncType"
	NodeTypeInterfaceType  = "InterfaceType"
	NodeTypeMapType        = "MapType"
	NodeTypeChanType       = "ChanType"
	NodeTypeBadStmt        = "BadStmt"
	NodeTypeDeclStmt       = "DeclStmt"
	NodeTypeEmptyStmt      = "EmptyStmt"
	NodeTypeLabeledStmt    = "LabeledStmt"
	NodeTypeExprStmt       = "ExprStmt"
	NodeTypeSendStmt       = "SendStmt"
	NodeTypeIncDecStmt     = "IncDecStmt"
	NodeTypeAssignStmt     = "AssignStmt"
	NodeTypeGoStmt         = "GoStmt"
	NodeTypeDeferStmt      = "DeferStmt"
	NodeTypeReturnStmt     = "ReturnStmt"
	NodeTypeBranchStmt     = "BranchStmt"
	NodeTypeBlockStmt      = "BlockStmt"
	NodeTypeIfStmt         = "IfStmt"
	NodeTypeCaseClause     = "CaseClause"
	NodeTypeSwitchStmt     = "SwitchStmt"
	NodeTypeTypeSwitchStmt = "TypeSwitchStmt"
	NodeTypeCommClause     = "CommClause"
	NodeTypeSelectStmt     = "SelectStmt"
	NodeTypeForStmt        = "ForStmt"
	NodeTypeRangeStmt      = "RangeStmt"
	NodeTypeImportSpec     = "ImportSpec"
	NodeTypeValueSpec      = "ValueSpec"
	NodeTypeTypeSpec       = "TypeSpec"
	NodeTypeGenDecl        = "GenDecl"
	NodeTypeBadDecl        = "BadDecl"
	NodeTypeFuncDecl       = "FuncDecl"
)

NodeType constants define the string representation of various AST node types.

Variables

This section is empty.

Functions

func DeRefLookup

func DeRefLookup[I Ason, O ast.Node](pass *dePass, input I, deFn DeFn[I, O]) O

func DeserializeArrayType

func DeserializeArrayType(pass *dePass, input *ArrayType) *ast.ArrayType

func DeserializeAssignStmt

func DeserializeAssignStmt(pass *dePass, input *AssignStmt) *ast.AssignStmt

func DeserializeBadDecl

func DeserializeBadDecl(pass *dePass, input *BadDecl) *ast.BadDecl

func DeserializeBadExpr

func DeserializeBadExpr(pass *dePass, input *BadExpr) *ast.BadExpr

func DeserializeBadStmt

func DeserializeBadStmt(pass *dePass, input *BadStmt) *ast.BadStmt

func DeserializeBasicLit

func DeserializeBasicLit(pass *dePass, input *BasicLit) *ast.BasicLit

func DeserializeBinaryExpr

func DeserializeBinaryExpr(pass *dePass, input *BinaryExpr) *ast.BinaryExpr

func DeserializeBlockStmt

func DeserializeBlockStmt(pass *dePass, input *BlockStmt) *ast.BlockStmt

func DeserializeBranchStmt

func DeserializeBranchStmt(pass *dePass, input *BranchStmt) *ast.BranchStmt

func DeserializeCallExpr

func DeserializeCallExpr(pass *dePass, input *CallExpr) *ast.CallExpr

func DeserializeCaseClause

func DeserializeCaseClause(pass *dePass, input *CaseClause) *ast.CaseClause

func DeserializeChanType

func DeserializeChanType(pass *dePass, input *ChanType) *ast.ChanType

func DeserializeCommClause

func DeserializeCommClause(pass *dePass, input *CommClause) *ast.CommClause

func DeserializeComment

func DeserializeComment(pass *dePass, input *Comment) *ast.Comment

func DeserializeCommentGroup

func DeserializeCommentGroup(pass *dePass, input *CommentGroup) *ast.CommentGroup

func DeserializeCompositeLit

func DeserializeCompositeLit(pass *dePass, input *CompositeLit) *ast.CompositeLit

func DeserializeDecl

func DeserializeDecl(pass *dePass, decl Decl) ast.Decl

func DeserializeDeclStmt

func DeserializeDeclStmt(pass *dePass, input *DeclStmt) *ast.DeclStmt

func DeserializeDeferStmt

func DeserializeDeferStmt(pass *dePass, input *DeferStmt) *ast.DeferStmt

func DeserializeEllipsis

func DeserializeEllipsis(pass *dePass, input *Ellipsis) *ast.Ellipsis

func DeserializeEmptyStmt

func DeserializeEmptyStmt(pass *dePass, input *EmptyStmt) *ast.EmptyStmt

func DeserializeExpr

func DeserializeExpr(pass *dePass, expr Expr) ast.Expr

func DeserializeExprStmt

func DeserializeExprStmt(pass *dePass, input *ExprStmt) *ast.ExprStmt

func DeserializeField

func DeserializeField(pass *dePass, input *Field) *ast.Field

func DeserializeFieldList

func DeserializeFieldList(pass *dePass, input *FieldList) *ast.FieldList

func DeserializeFile

func DeserializeFile(pass *dePass, input *File) (*ast.File, error)

func DeserializeForStmt

func DeserializeForStmt(pass *dePass, input *ForStmt) *ast.ForStmt

func DeserializeFuncDecl

func DeserializeFuncDecl(pass *dePass, input *FuncDecl) *ast.FuncDecl

func DeserializeFuncLit

func DeserializeFuncLit(pass *dePass, input *FuncLit) *ast.FuncLit

func DeserializeFuncType

func DeserializeFuncType(pass *dePass, input *FuncType) *ast.FuncType

func DeserializeGenDecl

func DeserializeGenDecl(pass *dePass, input *GenDecl) *ast.GenDecl

func DeserializeGoStmt

func DeserializeGoStmt(pass *dePass, input *GoStmt) *ast.GoStmt

func DeserializeIdent

func DeserializeIdent(pass *dePass, input *Ident) *ast.Ident

func DeserializeIfStmt

func DeserializeIfStmt(pass *dePass, input *IfStmt) *ast.IfStmt

func DeserializeImportSpec

func DeserializeImportSpec(pass *dePass, input *ImportSpec) *ast.ImportSpec

func DeserializeIncDecStmt

func DeserializeIncDecStmt(pass *dePass, input *IncDecStmt) *ast.IncDecStmt

func DeserializeIndexExpr

func DeserializeIndexExpr(pass *dePass, input *IndexExpr) *ast.IndexExpr

func DeserializeIndexListExpr

func DeserializeIndexListExpr(pass *dePass, input *IndexListExpr) *ast.IndexListExpr

func DeserializeInterfaceType

func DeserializeInterfaceType(pass *dePass, input *InterfaceType) *ast.InterfaceType

func DeserializeKeyValueExpr

func DeserializeKeyValueExpr(pass *dePass, input *KeyValueExpr) *ast.KeyValueExpr

func DeserializeLabeledStmt

func DeserializeLabeledStmt(pass *dePass, input *LabeledStmt) *ast.LabeledStmt

func DeserializeList

func DeserializeList[I Ason, R ast.Node](pass *dePass, inputList []I, deFn DeFn[I, R]) (result []R)

func DeserializeMapType

func DeserializeMapType(pass *dePass, input *MapType) *ast.MapType

func DeserializeOption

func DeserializeOption[I Ason, R ast.Node](pass *dePass, input I, deFn DeFn[I, R]) (empty R)

func DeserializeParenExpr

func DeserializeParenExpr(pass *dePass, input *ParenExpr) *ast.ParenExpr

func DeserializePos

func DeserializePos(pass *dePass, input Pos) token.Pos

func DeserializeRangeStmt

func DeserializeRangeStmt(pass *dePass, input *RangeStmt) *ast.RangeStmt

func DeserializeReturnStmt

func DeserializeReturnStmt(pass *dePass, input *ReturnStmt) *ast.ReturnStmt

func DeserializeSelectStmt

func DeserializeSelectStmt(pass *dePass, input *SelectStmt) *ast.SelectStmt

func DeserializeSelectorExpr

func DeserializeSelectorExpr(pass *dePass, input *SelectorExpr) *ast.SelectorExpr

func DeserializeSendStmt

func DeserializeSendStmt(pass *dePass, input *SendStmt) *ast.SendStmt

func DeserializeSliceExpr

func DeserializeSliceExpr(pass *dePass, input *SliceExpr) *ast.SliceExpr

func DeserializeSpec

func DeserializeSpec(pass *dePass, spec Spec) ast.Spec

func DeserializeStarExpr

func DeserializeStarExpr(pass *dePass, input *StarExpr) *ast.StarExpr

func DeserializeStmt

func DeserializeStmt(pass *dePass, stmt Stmt) ast.Stmt

func DeserializeStructType

func DeserializeStructType(pass *dePass, input *StructType) *ast.StructType

func DeserializeSwitchStmt

func DeserializeSwitchStmt(pass *dePass, input *SwitchStmt) *ast.SwitchStmt

func DeserializeTypeAssertExpr

func DeserializeTypeAssertExpr(pass *dePass, input *TypeAssertExpr) *ast.TypeAssertExpr

func DeserializeTypeSpec

func DeserializeTypeSpec(pass *dePass, input *TypeSpec) *ast.TypeSpec

func DeserializeTypeSwitchStmt

func DeserializeTypeSwitchStmt(pass *dePass, input *TypeSwitchStmt) *ast.TypeSwitchStmt

func DeserializeUnaryExpr

func DeserializeUnaryExpr(pass *dePass, input *UnaryExpr) *ast.UnaryExpr

func DeserializeValueSpec

func DeserializeValueSpec(pass *dePass, input *ValueSpec) *ast.ValueSpec

func IsPosValid

func IsPosValid(pos Pos) bool

Checking whether the position exists.

func NewDePass

func NewDePass(fset *token.FileSet) *dePass

func NewSerPass

func NewSerPass(fset *token.FileSet, options ...Mode) *serPass

func NewWeakRef

func NewWeakRef(v interface{}) *weakRef

func SerRefLookup

func SerRefLookup[I ast.Node, O Ason](pass *serPass, input I, serFn SerFn[I, O]) O

func SerializeList

func SerializeList[I ast.Node, R Ason](pass *serPass, inputList []I, serFn SerFn[I, R]) (result []R)

func SerializeMap

func SerializeMap[K comparable, V ast.Node, R Ason](pass *serPass, inputMap map[K]V, serFn SerFn[V, R]) map[K]R

func SerializeOption

func SerializeOption[I ast.Node, R Ason](pass *serPass, input I, serFn SerFn[I, R]) (empty R)

Types

type ArrayType

type ArrayType struct {
	Lbrack Pos  // position of "["
	Len    Expr // Ellipsis node for [...]T array types, nil for slice types
	Elt    Expr // element type

	Node
}

An ArrayType node represents an array or slice type.

func SerializeArrayType

func SerializeArrayType(pass *serPass, input *ast.ArrayType) *ArrayType

type Ason

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

type AssignStmt

type AssignStmt struct {
	Lhs    []Expr
	TokPos Pos    // position of Tok
	Tok    string // assignment token, DEFINE
	Rhs    []Expr

	Node
}

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

func SerializeAssignStmt

func SerializeAssignStmt(pass *serPass, input *ast.AssignStmt) *AssignStmt

type BadDecl

type BadDecl struct {
	From, To Pos // position range of bad declaration

	Node
}

A BadDecl node is a placeholder for a declaration containing syntax errors for which a correct declaration node cannot be created.

func SerializeBadDecl

func SerializeBadDecl(pass *serPass, input *ast.BadDecl) *BadDecl

type BadExpr

type BadExpr struct {
	From, To Pos // position range of bad expression

	Node
}

A BadExpr node is a placeholder for an expression containing syntax errors for which a correct expression node cannot be created.

func SerializeBadExpr

func SerializeBadExpr(pass *serPass, input *ast.BadExpr) *BadExpr

type BadStmt

type BadStmt struct {
	From, To Pos // position range of bad statement

	Node
}

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

func SerializeBadStmt

func SerializeBadStmt(pass *serPass, input *ast.BadStmt) *BadStmt

type BasicLit

type BasicLit struct {
	ValuePos Pos    // literal position
	Kind     string // 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`

	Node
}

A BasicLit node represents a literal of basic type.

func SerializeBasicLit

func SerializeBasicLit(pass *serPass, input *ast.BasicLit) *BasicLit

type BinaryExpr

type BinaryExpr struct {
	X     Expr   // left operand
	OpPos Pos    // position of Op
	Op    string // operator (token)
	Y     Expr   // right operand

	Node
}

A BinaryExpr node represents a binary expression.

func SerializeBinaryExpr

func SerializeBinaryExpr(pass *serPass, input *ast.BinaryExpr) *BinaryExpr

type BlockStmt

type BlockStmt struct {
	Lbrace Pos // position of "{"
	List   []Stmt
	Rbrace Pos // position of "}", if any (may be absent due to syntax error)

	Node
}

A BlockStmt node represents a braced statement list.

func SerializeBlockStmt

func SerializeBlockStmt(pass *serPass, input *ast.BlockStmt) *BlockStmt

type BranchStmt

type BranchStmt struct {
	TokPos Pos    // position of Tok
	Tok    string // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH)
	Label  *Ident // label name; or nil

	Node
}

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

func SerializeBranchStmt

func SerializeBranchStmt(pass *serPass, input *ast.BranchStmt) *BranchStmt

type CallExpr

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

	Node
}

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

func SerializeCallExpr

func SerializeCallExpr(pass *serPass, input *ast.CallExpr) *CallExpr

type CaseClause

type CaseClause struct {
	Case  Pos    // position of "case" or "default" keyword
	List  []Expr // list of expressions or types; nil means default case
	Colon Pos    // position of ":"
	Body  []Stmt // statement list; or nil

	Node
}

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

func SerializeCaseClause

func SerializeCaseClause(pass *serPass, input *ast.CaseClause) *CaseClause

type ChanType

type ChanType struct {
	Begin Pos  // position of "chan" keyword or "<-" (whichever comes first)
	Arrow Pos  // position of "<-" (token.NoPos if there is no "<-")
	Dir   int  // channel direction
	Value Expr // value type

	Node
}

A ChanType node represents a channel type.

func SerializeChanType

func SerializeChanType(pass *serPass, input *ast.ChanType) *ChanType

type CommClause

type CommClause struct {
	Case  Pos    // position of "case" or "default" keyword
	Comm  Stmt   // send or receive statement; nil means default case
	Colon Pos    // position of ":"
	Body  []Stmt // statement list; or nil

	Node
}

A CommClause node represents a case of a select statement.

func SerializeCommClause

func SerializeCommClause(pass *serPass, input *ast.CommClause) *CommClause

type Comment

type Comment struct {
	Slash Pos    // position of "/" starting the comment
	Text  string // comment text (excluding '\n' for //-style comments)

	Node
}

func SerializeComment

func SerializeComment(pass *serPass, input *ast.Comment) *Comment

type CommentGroup

type CommentGroup struct {
	List []*Comment

	Node
}

A CommentGroup represents a sequence of comments with no other tokens and no empty lines between.

func SerializeCommentGroup

func SerializeCommentGroup(pass *serPass, input *ast.CommentGroup) *CommentGroup

type CompositeLit

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

	Node
}

A CompositeLit node represents a composite literal.

func SerializeCompositeLit

func SerializeCompositeLit(pass *serPass, input *ast.CompositeLit) *CompositeLit

type DeFn

type DeFn[I Ason, O ast.Node] func(*dePass, I) O

type Decl

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

func SerializeDecl

func SerializeDecl(pass *serPass, decl ast.Decl) Decl

type DeclStmt

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

	Node
}

A DeclStmt node represents a declaration in a statement list.

func SerializeDeclStmt

func SerializeDeclStmt(pass *serPass, input *ast.DeclStmt) *DeclStmt

type DeferStmt

type DeferStmt struct {
	Defer Pos // position of "defer" keyword
	Call  *CallExpr

	Node
}

A DeferStmt node represents a defer statement.

func SerializeDeferStmt

func SerializeDeferStmt(pass *serPass, input *ast.DeferStmt) *DeferStmt

type Ellipsis

type Ellipsis struct {
	Ellipsis Pos  // position of "..."
	Elt      Expr // ellipsis element type (parameter lists only); or nil

	Node
}

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

func SerializeEllipsis

func SerializeEllipsis(pass *serPass, input *ast.Ellipsis) *Ellipsis

type EmptyStmt

type EmptyStmt struct {
	Semicolon Pos  // position of following ";"
	Implicit  bool // if set, ";" was omitted in the source

	Node
}

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

func SerializeEmptyStmt

func SerializeEmptyStmt(pass *serPass, input *ast.EmptyStmt) *EmptyStmt

type Expr

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

func SerializeExpr

func SerializeExpr(pass *serPass, expr ast.Expr) Expr

type ExprStmt

type ExprStmt struct {
	X Expr // expression

	Node
}

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

func SerializeExprStmt

func SerializeExprStmt(pass *serPass, input *ast.ExprStmt) *ExprStmt

type Field

type Field struct {
	Doc     *CommentGroup // associated documentation; or nil
	Names   []*Ident      // field/method/(type) parameter names; or nil
	Type    Expr          // field/method/parameter type; or nil
	Tag     *BasicLit     // field tag; or nil
	Comment *CommentGroup // line comments; or nil

	Node
}

func SerializeField

func SerializeField(pass *serPass, input *ast.Field) *Field

type FieldList

type FieldList struct {
	Opening Pos      // position of opening parenthesis/brace/bracket, if any
	List    []*Field // field list; or nil
	Closing Pos      // position of closing parenthesis/brace/bracket, if any

	Node
}

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

func SerializeFieldList

func SerializeFieldList(pass *serPass, input *ast.FieldList) *FieldList

type File

type File struct {
	Doc                *CommentGroup   // associated documentation; or empty
	Name               *Ident          // package name
	Decls              []Decl          // top-level declarations
	Size               int             // file size in bytes
	FileStart, FileEnd Pos             // start and end of entire file
	Scope              *Scope          // package scope (this file only)
	Imports            []*ImportSpec   // imports in this file
	Unresolved         []*Ident        // unresolved identifiers in this file
	Package            Pos             // position of "package" keyword
	Comments           []*CommentGroup // list of all comments in the source file
	GoVersion          string          // minimum Go version required by go:build or +build directives

	Node
}

A File node represents a Go source file.

func SerializeFile

func SerializeFile(pass *serPass, input *ast.File) *File

type ForStmt

type ForStmt struct {
	For  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

	Node
}

A ForStmt represents a for statement.

func SerializeForStmt

func SerializeForStmt(pass *serPass, input *ast.ForStmt) *ForStmt

type FuncDecl

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: type and value parameters, results, and position of "func" keyword
	Body *BlockStmt    // function body; or nil for external (non-Go) function

	Node
}

A FuncDecl node represents a function declaration.

func SerializeFuncDecl

func SerializeFuncDecl(pass *serPass, input *ast.FuncDecl) *FuncDecl

type FuncLit

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

	Node
}

A FuncLit node represents a function literal.

func SerializeFuncLit

func SerializeFuncLit(pass *serPass, input *ast.FuncLit) *FuncLit

type FuncType

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

	Node
}

A FuncType node represents a function type.

func SerializeFuncType

func SerializeFuncType(pass *serPass, input *ast.FuncType) *FuncType

type GenDecl

type GenDecl struct {
	Doc      *CommentGroup // associated documentation; or nil
	TokenPos Pos           // position of Tok
	Tok      string        // IMPORT, CONST, TYPE, or VAR
	Lparen   Pos           // position of '(', if any
	Specs    []Spec
	Rparen   Pos // position of ')', if any

	Node
}

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

func SerializeGenDecl

func SerializeGenDecl(pass *serPass, input *ast.GenDecl) *GenDecl

type GoStmt

type GoStmt struct {
	Go   Pos // position of "go" keyword
	Call *CallExpr

	Node
}

A GoStmt node represents a go statement.

func SerializeGoStmt

func SerializeGoStmt(pass *serPass, input *ast.GoStmt) *GoStmt

type Ident

type Ident struct {
	NamePos Pos     // identifier position
	Name    string  // identifier name
	Obj     *Object // denoted object; or nil

	Node
}

An Ident node represents an identifier.

func SerializeIdent

func SerializeIdent(pass *serPass, input *ast.Ident) *Ident

type IfStmt

type IfStmt struct {
	If   Pos  // position of "if" keyword
	Init Stmt // initialization statement; or nil
	Cond Expr // condition
	Body *BlockStmt
	Else Stmt // else branch; or nil

	Node
}

An IfStmt node represents an if statement.

func SerializeIfStmt

func SerializeIfStmt(pass *serPass, input *ast.IfStmt) *IfStmt

type 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  Pos           // end of spec (overrides Path.Pos if nonzero)

	Node
}

An ImportSpec node represents a single package import.

func SerializeImportSpec

func SerializeImportSpec(pass *serPass, input *ast.ImportSpec) *ImportSpec

type IncDecStmt

type IncDecStmt struct {
	X      Expr
	TokPos Pos    // position of Tok
	Tok    string // INC or DEC

	Node
}

An IncDecStmt node represents an increment or decrement statement.

func SerializeIncDecStmt

func SerializeIncDecStmt(pass *serPass, input *ast.IncDecStmt) *IncDecStmt

type IndexExpr

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

	Node
}

An IndexExpr node represents an expression followed by an index.

func SerializeIndexExpr

func SerializeIndexExpr(pass *serPass, input *ast.IndexExpr) *IndexExpr

type IndexListExpr

type IndexListExpr struct {
	X       Expr   // expression
	Lbrack  Pos    // position of "["
	Indices []Expr // index expressions
	Rbrack  Pos    // position of "]"

	Node
}

An IndexListExpr node represents an expression followed by multiple indices.

func SerializeIndexListExpr

func SerializeIndexListExpr(pass *serPass, input *ast.IndexListExpr) *IndexListExpr

type InterfaceType

type InterfaceType struct {
	Interface  Pos        // position of "interface" keyword
	Methods    *FieldList // list of embedded interfaces, methods, or types
	Incomplete bool       // true if (source) methods or types are missing in the Methods list

	Node
}

An InterfaceType node represents an interface type.

func SerializeInterfaceType

func SerializeInterfaceType(pass *serPass, input *ast.InterfaceType) *InterfaceType

type KeyValueExpr

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

	Node
}

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

func SerializeKeyValueExpr

func SerializeKeyValueExpr(pass *serPass, input *ast.KeyValueExpr) *KeyValueExpr

type LabeledStmt

type LabeledStmt struct {
	Label *Ident
	Colon Pos // position of ":"
	Stmt  Stmt

	Node
}

A LabeledStmt node represents a labeled statement.

func SerializeLabeledStmt

func SerializeLabeledStmt(pass *serPass, input *ast.LabeledStmt) *LabeledStmt

type Loc

type Loc struct {
	Start Pos `json:"Start"`
	End   Pos `json:"End"`
	// contains filtered or unexported fields
}

func SerializeLoc

func SerializeLoc(pass *serPass, input ast.Node) *Loc

type MapType

type MapType struct {
	Map   Pos // position of "map" keyword
	Key   Expr
	Value Expr

	Node
}

A MapType node represents a map type.

func SerializeMapType

func SerializeMapType(pass *serPass, input *ast.MapType) *MapType

type Mode

type Mode int
const (
	Default Mode = iota

	// Cache large nodes. Use this mode when you carry out some
	// manual manipulations with the source AST tree. For example,
	// you duplicate nodes, which can create nodes that have the
	// same references to the original object in memory. Only
	// large nodes can be cached, such as specifications, types
	// and declarations.
	CacheRef

	// SkipComments will not serialize any comments declarations
	SkipComments

	// ResolveObject identifiers to objects
	ResolveObject

	// ResolveScope file and package scope and identifiers objects
	ResolveScope

	// ResolveLoc allow to resolve start and end position for
	// all AST nodes.
	ResolveLoc
)

type NoPos

type NoPos int

func (*NoPos) Column

func (*NoPos) Column() int

func (*NoPos) Line

func (*NoPos) Line() int

func (*NoPos) Offset

func (*NoPos) Offset() int

type Node

type Node struct {
	Ref  uint   `json:"_ref"`
	Type string `json:"_type"`
	Loc  *Loc   `json:"_loc"`
}

type Object

type Object struct {
	Kind string
	Name string // declared name
}

func SerializeObject

func SerializeObject(pass *serPass, input *ast.Object) *Object

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 SerializePackage

func SerializePackage(pass *serPass, input *ast.Package) *Package

type ParenExpr

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

	Node
}

A ParenExpr node represents a parenthesized expression.

func SerializeParenExpr

func SerializeParenExpr(pass *serPass, input *ast.ParenExpr) *ParenExpr

type Pos

type Pos interface {
	// Offset is an absolute position of a character in the file text.
	Offset() int
	// Line is a line number in the file where this piece of code is located.
	Line() int
	// Column ia s character position in a specific line, starting from zero.
	Column() int
}

func SerializePos

func SerializePos(pass *serPass, pos token.Pos) Pos

type Position

type Position struct {
	Location [3]int // set of coordinates used to indicate a specific location in the source code; the order is `Offset`, `Line`, `Column`
	Filename string
}

func NewPosition

func NewPosition(pos token.Position) *Position

func (*Position) Column

func (p *Position) Column() int

func (*Position) Line

func (p *Position) Line() int

func (*Position) Offset

func (p *Position) Offset() int

type RangeStmt

type RangeStmt struct {
	For        Pos    // position of "for" keyword
	Key, Value Expr   // Key, Value may be nil
	TokPos     Pos    // position of Tok; invalid if Key == nil
	Tok        string // ILLEGAL if Key == nil, ASSIGN, DEFINE
	Range      Pos    // position of "range" keyword
	X          Expr   // value to range over
	Body       *BlockStmt

	Node
}

A RangeStmt represents a for statement with a range clause.

func SerializeRangeStmt

func SerializeRangeStmt(pass *serPass, input *ast.RangeStmt) *RangeStmt

type ReturnStmt

type ReturnStmt struct {
	Return  Pos    // position of "return" keyword
	Results []Expr // result expressions; or nil

	Node
}

A ReturnStmt node represents a return statement.

func SerializeReturnStmt

func SerializeReturnStmt(pass *serPass, input *ast.ReturnStmt) *ReturnStmt

type Scope

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

func SerializeScope

func SerializeScope(pass *serPass, input *ast.Scope) *Scope

type SelectStmt

type SelectStmt struct {
	Select Pos        // position of "select" keyword
	Body   *BlockStmt // CommClauses only

	Node
}

A SelectStmt node represents a select statement.

func SerializeSelectStmt

func SerializeSelectStmt(pass *serPass, input *ast.SelectStmt) *SelectStmt

type SelectorExpr

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

	Node
}

A SelectorExpr node represents an expression followed by a selector.

func SerializeSelectorExpr

func SerializeSelectorExpr(pass *serPass, input *ast.SelectorExpr) *SelectorExpr

type SendStmt

type SendStmt struct {
	Chan  Expr
	Arrow Pos // position of "<-"
	Value Expr

	Node
}

A SendStmt node represents a send statement.

func SerializeSendStmt

func SerializeSendStmt(pass *serPass, input *ast.SendStmt) *SendStmt

type SerFn

type SerFn[I ast.Node, O Ason] func(*serPass, I) O

type SliceExpr

type SliceExpr struct {
	X      Expr // expression
	Lbrack 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
	Slice3 bool // true if 3-index slice (2 colons present)
	Rbrack Pos  // position of "]"

	Node
}

A SliceExpr node represents an expression followed by slice indices.

func SerializeSliceExpr

func SerializeSliceExpr(pass *serPass, input *ast.SliceExpr) *SliceExpr

type Spec

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

func SerializeSpec

func SerializeSpec(pass *serPass, spec ast.Spec) Spec

type StarExpr

type StarExpr struct {
	Star Pos  // position of "*"
	X    Expr // operand

	Node
}

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

func SerializeStarExpr

func SerializeStarExpr(pass *serPass, input *ast.StarExpr) *StarExpr

type Stmt

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

func SerializeStmt

func SerializeStmt(pass *serPass, stmt ast.Stmt) Stmt

type StructType

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

	Node
}

A StructType node represents a struct type.

func SerializeStructType

func SerializeStructType(pass *serPass, input *ast.StructType) *StructType

type SwitchStmt

type SwitchStmt struct {
	Switch Pos        // position of "switch" keyword
	Init   Stmt       // initialization statement; or nil
	Tag    Expr       // tag expression; or nil
	Body   *BlockStmt // CaseClauses only

	Node
}

A SwitchStmt node represents an expression switch statement.

func SerializeSwitchStmt

func SerializeSwitchStmt(pass *serPass, input *ast.SwitchStmt) *SwitchStmt

type TypeAssertExpr

type TypeAssertExpr struct {
	X      Expr // expression
	Lparen Pos  // position of "("
	Type   Expr // asserted type; nil means type switch X.(type)
	Rparen Pos  // position of ")"

	Node
}

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

func SerializeTypeAssertExpr

func SerializeTypeAssertExpr(pass *serPass, input *ast.TypeAssertExpr) *TypeAssertExpr

type TypeSpec

type TypeSpec struct {
	Doc        *CommentGroup // associated documentation; or nil
	Name       *Ident        // type name
	TypeParams *FieldList    // type parameters; or nil
	Assign     Pos           // position of '=', if any
	Type       Expr          // *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes
	Comment    *CommentGroup // line comments; or nil

	Node
}

A TypeSpec node represents a type declaration.

func SerializeTypeSpec

func SerializeTypeSpec(pass *serPass, input *ast.TypeSpec) *TypeSpec

type TypeSwitchStmt

type TypeSwitchStmt struct {
	Switch Pos        // position of "switch" keyword
	Init   Stmt       // initialization statement; or nil
	Assign Stmt       // x := y.(type) or y.(type)
	Body   *BlockStmt // CaseClauses only

	Node
}

A TypeSwitchStmt node represents a type switch statement.

func SerializeTypeSwitchStmt

func SerializeTypeSwitchStmt(pass *serPass, input *ast.TypeSwitchStmt) *TypeSwitchStmt

type UnaryExpr

type UnaryExpr struct {
	OpPos Pos    // position of Op
	Op    string // operator (token)
	X     Expr   // operand

	Node
}

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

func SerializeUnaryExpr

func SerializeUnaryExpr(pass *serPass, input *ast.UnaryExpr) *UnaryExpr

type ValueSpec

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

	Node
}

A ValueSpec node represents a constant or variable declaration

func SerializeValueSpec

func SerializeValueSpec(pass *serPass, input *ast.ValueSpec) *ValueSpec

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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