Skip to content

Commit

Permalink
[ruby] Fixed issue where init stmts and params were missing in classD…
Browse files Browse the repository at this point in the history
…ecl (#4817)
  • Loading branch information
AndreiDreyer authored Aug 1, 2024
1 parent 3cd3f3c commit 3a53fdb
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1083,7 +1083,7 @@ class RubyNodeCreator extends RubyParserBaseVisitor[RubyNode] {
)
}

StatementList(otherTypeDeclChildren ++ updatedBodyMethod)(stmts.span)
StatementList(initMethod ++ otherTypeDeclChildren ++ updatedBodyMethod)(stmts.span)
}

override def visitClassDefinition(ctx: RubyParser.ClassDefinitionContext): RubyNode = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import io.joern.x2cpg.Defines
import io.shiftleft.codepropertygraph.generated.{DispatchTypes, Operators}
import io.shiftleft.codepropertygraph.generated.nodes.*
import io.shiftleft.semanticcpg.language.*
import io.joern.rubysrc2cpg.passes.Defines.Main
import io.joern.rubysrc2cpg.passes.Defines.{Main, TypeDeclBody, Initialize}
import io.joern.rubysrc2cpg.passes.GlobalTypes

class ClassTests extends RubyCode2CpgFixture {

Expand Down Expand Up @@ -908,4 +909,45 @@ class ClassTests extends RubyCode2CpgFixture {
cpg.method.nameExact("foo").fullName.l shouldBe List(s"Test0.rb:$Main.Foo.foo", s"Test0.rb:$Main.Foo0.foo")

}

"Class with nonAllowedTypeDeclChildren and explicit init" should {
val cpg = code("""
|class Foo
| 1
| def initialize(bar)
| puts bar
| end
|end
|""".stripMargin)

"have an explicit init method" in {
inside(cpg.typeDecl.nameExact("Foo").method.l) {
case initMethod :: bodyMethod :: Nil =>
bodyMethod.name shouldBe TypeDeclBody

initMethod.name shouldBe Initialize
inside(initMethod.parameter.l) {
case selfParam :: barParam :: Nil =>
selfParam.name shouldBe "self"
barParam.name shouldBe "bar"
case xs => fail(s"Expected two params, got [${xs.code.mkString(",")}]")
}

inside(initMethod.block.astChildren.l) {
case (putsCall: Call) :: Nil =>
putsCall.name shouldBe "puts"
case xs => fail(s"Expected one call, got [${xs.code.mkString(",")}]")
}

inside(bodyMethod.block.astChildren.l) {
case (one: Literal) :: Nil =>
one.code shouldBe "1"
one.typeFullName shouldBe s"${GlobalTypes.kernelPrefix}.Integer"
case xs => fail(s"Expected one literal, got [${xs.code.mkString(",")}]")
}

case xs => fail(s"Expected body method and init method, got [${xs.code.mkString(",")}]")
}
}
}
}

0 comments on commit 3a53fdb

Please sign in to comment.