Skip to content

Commit

Permalink
[ruby] Added handling for .[]() indexAccess (#4978)
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreiDreyer authored Sep 30, 2024
1 parent 7c417d2 commit fa22d81
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ methodName
: methodIdentifier
| keyword
| pseudoVariable
| LBRACK RBRACK
;

methodOnlyIdentifier
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,7 @@ class RubyNodeCreator(
Option(ctx.primaryValue()).map(_.getText).contains("Class") && Option(ctx.methodName())
.map(_.getText)
.contains("new")

val methodName = ctx.methodName().getText

if (!hasBlock) {
Expand All @@ -943,7 +944,8 @@ class RubyNodeCreator(
}
} else {
val args = ctx.argumentWithParentheses().arguments.map(visit)
return MemberCall(target, ctx.op.getText, methodName, args)(ctx.toTextSpan)
if methodName == "[]" then return IndexAccess(target, args)(ctx.toTextSpan)
else return MemberCall(target, ctx.op.getText, methodName, args)(ctx.toTextSpan)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,27 @@ class IndexAccessTests extends RubyCode2CpgFixture {
two.code shouldBe "2"
}

"Index Access with `.[](index)`" in {
val cpg = code("""
|class Foo
| def extract_url
| @params.dig(:event, :links)&.first&.[](:url)
| end
|end
|""".stripMargin)

inside(cpg.call.name(Operators.indexAccess).l) {
case indexCall :: Nil =>
indexCall.code shouldBe "@params.dig(:event, :links)&.first&.[](:url)"

inside(indexCall.argument.l) {
case target :: index :: Nil =>
target.code shouldBe "(<tmp-1> = @params.dig(:event, :links))&.first"
index.code shouldBe ":url"
case xs => fail(s"Expected target and index, got [${xs.code.mkString(",")}]")
}

case xs => fail(s"Expected one index access, got [${xs.code.mkString(",")}]")
}
}
}

0 comments on commit fa22d81

Please sign in to comment.