Skip to content

Commit

Permalink
Implementing nil as a literal in the Go language frontend (#897)
Browse files Browse the repository at this point in the history
Fixes #447
  • Loading branch information
oxisto committed Aug 30, 2022
1 parent 854252e commit 62885d0
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
13 changes: 11 additions & 2 deletions cpg-language-go/src/main/golang/frontend/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -1184,7 +1184,16 @@ func (this *GoLanguageFrontend) handleCompositeLit(fset *token.FileSet, lit *ast
return c
}

func (this *GoLanguageFrontend) handleIdent(fset *token.FileSet, ident *ast.Ident) *cpg.DeclaredReferenceExpression {
func (this *GoLanguageFrontend) handleIdent(fset *token.FileSet, ident *ast.Ident) *cpg.Expression {
// Check, if this is 'nil', because then we handle it as a literal in the graph
if ident.Name == "nil" {
lit := cpg.NewLiteral(fset, ident)

(*cpg.Node)(lit).SetName(ident.Name)

return (*cpg.Expression)(lit)
}

ref := cpg.NewDeclaredReferenceExpression(fset, ident)

tu := this.GetCurrentTU()
Expand All @@ -1199,7 +1208,7 @@ func (this *GoLanguageFrontend) handleIdent(fset *token.FileSet, ident *ast.Iden

ref.SetName(ident.Name)

return ref
return (*cpg.Expression)(ref)
}

func (this *GoLanguageFrontend) handleTypeAssertExpr(fset *token.FileSet, assert *ast.TypeAssertExpr) *cpg.CastExpression {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,15 @@ class GoLanguageFrontendTest : BaseTest() {
assertNotNull(f32)
assertEquals("f32", f32.name)
assertEquals(TypeParser.createFrom("float32", false), f32.type)

val n = p.byNameOrNull<VariableDeclaration>("n")
assertNotNull(n)
assertEquals(TypeParser.createFrom("int*", false), n.type)

val nil = n.initializer as? Literal<*>
assertNotNull(nil)
assertEquals("nil", nil.name)
assertEquals(null, nil.value)
}

@Test
Expand Down
1 change: 1 addition & 0 deletions cpg-language-go/src/test/resources/golang/literal.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ const a = 1
const s = "test"
const f = 1.0
const f32 float32 = 1.00
var n *int = nil

0 comments on commit 62885d0

Please sign in to comment.