Skip to content

Commit 225af8c

Browse files
[jssrc2cpg] Fixes for json exceptions and missing identifier/local links (#5127)
1 parent d65ef4e commit 225af8c

File tree

4 files changed

+60
-38
lines changed

4 files changed

+60
-38
lines changed

joern-cli/frontends/jssrc2cpg/src/main/scala/io/joern/jssrc2cpg/astcreation/AstForDeclarationsCreator.scala

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,10 @@ trait AstForDeclarationsCreator(implicit withSchemaValidation: ValidationMode) {
8585
): Ast = {
8686
from match {
8787
case Some(value) =>
88+
val identNode = identifierNode(declaration, value)
89+
scope.addVariableReference(name, identNode)
8890
val call = createFieldAccessCallAst(
89-
identifierNode(declaration, value, Seq.empty),
91+
identNode,
9092
createFieldIdentifierNode(name, declaration.lineNumber, declaration.columnNumber),
9193
declaration.lineNumber,
9294
declaration.columnNumber
@@ -99,9 +101,11 @@ trait AstForDeclarationsCreator(implicit withSchemaValidation: ValidationMode) {
99101
declaration.columnNumber
100102
)
101103
case None =>
104+
val identNode = identifierNode(declaration, name)
105+
scope.addVariableReference(name, identNode)
102106
createAssignmentCallAst(
103107
exportCallAst,
104-
Ast(identifierNode(declaration, name)),
108+
Ast(identNode),
105109
s"${codeOf(exportCallAst.nodes.head)} = $name",
106110
declaration.lineNumber,
107111
declaration.columnNumber
@@ -262,7 +266,6 @@ trait AstForDeclarationsCreator(implicit withSchemaValidation: ValidationMode) {
262266
createExportAssignmentCallAst(name, exportCallAst, assignment, None)
263267
}
264268
}
265-
266269
setArgumentIndices(declAsts)
267270
blockAst(createBlockNode(assignment), declAsts)
268271
}

joern-cli/frontends/jssrc2cpg/src/main/scala/io/joern/jssrc2cpg/parser/BabelJsonParser.scala

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ import io.joern.x2cpg.astgen.BaseParserResult
44
import io.shiftleft.utils.IOUtils
55
import ujson.Value.Value
66

7-
import java.nio.file.{Path, Paths}
7+
import java.nio.file.Path
8+
import java.nio.file.Paths
9+
import scala.util.Try
810

911
object BabelJsonParser {
1012

@@ -13,25 +15,28 @@ object BabelJsonParser {
1315
fullPath: String,
1416
json: Value,
1517
fileContent: String,
16-
typeMap: Map[Int, String]
18+
typeMap: Map[Int, String],
19+
fileLoc: Int
1720
) extends BaseParserResult
1821

19-
def readFile(rootPath: Path, file: Path): ParseResult = {
20-
val typeMapPath = Paths.get(file.toString.replace(".json", ".typemap"))
21-
val typeMap = if (typeMapPath.toFile.exists()) {
22-
val typeMapJsonContent = IOUtils.readEntireFile(typeMapPath)
23-
val typeMapJson = ujson.read(typeMapJsonContent)
24-
typeMapJson.obj.map { case (k, v) => k.toInt -> v.str }.toMap
25-
} else {
26-
Map.empty[Int, String]
22+
def readFile(rootPath: Path, file: Path): Option[ParseResult] = {
23+
Try {
24+
val typeMapPath = Paths.get(file.toString.replace(".json", ".typemap"))
25+
val typeMap = if (typeMapPath.toFile.exists()) {
26+
val typeMapJsonContent = IOUtils.readEntireFile(typeMapPath)
27+
val typeMapJson = ujson.read(typeMapJsonContent)
28+
typeMapJson.obj.map { case (k, v) => k.toInt -> v.str }.toMap
29+
} else {
30+
Map.empty[Int, String]
31+
}
32+
val jsonContent = IOUtils.readEntireFile(file)
33+
val json = ujson.read(jsonContent)
34+
val filename = json("relativeName").str
35+
val fullPath = Paths.get(rootPath.toString, filename)
36+
val sourceFileContent = IOUtils.readEntireFile(fullPath)
37+
val fileLoc = sourceFileContent.lines().count().toInt
38+
ParseResult(filename, fullPath.toString, json, sourceFileContent, typeMap, fileLoc)
2739
}
28-
29-
val jsonContent = IOUtils.readEntireFile(file)
30-
val json = ujson.read(jsonContent)
31-
val filename = json("relativeName").str
32-
val fullPath = Paths.get(rootPath.toString, filename)
33-
val sourceFileContent = IOUtils.readEntireFile(fullPath)
34-
ParseResult(filename, fullPath.toString, json, sourceFileContent, typeMap)
35-
}
40+
}.toOption
3641

3742
}

joern-cli/frontends/jssrc2cpg/src/main/scala/io/joern/jssrc2cpg/passes/AstCreationPass.scala

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,19 @@ import io.joern.jssrc2cpg.utils.AstGenRunner.AstGenRunnerResult
77
import io.joern.x2cpg.ValidationMode
88
import io.joern.x2cpg.datastructures.Global
99
import io.joern.x2cpg.frontendspecific.jssrc2cpg.Defines
10-
import io.joern.x2cpg.utils.{Report, TimeUtils}
10+
import io.joern.x2cpg.utils.Report
11+
import io.joern.x2cpg.utils.TimeUtils
1112
import io.shiftleft.codepropertygraph.generated.Cpg
1213
import io.shiftleft.passes.ForkJoinParallelCpgPass
1314
import io.shiftleft.utils.IOUtils
14-
import org.slf4j.{Logger, LoggerFactory}
15+
import org.slf4j.Logger
16+
import org.slf4j.LoggerFactory
1517

1618
import java.nio.file.Paths
17-
import scala.util.{Failure, Success, Try}
1819
import scala.jdk.CollectionConverters.*
20+
import scala.util.Failure
21+
import scala.util.Success
22+
import scala.util.Try
1923

2024
class AstCreationPass(cpg: Cpg, astGenRunnerResult: AstGenRunnerResult, config: Config, report: Report = new Report())(
2125
implicit withSchemaValidation: ValidationMode
@@ -45,20 +49,24 @@ class AstCreationPass(cpg: Cpg, astGenRunnerResult: AstGenRunnerResult, config:
4549

4650
override def runOnPart(diffGraph: DiffGraphBuilder, input: (String, String)): Unit = {
4751
val (rootPath, jsonFilename) = input
52+
val parseResultMaybe = BabelJsonParser.readFile(Paths.get(rootPath), Paths.get(jsonFilename))
4853
val ((gotCpg, filename), duration) = TimeUtils.time {
49-
val parseResult = BabelJsonParser.readFile(Paths.get(rootPath), Paths.get(jsonFilename))
50-
val fileLOC = IOUtils.readLinesInFile(Paths.get(parseResult.fullPath)).size
51-
report.addReportInfo(parseResult.filename, fileLOC, parsed = true)
52-
Try {
53-
val localDiff = new AstCreator(config, global, parseResult).createAst()
54-
diffGraph.absorb(localDiff)
55-
} match {
56-
case Failure(exception) =>
57-
logger.warn(s"Failed to generate a CPG for: '${parseResult.fullPath}'", exception)
58-
(false, parseResult.filename)
59-
case Success(_) =>
60-
logger.debug(s"Generated a CPG for: '${parseResult.fullPath}'")
61-
(true, parseResult.filename)
54+
parseResultMaybe match {
55+
case Some(parseResult) =>
56+
report.addReportInfo(parseResult.filename, parseResult.fileLoc, parsed = true)
57+
Try {
58+
val localDiff = new AstCreator(config, global, parseResult).createAst()
59+
diffGraph.absorb(localDiff)
60+
} match {
61+
case Failure(exception) =>
62+
logger.warn(s"Failed to generate a CPG for: '${parseResult.fullPath}'", exception)
63+
(false, parseResult.filename)
64+
case Success(_) =>
65+
logger.debug(s"Generated a CPG for: '${parseResult.fullPath}'")
66+
(true, parseResult.filename)
67+
}
68+
case None =>
69+
(false, jsonFilename.replace(".json", ""))
6270
}
6371
}
6472
report.updateReport(filename, cpg = gotCpg, duration)

joern-cli/frontends/jssrc2cpg/src/test/scala/io/joern/jssrc2cpg/passes/ast/DependencyAstCreationPassTests.scala

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,12 @@ class DependencyAstCreationPassTests extends AstJsSrc2CpgSuite {
4949
}
5050

5151
"AST generation for dependencies" should {
52+
"reference identifiers correctly" in {
53+
val cpg = code("export const foo = bar();")
54+
cpg.local.name("foo").referencingIdentifiers.size shouldBe 2
55+
cpg.identifier.name("foo").size shouldBe 2
56+
}
57+
5258
"have no dependencies if none are declared at all" in {
5359
val cpg = code("var x = 1;")
5460
cpg.dependency.l.size shouldBe 0
@@ -335,7 +341,7 @@ class DependencyAstCreationPassTests extends AstJsSrc2CpgSuite {
335341
|export = function () {}; // anonymous
336342
|export = class ClassA {};
337343
|""".stripMargin)
338-
cpg.local.code.l shouldBe List("foo", "bar", "func", "<lambda>0")
344+
cpg.local.code.l shouldBe List("foo", "bar", "func", "<lambda>0", "ClassA")
339345
cpg.typeDecl.name.l should contain allElementsOf List("func", "ClassA")
340346
cpg.assignment.code.l shouldBe List(
341347
"var foo = 1",

0 commit comments

Comments
 (0)