| description | CodeQL AST class reference for Go programs |
|---|
Write CodeQL queries over Go by navigating the Go AST classes. Model: Syntax → CodeQL class hierarchy; use predicates to access parts (condition, body, operands). Pattern: get<Part>(), getA<Part>(), get<Left/Right>Operand>(), getAnArgument(), getCallee().
- Statements: subclasses of
Stmt - Expressions: subclasses of
Expr(literals, unary, binary, calls, selectors, etc.) - Declarations:
FuncDecl,GenDecl(+ImportSpec,TypeSpec,ValueSpec) - Types:
TypeExprnodes (ArrayTypeExpr,StructTypeExpr,FuncTypeExpr,InterfaceTypeExpr,MapTypeExpr,ChanTypeExprvariants) - Names/Selectors:
SimpleName,SelectorExpr; Name hierarchy:PackageName,TypeName,ValueName,LabelName
EmptyStmt- Empty statement ";"ExprStmt- Expression used as statementBlockStmt- Block statement "{…}"DeclStmt- Declaration statement
IfStmt- if condition then [else]; supports init; Then/Else are blocks or statementsgetCondition(),getThen(),getElse(),getInit()
ForStmt- Classic init/cond/post;LoopStmtsuperclassgetInit(),getCondition(),getPost(),getBody()
RangeStmt- "for k,v := range expr { … }"getKey(),getValue(),getDomain(),getBody()
SwitchStmt/ExpressionSwitchStmt- Expression-based switchTypeSwitchStmt- Type-based switchCaseClause- Case clause inside switch statementsgetExpr(i),getStmt(i)
SelectStmt- Select statement for channel operationsCommClause- Communication clause in select statement
SendStmt- Channel send "ch <- x"RecvStmt- Channel receive "x = <-ch"GoStmt- Goroutine launch "go f()"DeferStmt- Deferred function call "defer f()"
SimpleAssignStmt- Simple assignment "="DefineStmt- Short variable declaration ":="CompoundAssignStmt- Compound assignment (+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, &^=)IncStmt- Increment "x++"DecStmt- Decrement "x--"
LabeledStmt- Labeled statementBreakStmt- Break statementContinueStmt- Continue statementGotoStmt- Goto statementFallthroughStmt- Fallthrough statementReturnStmt- Return statementgetResult(i)to access return values
BasicLitsubclasses:IntLit- Integer literalFloatLit- Floating point literalImagLit- Imaginary literalCharLit/RuneLit- Character/rune literalStringLit- String literal
CompositeLit- Composite literals:StructLit- Struct literal "T{…}"MapLit- Map literal "map[K]V{…}"
FuncLit- Function literal (anonymous function)
PlusExpr- Unary plus "+x"MinusExpr- Unary minus "-x"NotExpr- Logical not "!x"ComplementExpr- Bitwise complement "^x"AddressExpr- Address-of "&x"RecvExpr- Channel receive "<-x"
- Arithmetic:
MulExpr,QuoExpr,RemExpr,AddExpr,SubExpr - Shift:
ShlExpr"<<",ShrExpr">>" - Logical:
LandExpr"&&",LorExpr"||" - Relational:
LssExpr"<",GtrExpr">",LeqExpr"<=",GeqExpr">=" - Equality:
EqlExpr"==",NeqExpr"!=" - Bitwise:
AndExpr"&",OrExpr"|",XorExpr"^",AndNotExpr"&^"
SelectorExpr- Field/method access "X.Y"getBase(),getSelector()
CallExpr- Function/method callgetCallee(),getAnArgument(),getArgument(i)
IndexExpr- Array/slice/map index "a[i]"SliceExpr- Slice expression "a[i:j:k]"KeyValueExpr- Key-value pair in composite literals
ParenExpr- Parenthesized expressionStarExpr- Pointer dereference/typeTypeAssertExpr- Type assertion "x.(T)"Conversion- Type conversion "T(x)"
ArrayTypeExpr- Array type "[N]T" or slice type "[]T"StructTypeExpr- Struct type "struct{…}"FuncTypeExpr- Function type "func(…) …"InterfaceTypeExpr- Interface typeMapTypeExpr- Map typeChanTypeExprvariants:SendChanTypeExpr- Send-only channelRecvChanTypeExpr- Receive-only channelSendRecvChanTypeExpr- Bidirectional channel
Namesubclasses:SimpleName- Simple identifierQualifiedName- Package-qualified name
ValueNamesubclasses:ConstantName- Constant identifierVariableName- Variable identifierFunctionName- Function identifier
PackageName- Package name identifierTypeName- Type name identifierLabelName- Label identifier
FuncDecl/FuncLitviaFuncDef:getBody(),getName(),getParameter(i),getResultVar(i),getACall()
GenDeclwith:ImportSpec- Import specificationTypeSpec- Type specificationValueSpec- Variable/constant specification
Field/FieldList- For parameters, results, struct/interface fields
- If statements:
getCondition(),getThen(),getElse() - For/Range loops: inspect
getInit()/getCondition()/getPost()or range expression - Switch statements: use
CaseClause,getExpr(i)/getStmt(i) - Select statements: use
CommClause
// Method calls by name
from CallExpr call, SelectorExpr sel
where call.getCallee() = sel and sel.getMemberName() = "Close"
select call
// Method vs function calls
// SelectorExpr callee = method call
// SimpleName callee = function call- Assignment: match
AssignStmtsubclasses - Short variable declaration:
DefineStmtfor ":=" - Compound assignment:
CompoundAssignStmtfor "+=", etc.
- Use specific subclasses or operator accessors
- Access operands via
getLeftOperand(),getRightOperand()
- Basic literals: filter
BasicLitsubclasses - Composite literals:
CompositeLitelements via keys/values - Struct literals:
StructLitwith type information
// Range over map/slice
from RangeStmt r select r
// Defer calls
from DeferStmt d, CallExpr c
where d.getExpr() = c
select d, c
// Struct literal of specific type
from StructLit lit
where lit.getType().getName() = "Point"
select lit
// Channel operations
from SendStmt s select s // ch <- x
from RecvStmt r select r // x = <-ch// Find method calls on specific receiver types
from CallExpr call, SelectorExpr sel
where call.getCallee() = sel and
sel.getBase().getType().toString() = "MyType"
select callGoFile- Represents a Go source fileGoModFile- Represents a go.mod fileGoModModuleLine- Module declaration in go.modGoModGoLine- Go version declaration in go.mod
CommentGroup- Group of related commentsDocComment- Documentation comment group (typically for functions/types)SlashSlashComment- Single-line comment (//) within comment groups
TypeParamDecl- Type parameter declaration with constraints- Generic type parameters and constraints for Go generics
- Support for type inference and constraint satisfaction
- Goroutines:
GoStmtfor "go f()" patterns - Channels:
SendStmt,RecvStmt,RecvExprfor channel operations - Select:
SelectStmtwithCommClausefor channel multiplexing - Defer:
DeferStmtfor cleanup patterns
- Class tests over string parsing: Use specific AST classes rather than string matching
- Type conversion disambiguation:
CallExprcallee is aTypeExprfor type conversions - Statement vs expression: Inc/Dec are statements, not expressions
- Assignment variants: Handle ":=" vs "=" separately with
DefineStmtvsSimpleAssignStmt - Error handling: Exclude
BadStmt/BadExprfrom analysis
- Control Flow: If→
IfStmt, For→ForStmt, Range→RangeStmt, Switch→SwitchStmt/ExpressionSwitchStmt, Type switch→TypeSwitchStmt, Select→SelectStmt - Cases: Case→
CaseClause, Select case→CommClause - Assignment:
=→SimpleAssignStmt,:=→DefineStmt,+=etc.→CompoundAssignStmt - Increment:
++→IncStmt,--→DecStmt - Access: Call→
CallExpr, Selector→SelectorExpr, Index→IndexExpr, Slice→SliceExpr - Type operations: Type assert→
TypeAssertExpr, Conversion→Conversion - Unary/Binary: Specific subclasses of
UnaryExpr/BinaryExpr - Literals:
IntLit,FloatLit,StringLit,StructLit,MapLit,FuncLit - Types:
ArrayTypeExpr,StructTypeExpr,FuncTypeExpr,InterfaceTypeExpr,MapTypeExpr,ChanTypeExpr
This repo contains a variant of the open-source PrintAst.ql query for go language, with modifications for local testing:
The following links can be fetched to get the expected results for different unit tests of the open-source PrintAst.ql query for the go language:
- library-tests/semmle/go/PrintAst/PrintAst.expected
- library-tests/semmle/go/PrintAst/PrintAstExcludeComments.expected
- library-tests/semmle/go/PrintAst/PrintAstNestedFunction.expected
- library-tests/semmle/go/PrintAst/PrintAstRestrictFile.expected
- library-tests/semmle/go/PrintAst/PrintAstRestrictFunction.expected