Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

🔍Type Assertions

In go-fAST, understanding the type of AST node you're working with is fundamental to writing effective visitors and transformations. Since the library is written in Go, it leverages Go's type system and interfaces to represent different nodes. To inspect and work with a specific node type, you'll use Go's built-in type assertions.

This guide explains how to:

  • Identify the type of an Expr or Stmt

  • Use type assertions for transformation and analysis

  • Understand the common AST node types you'll encounter


🧠 What Is a Type Assertion?

In Go, if you have an interface (like Expr or Stmt), and you want to know whether it holds a specific concrete type, you use a type assertion:

if ident, ok := expr.Expr.(*ast.Identifier); ok {
    fmt.Println("This is an identifier with name:", ident.Name)
}

If expr.Expr is a *ast.Identifier, the cast succeeds and ok is true. If not, ok will be false, and the cast fails gracefully.


✅ Checking for Expression Types

All expressions in go-fAST implement the ast.Expr interface. To check for specific types, you usually work through *ast.Expression wrappers:

type ExampleVisitor struct {
    ast.NoopVisitor
}

func (v *ExampleVisitor) VisitExpression(n *ast.Expression) {
    switch e := n.Expr.(type) {
    case *ast.CallExpression:
        fmt.Println("Found a function call:", e.Callee)
    case *ast.SequenceExpression:
        fmt.Println("This is a sequence of expressions.")
    case *ast.AssignExpression:
        fmt.Println("Assignment to:", e.Left)
    default:
        fmt.Println("Some other expression")
    }
}

Common expression types:

  • *ast.CallExpression

  • *ast.SequenceExpression

  • *ast.AssignExpression

  • *ast.Identifier

  • *ast.MemberExpression

  • *ast.NumberLiteral, *ast.StringLiteral, *ast.BooleanLiteral


📚 Full List of Statement Types (Stmt)

All statement nodes implement the Stmt interface. You can check for these types in visitors like VisitStatement, VisitStatements, or any higher-level node.

Node Type
Purpose

*BadStatement

Invalid syntax fragment

*BlockStatement

{ ... } code blocks

*BreakStatement

break

*ContinueStatement

continue

*CaseStatement

case clause inside switch

*CatchStatement

catch block inside try

*DebuggerStatement

debugger;

*DoWhileStatement

do { ... } while (...)

*EmptyStatement

; (no-op statement)

*ExpressionStatement

Expression as a statement

*ForStatement

for (;;) loop

*ForInStatement

for (x in y)

*ForOfStatement

for (x of y)

*IfStatement

if (...) ... else ...

*LabelledStatement

label: ...

*ReturnStatement

return ...;

*SwitchStatement

switch (...) { ... }

*ThrowStatement

throw ...;

*TryStatement

try { ... } catch { ... }

*WhileStatement

while (...) { ... }

*WithStatement

with (...) { ... }


🧠 Expression Types (Expr)

All expressions implement the Expr interface. These are the building blocks of values, calls, operations, etc.

Node Type
Description

*ArrayLiteral

[1, 2, 3]

*ArrowFunctionLiteral

(x) => x * 2

*AssignExpression

a = b or a += b

*AwaitExpression

await x

*BinaryExpression

a + b, a === b

*CallExpression

f(x)

*ConditionalExpression

a ? b : c

*InvalidExpression

Malformed expression

*MemberExpression

obj.prop or obj["prop"]

*MetaProperty

new.target, import.meta

*NewExpression

new Foo()

*ObjectLiteral

{ a: 1, b: 2 }

*PrivateDotExpression

this.#privateField

*PrivateIdentifier

#field

*SequenceExpression

(a, b, c)

*SpreadElement

...rest in arrays or objects

*SuperExpression

super.method()

*TemplateLiteral

`hello ${name}`

*ThisExpression

this

*UnaryExpression

!a, typeof x, -y

*UpdateExpression

++x, x--

*YieldExpression

yield x

*OptionalChain

obj?.prop

*Optional

Wrapper for optional expressions

*ArrayPattern

[a, b] = [1, 2]

*ObjectPattern

{a, b} = obj

*VariableDeclarator

var x = 1 (used inside declarations)

✅ Checking for Statement Types

Statements implement the ast.Stmt interface and are accessed via *ast.Statement nodes:

Common statement types:

  • *ast.ReturnStatement

  • *ast.ExpressionStatement

  • *ast.BlockStatement

  • *ast.IfStatement

  • *ast.ForStatement, *ast.WhileStatement

  • *ast.VariableDeclaration


🧩 Advanced Usage: Visitor Filtering

You can use assertions in your custom visitors to conditionally apply logic:


📚 Pro Tip: Create Helpers

You can abstract repeated checks into helpers:


Last updated