use of de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression in project cpg by Fraunhofer-AISEC.
the class CXXIncludeTest method testDefinitionsAndDeclaration.
@Test
void testDefinitionsAndDeclaration() throws Exception {
File file = new File("src/test/resources/include.cpp");
TranslationUnitDeclaration tu = TestUtils.analyzeAndGetFirstTU(List.of(file), file.getParentFile().toPath(), true);
for (Declaration d : tu.getDeclarations()) {
System.out.println(d.getName() + " " + d.getLocation());
}
assertEquals(6, tu.getDeclarations().size());
RecordDeclaration someClass = tu.getDeclarationsByName("SomeClass", RecordDeclaration.class).iterator().next();
assertNotNull(someClass);
Set<FunctionDeclaration> main = tu.getDeclarationsByName("main", FunctionDeclaration.class);
assertFalse(main.isEmpty());
ConstructorDeclaration someClassConstructor = tu.getDeclarationsByName("SomeClass", ConstructorDeclaration.class).iterator().next();
assertNotNull(someClassConstructor);
assertEquals(someClass, someClassConstructor.getRecordDeclaration());
MethodDeclaration doSomething = tu.getDeclarationsByName("DoSomething", MethodDeclaration.class).iterator().next();
assertNotNull(doSomething);
assertEquals(someClass, doSomething.getRecordDeclaration());
ReturnStatement returnStatement = doSomething.getBodyStatementAs(0, ReturnStatement.class);
assertNotNull(returnStatement);
DeclaredReferenceExpression ref = (DeclaredReferenceExpression) returnStatement.getReturnValue();
assertNotNull(ref);
FieldDeclaration someField = someClass.getField("someField");
assertNotNull(someField);
assertEquals(someField, ref.getRefersTo());
}
use of de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression in project cpg by Fraunhofer-AISEC.
the class EOGTest method testBranchProperty.
/**
* Tests EOG branch edge property in if/else if/else construct
*
* @throws Exception
*/
@Test
void testBranchProperty() throws Exception {
Path topLevel = Path.of("src", "test", "resources", "eog");
List<TranslationUnitDeclaration> result = TestUtils.analyze(List.of(topLevel.resolve("EOG.java").toFile()), topLevel, true);
// Test If-Block
IfStatement firstIf = TestUtils.findByPredicate(TestUtils.subnodesOfType(result, IfStatement.class), l -> l.getLocation().getRegion().getStartLine() == 6).get(0);
DeclaredReferenceExpression a = TestUtils.findByPredicate(TestUtils.subnodesOfType(result, DeclaredReferenceExpression.class), l -> l.getLocation().getRegion().getStartLine() == 8 && l.getName().equals("a")).get(0);
DeclaredReferenceExpression b = TestUtils.findByPredicate(TestUtils.subnodesOfType(result, DeclaredReferenceExpression.class), l -> l.getLocation().getRegion().getStartLine() == 7 && l.getName().equals("b")).get(0);
List<PropertyEdge<Node>> nextEOG = firstIf.getNextEOGEdges();
assertEquals(2, nextEOG.size());
for (PropertyEdge<Node> edge : nextEOG) {
assertEquals(firstIf, edge.getStart());
if (edge.getEnd().equals(b)) {
assertEquals(true, edge.getProperty(Properties.BRANCH));
assertEquals(0, edge.getProperty(Properties.INDEX));
} else {
assertEquals(a, edge.getEnd());
assertEquals(false, edge.getProperty(Properties.BRANCH));
assertEquals(1, edge.getProperty(Properties.INDEX));
}
}
IfStatement elseIf = TestUtils.findByPredicate(TestUtils.subnodesOfType(result, IfStatement.class), l -> l.getLocation().getRegion().getStartLine() == 8).get(0);
assertEquals(elseIf, firstIf.getElseStatement());
DeclaredReferenceExpression b2 = TestUtils.findByPredicate(TestUtils.subnodesOfType(result, DeclaredReferenceExpression.class), l -> l.getLocation().getRegion().getStartLine() == 9 && l.getName().equals("b")).get(0);
DeclaredReferenceExpression x = TestUtils.findByPredicate(TestUtils.subnodesOfType(result, DeclaredReferenceExpression.class), l -> l.getLocation().getRegion().getStartLine() == 11 && l.getName().equals("x")).get(0);
nextEOG = elseIf.getNextEOGEdges();
assertEquals(2, nextEOG.size());
for (PropertyEdge<Node> edge : nextEOG) {
assertEquals(elseIf, edge.getStart());
if (edge.getEnd().equals(b2)) {
assertEquals(true, edge.getProperty(Properties.BRANCH));
assertEquals(0, edge.getProperty(Properties.INDEX));
} else {
assertEquals(x, edge.getEnd());
assertEquals(false, edge.getProperty(Properties.BRANCH));
assertEquals(1, edge.getProperty(Properties.INDEX));
}
}
}
use of de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression in project cpg by Fraunhofer-AISEC.
the class CXXSymbolConfigurationTest method testWithoutSymbols.
@Test
void testWithoutSymbols() throws TranslationException {
// parse without symbols
TranslationUnitDeclaration tu = new CXXLanguageFrontend(TranslationConfiguration.builder().defaultPasses().build(), new ScopeManager()).parse(new File("src/test/resources/symbols.cpp"));
Set<FunctionDeclaration> main = tu.getDeclarationsByName("main", FunctionDeclaration.class);
assertFalse(main.isEmpty());
FunctionDeclaration funcDecl = main.iterator().next();
BinaryOperator binaryOperator = funcDecl.getBodyStatementAs(0, BinaryOperator.class);
assertNotNull(binaryOperator);
// without additional symbols, the first line will look like a reference (to something we do not
// know)
DeclaredReferenceExpression dre = binaryOperator.getRhsAs(DeclaredReferenceExpression.class);
assertNotNull(dre);
assertEquals("HELLO_WORLD", dre.getName());
binaryOperator = funcDecl.getBodyStatementAs(1, BinaryOperator.class);
assertNotNull(binaryOperator);
// without additional symbols, the second line will look like a function call (to something we
// do not know)
CallExpression call = binaryOperator.getRhsAs(CallExpression.class);
assertNotNull(call);
assertEquals("INCREASE", call.getName());
}
use of de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression in project cpg by Fraunhofer-AISEC.
the class VariableUsageResolver method resolveFieldUsages.
protected void resolveFieldUsages(Node current, RecordDeclaration curClass) {
if (current instanceof MemberExpression) {
MemberExpression memberExpression = (MemberExpression) current;
Declaration baseTarget = null;
if (memberExpression.getBase() instanceof DeclaredReferenceExpression) {
DeclaredReferenceExpression base = (DeclaredReferenceExpression) memberExpression.getBase();
if (lang instanceof JavaLanguageFrontend && base.getName().equals("super")) {
if (curClass != null && !curClass.getSuperClasses().isEmpty()) {
var superType = curClass.getSuperClasses().get(0);
var superRecord = recordMap.get(superType);
if (superRecord == null) {
log.error("Could not find referring super type {} for {} in the record map. Will set the super type to java.lang.Object", superType.getTypeName(), curClass.getName());
base.setType(TypeParser.createFrom(Object.class.getName(), true));
} else {
baseTarget = superRecord.getThis();
base.setRefersTo(baseTarget);
}
} else {
// no explicit super type -> java.lang.Object
Type objectType = TypeParser.createFrom(Object.class.getName(), true);
base.setType(objectType);
}
} else {
baseTarget = resolveBase((DeclaredReferenceExpression) memberExpression.getBase());
base.setRefersTo(baseTarget);
}
if (baseTarget instanceof EnumDeclaration) {
String name = memberExpression.getName();
Optional<EnumConstantDeclaration> memberTarget = ((EnumDeclaration) baseTarget).getEntries().stream().filter(e -> e.getName().equals(name)).findFirst();
if (memberTarget.isPresent()) {
memberExpression.setRefersTo(memberTarget.get());
return;
}
} else if (baseTarget instanceof RecordDeclaration) {
Type baseType = TypeParser.createFrom(baseTarget.getName(), true);
if (!recordMap.containsKey(baseType)) {
final Type containingT = baseType;
Optional<Type> fqnResolvedType = recordMap.keySet().stream().filter(t -> t.getName().endsWith("." + containingT.getName())).findFirst();
if (fqnResolvedType.isPresent()) {
baseType = fqnResolvedType.get();
}
}
memberExpression.setRefersTo(resolveMember(baseType, memberExpression));
return;
}
}
Type baseType = memberExpression.getBase().getType();
if (!recordMap.containsKey(baseType)) {
final Type containingT = baseType;
Optional<Type> fqnResolvedType = recordMap.keySet().stream().filter(t -> t.getName().endsWith("." + containingT.getName())).findFirst();
if (fqnResolvedType.isPresent()) {
baseType = fqnResolvedType.get();
}
}
memberExpression.setRefersTo(resolveMember(baseType, memberExpression));
}
}
use of de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression in project cpg by Fraunhofer-AISEC.
the class VariableUsageResolver method resolveLocalVarUsage.
protected void resolveLocalVarUsage(RecordDeclaration currentClass, Node parent, Node current) {
if (lang == null) {
Util.errorWithFileLocation(current, log, "Could not resolve local variable usage: language frontend is null");
return;
}
if (current instanceof DeclaredReferenceExpression && !(current instanceof MemberExpression)) {
DeclaredReferenceExpression ref = (DeclaredReferenceExpression) current;
if (parent instanceof MemberCallExpression && current == ((MemberCallExpression) parent).getMember() && !(ref.getType() instanceof FunctionPointerType)) {
// function pointer call
return;
}
// only consider resolving, if the language frontend did not specify a resolution
Optional<? extends Declaration> refersTo = ref.getRefersTo() == null ? Optional.ofNullable(lang.getScopeManager().resolveReference(ref)) : Optional.of(ref.getRefersTo());
Type recordDeclType = null;
if (currentClass != null) {
recordDeclType = TypeParser.createFrom(currentClass.getName(), true);
}
if (ref.getType() instanceof FunctionPointerType && refersTo.isEmpty()) {
refersTo = resolveFunctionPtr(recordDeclType, ref);
}
// only add new nodes for non-static unknown
if (refersTo.isEmpty() && !(((DeclaredReferenceExpression) current).isStaticAccess()) && recordDeclType != null && recordMap.containsKey(recordDeclType)) {
// Maybe we are referring to a field instead of a local var
if (current.getName().contains(lang.getNamespaceDelimiter())) {
List<String> path = Arrays.asList(current.getName().split(Pattern.quote(lang.getNamespaceDelimiter())));
recordDeclType = TypeParser.createFrom(String.join(lang.getNamespaceDelimiter(), path.subList(0, path.size() - 1)), true);
}
ValueDeclaration field = resolveMember(recordDeclType, (DeclaredReferenceExpression) current);
if (field != null) {
refersTo = Optional.of(field);
}
}
// just enables CXX static fields
if (refersTo.isEmpty() && current.getName().contains(lang.getNamespaceDelimiter())) {
var path = Arrays.asList(current.getName().split(Pattern.quote(lang.getNamespaceDelimiter())));
recordDeclType = TypeParser.createFrom(String.join(lang.getNamespaceDelimiter(), path.subList(0, path.size() - 1)), true);
var field = resolveMember(recordDeclType, (DeclaredReferenceExpression) current);
if (field != null) {
refersTo = Optional.of(field);
}
}
if (refersTo.isPresent()) {
ref.setRefersTo(refersTo.get());
} else {
warnWithFileLocation(current, log, "Did not find a declaration for {}", ref.getName());
}
}
}
Aggregations