From 62885d049339e45e37cc30f91e0e911a14b7a791 Mon Sep 17 00:00:00 2001 From: Christian Banse Date: Sun, 28 Aug 2022 12:44:11 +0200 Subject: [PATCH] Implementing `nil` as a literal in the Go language frontend (#897) Fixes #447 --- cpg-language-go/src/main/golang/frontend/handler.go | 13 +++++++++++-- .../cpg/frontends/golang/GoLanguageFrontendTest.kt | 9 +++++++++ .../src/test/resources/golang/literal.go | 1 + 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/cpg-language-go/src/main/golang/frontend/handler.go b/cpg-language-go/src/main/golang/frontend/handler.go index 578779c6f7..3a277abbed 100644 --- a/cpg-language-go/src/main/golang/frontend/handler.go +++ b/cpg-language-go/src/main/golang/frontend/handler.go @@ -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() @@ -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 { diff --git a/cpg-language-go/src/test/kotlin/de/fraunhofer/aisec/cpg/frontends/golang/GoLanguageFrontendTest.kt b/cpg-language-go/src/test/kotlin/de/fraunhofer/aisec/cpg/frontends/golang/GoLanguageFrontendTest.kt index edd6e0272d..c7764c7b42 100644 --- a/cpg-language-go/src/test/kotlin/de/fraunhofer/aisec/cpg/frontends/golang/GoLanguageFrontendTest.kt +++ b/cpg-language-go/src/test/kotlin/de/fraunhofer/aisec/cpg/frontends/golang/GoLanguageFrontendTest.kt @@ -247,6 +247,15 @@ class GoLanguageFrontendTest : BaseTest() { assertNotNull(f32) assertEquals("f32", f32.name) assertEquals(TypeParser.createFrom("float32", false), f32.type) + + val n = p.byNameOrNull("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 diff --git a/cpg-language-go/src/test/resources/golang/literal.go b/cpg-language-go/src/test/resources/golang/literal.go index 147c509bdd..63cdc1c7e5 100644 --- a/cpg-language-go/src/test/resources/golang/literal.go +++ b/cpg-language-go/src/test/resources/golang/literal.go @@ -4,3 +4,4 @@ const a = 1 const s = "test" const f = 1.0 const f32 float32 = 1.00 +var n *int = nil