Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/documentation/wiki-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1145,6 +1145,25 @@ package/version in the database directly, reach for the ${linkToQueryOfName('sig
}
`);

registerQueryDocumentation('aliases', {
type: 'active',
shortDescription: 'Returns all aliases of a given identifier.',
buildExplanation: async(shell: RShell, _: GeneralDocContext) => {
const exampleCode = 'x <- 1\ng <- x\nh <- g';
const criteria = ['1@x'] as SlicingCriteria;
const id = [3];
return `
If the identifier is given as a NodeId the aliases will be returned as NodeId as well. If the identifier uses a slicing criterion the location of the corresponding aliases will be returned.
The following example uses both functionalities:
Given the code ${codeBlock('r', exampleCode)}. Here '2@g' resolves to NodeId 3.
Then the following query will return the location of the aliases of x and the NodeIds of the aliases of g.
${
await showQuery(shell, exampleCode, [{ type: 'aliases', criteria: criteria, id: id }])
}
`;
}
});

/** https://github.com/flowr-analysis/flowr/wiki/Query-API */
export class WikiQuery extends DocMaker<'wiki/Query API.md'> {
constructor() {
Expand Down
110 changes: 110 additions & 0 deletions src/queries/catalog/aliases-query/aliases-query-executor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { DfEdge, EdgeType } from '../../../dataflow/graph/edge';
import type { DataflowGraph } from '../../../dataflow/graph/graph';
import { DfgVertex, type DataflowGraphVertexInfo } from '../../../dataflow/graph/vertex';
import type { NodeId } from '../../../r-bridge/lang-4.x/ast/model/processing/node-id';
import { SlicingCriterion } from '../../../slicing/criterion/parse';
import { isNotUndefined, isUndefined } from '../../../util/assert';
import { SourceLocation } from '../../../util/range';
import type { BasicQueryData } from '../../base-query-format';
import { metaSince } from '../../query-meta';
import type { AliasesQuery, AliasesQueryResult } from './aliases-query-format';

function getAlias(source: NodeId, dfg: DataflowGraph<DataflowGraphVertexInfo, DfEdge>) {
const alreadyVisited = new Set<NodeId>();
//search for whether source node is/defines a function?
let srcIsFunc = false;
const searchSrcDef = [source];
while(searchSrcDef.length !== 0) {
const id = searchSrcDef.pop();
if(isUndefined(id) || alreadyVisited.has(id)) {
continue;
}
const vertex = dfg.getVertex(id);
if(DfgVertex.isFunctionDefinition(vertex)) {
srcIsFunc = true;
break;
}
for(const [neighbor, edge] of dfg.edgesFrom(id)) {
if(DfEdge.isOnlyType({ types: EdgeType.Reads }, edge.types) || DfEdge.isOnlyType({ types: EdgeType.DefinedBy }, edge.types) || DfEdge.isOnlyType({ types: EdgeType.DefinedByOnCall }, edge.types)) {
searchSrcDef.push(neighbor);
}
}
alreadyVisited.add(id);
}
//search for all aliases of source
alreadyVisited.clear();
const resultIds = new Set<NodeId>();
//isResult is used to make sure that we only return nodes that are actual aliases and not just different "mentions" of the source throughout the code
//there needs to be a DefinedBy/DefinedOnCall edge on the path between the source node and a possible result node for the result node to be a true alias of the source
const toSearch: { vertex: NodeId; isResult: boolean }[] = [{
vertex: source,
isResult: false
}];
while(toSearch.length !== 0) {
const next = toSearch.pop();
if(isUndefined(next)) {
continue;
}
const { vertex, isResult } = next;
if(alreadyVisited.has(vertex)) {
continue;
}
for(const [neighbor, edge] of dfg.edgesTo(vertex)) {
if(DfEdge.isOnlyType({ types: EdgeType.Reads }, edge.types) || DfEdge.isOnlyType({ types: EdgeType.DefinedBy }, edge.types) || DfEdge.isOnlyType({ types: EdgeType.DefinedByOnCall }, edge.types)) {
if((isResult || DfEdge.isOnlyType({ types: EdgeType.DefinedBy }, edge.types)) && !alreadyVisited.has(neighbor)) {
//edge case: if the possible result node is a function call, but the source doesn't define a function, the possible result node is actually defined
if(DfgVertex.isFunctionCall(dfg.getVertex(neighbor)) && !srcIsFunc) {
continue;
}
toSearch.push({ vertex: neighbor, isResult: true });
resultIds.add(neighbor);
} else {
toSearch.push({ vertex: neighbor, isResult: next.isResult });
}
}
}
for(const [neighbor, edge] of dfg.edgesFrom(vertex)) {
if(DfEdge.isOnlyType({ types: EdgeType.DefinesOnCall }, edge.types)) {
toSearch.push({ vertex: neighbor, isResult: true });
resultIds.add(neighbor);
}
}
alreadyVisited.add(vertex);
}
return resultIds;
}

/**
* Executes the given alias queries using the provided analyzer.
*/
export async function executeAliasesQuery({ analyzer }: BasicQueryData, queries: readonly AliasesQuery[]): Promise<AliasesQueryResult> {
const ast = await analyzer.normalize();
const idMap = ast.idMap;
const dataflow = await analyzer.dataflow();
const dfg = dataflow.graph;
const start = Date.now();

const result: ([SlicingCriterion, SourceLocation[]] | [NodeId, NodeId[]])[] = [];
for(const query of queries) {
if(isNotUndefined(query.criteria)) {
for(const criterion of query.criteria) {
const nodeId = SlicingCriterion.parse(criterion, idMap);
const aliases = Array.from(getAlias(nodeId, dfg));
const aliasesLocation = aliases.map(nodeId => {
return SourceLocation.fromNode(idMap.get(nodeId));
}).filter(element => isNotUndefined(element));
result.push([criterion, aliasesLocation]);
}
}
if(isNotUndefined(query.id)) {
for(const nodeId of query.id) {
const aliases = Array.from(getAlias(nodeId, dfg));
result.push([nodeId, aliases]);
}
}
}
return {
...metaSince(start),
result: result
};
}
42 changes: 42 additions & 0 deletions src/queries/catalog/aliases-query/aliases-query-format.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import Joi from 'joi';
import type { BaseQueryFormat, BaseQueryResult } from '../../base-query-format';
import type { QueryResults, SupportedQuery } from '../../query';
import { bold } from '../../../util/text/ansi';
import { executeAliasesQuery } from './aliases-query-executor';
import type { SlicingCriteria, SlicingCriterion } from '../../../slicing/criterion/parse';
import type { NodeId } from '../../../r-bridge/lang-4.x/ast/model/processing/node-id';
import type { SourceLocation } from '../../../util/range';

export interface AliasesQuery extends BaseQueryFormat {
readonly type: 'aliases';
readonly criteria?: SlicingCriteria;
readonly id?: NodeId[];
}
export interface AliasesQueryResult extends BaseQueryResult {
readonly result: ([SlicingCriterion, SourceLocation[]] | [NodeId, NodeId[]])[];//Map<SlicingCriterion, SourceLocation[]>;
}

export const AliasesQueryDefinition = {
title: 'Aliases Query',
executor: executeAliasesQuery,
asciiSummarizer: (formatter, _, queryResults, result) => {
const out = queryResults as QueryResults<'aliases'>['aliases'];
result.push(`Query: ${bold('aliases', formatter)} (${out['.meta'].timing.toFixed(0)}ms)`);
for(const criterion of out.result) {
const aliases = criterion[1].length === 0 ? ' ╰ has no aliases.' : ` ╰ has aliases ${criterion[1].map(elem => {
return `[${elem.toString()}]`;
}).join(', ')}`;
result.push(criterion[0].toString(), aliases);
}
return true;
},
schema: Joi.object({
type: Joi.string().valid('aliases').required().description('The type of the query.'),
criteria: Joi.array().items(Joi.string()).optional().description('The slicing criteria of the nodes we want to find the alias for.'),
id: Joi.array().items(Joi.number()).optional().description('The NodeId of the nodes we want to find the alias for.')
}).description('The alias query returns all aliases of the identifiers given as slicing criteria or node ids.'),
flattenInvolvedNodes: (queryResults: BaseQueryResult): NodeId[] => {
const out = queryResults as QueryResults<'aliases'>['aliases'];
return out.result.flatMap(([, aliases]) => (aliases as readonly (NodeId | SourceLocation)[]).filter((alias): alias is NodeId => !Array.isArray(alias)));
}
} as const satisfies SupportedQuery<'aliases'>;
8 changes: 5 additions & 3 deletions src/queries/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,17 @@ import type { LintingResult, LintingResultCertainty } from '../linter/linter-for
import { type DiceQuery, DiceQueryDefinition } from './catalog/dice-query/dice-query-format';
import { type GuessDepVersionsQuery, GuessDepVersionsQueryDefinition } from './catalog/guess-dep-versions-query/guess-dep-versions-query-format';
import { AbsintQueryDefinition, type AbsintQuery } from './catalog/absint-query/absint-query-format';
import { type FunctionInfoQuery, FunctionInfoQueryDefinition } from './catalog/function-info-query/function-info-query-format';
import { type AliasesQuery, AliasesQueryDefinition } from './catalog/aliases-query/aliases-query-format';
import { type CodeClonesQuery, CodeClonesQueryDefinition } from './catalog/code-clones-query/code-clones-query-format';
import { type DataColumnsQuery, DataColumnsQueryDefinition } from './catalog/data-columns-query/data-columns-query-format';
import { type FunctionInfoQuery, FunctionInfoQueryDefinition } from './catalog/function-info-query/function-info-query-format';

/** These are all queries that can be executed from within flowR */
export type Query = CallContextQuery | ConfigQuery | SearchQuery | DataflowQuery | DoesCallQuery | CallGraphQuery | ControlFlowQuery | DataflowLensQuery | FilesQuery
| AbsintQuery | NormalizedAstQuery | IdMapQuery | DataflowClusterQuery | StaticSliceQuery | DependenciesQuery | LocationMapQuery | HappensBeforeQuery
| InspectExceptionQuery | InspectHigherOrderQuery | InspectRecursionQuery | InspectFnPropsQuery | InspectFnGuardsQuery | AmbientAccessQuery
| ResolveValueQuery | ProjectQuery | SignatureQuery | OriginQuery | LinterQuery | ProvenanceQuery | InputSourcesQuery | TaintQuery | DiceQuery
| GuessDepVersionsQuery | FunctionInfoQuery | CodeClonesQuery | DataColumnsQuery;
| GuessDepVersionsQuery | FunctionInfoQuery | CodeClonesQuery | DataColumnsQuery | AliasesQuery;

export type QueryArgumentsWithType<QueryType extends BaseQueryFormat['type']> = Query & { type: QueryType };

Expand Down Expand Up @@ -138,7 +139,8 @@ export const SupportedQueries = {
'guess-dep-versions': GuessDepVersionsQueryDefinition,
'function-info': FunctionInfoQueryDefinition,
'code-clones': CodeClonesQueryDefinition,
'data-columns': DataColumnsQueryDefinition
'data-columns': DataColumnsQueryDefinition,
'aliases': AliasesQueryDefinition
} as const satisfies SupportedQueriesType;

export type SupportedQueryTypes = keyof typeof SupportedQueries;
Expand Down
6 changes: 3 additions & 3 deletions src/queries/virtual-query/compound-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ export interface CompoundQueryFormat<
* You do not have to re-state the type, this is automatically filled with the type for 'query'
* Additionally all arguments given in `commonArguments` are now enforced optional.
*/
readonly arguments: ReadonlyArray<StrictOmit<
StrictOmit<QueryArgumentsWithType<SubQueryType>, 'type'>,
CommonArguments /* we cannot use mark optional / some-partial constructions here as it trips up the type checker, hence we work around by union inclusion */
readonly arguments: ReadonlyArray<Omit<
QueryArgumentsWithType<SubQueryType>,
'type' | CommonArguments /* we cannot use mark optional / some-partial constructions here as it trips up the type checker, hence we work around by union inclusion */
> & Partial<QueryArgumentsWithType<SubQueryType>>>;
}

Expand Down
95 changes: 95 additions & 0 deletions test/functionality/queries/aliases-query.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { describe } from 'vitest';
import type { AliasesQuery } from '../../../src/queries/catalog/aliases-query/aliases-query-format';
import { assertQuery } from '../_helper/query';
import { label } from '../_helper/label';
import type { QueryResultsWithoutMeta } from '../../../src/queries/query';
import { withTreeSitter } from '../_helper/shell';
import type { SourceLocation } from '../../../src';

describe('Aliases Query', withTreeSitter(parser => {
function testQuery(name: string, code: string, query: readonly AliasesQuery[], expected: QueryResultsWithoutMeta<AliasesQuery>) {
assertQuery(label(name), parser, code, query, expected);
}

testQuery('Basic', 'f <- function(...) 42\ng <- f', [{ type: 'aliases', criteria: ['1@f'] }], { aliases: { result: [['1@f', [[2, 1, 2, 1] as SourceLocation]]] } });
testQuery('Basic 2', 'f <- function(...) 42\ng <- f\nh <- g', [{ type: 'aliases', criteria: ['1@f', '2@g'] }], { aliases: { result: [['1@f', [[2, 1, 2, 1] as SourceLocation, [3, 6, 3, 6] as SourceLocation, [3, 1, 3, 1] as SourceLocation]], ['2@g', [[3, 1, 3, 1] as SourceLocation]]] } });
testQuery('Basic - using nodeId criteria', 'f <- function(...) 42\ng <- f\nh <- g', [{ type: 'aliases', criteria: ['1@f', '2@g'], id: [7] }], { aliases: { result: [['1@f', [[2, 1, 2, 1] as SourceLocation, [3, 6, 3, 6] as SourceLocation, [3, 1, 3, 1] as SourceLocation]], ['2@g', [[3, 1, 3, 1] as SourceLocation]], [7, [10]]] } });
testQuery('several levels of aliases', 'f <- function(...){g <- h}\nh <- f\nf()', [{ type: 'aliases', criteria: ['3@f'] }], { aliases: { result: [['3@f', [[2, 1, 2, 1] as SourceLocation, [1, 25, 1, 25] as SourceLocation, [1, 20, 1, 20] as SourceLocation]]] } });
testQuery('several levels of aliases 2', 'f <- function(...){g <- h}\nh <- f', [{ type: 'aliases', criteria: ['2@f'] }], { aliases: { result: [['2@f', [[2, 1, 2, 1] as SourceLocation, [1, 25, 1, 25] as SourceLocation, [1, 20, 1, 20] as SourceLocation]]] } });
testQuery('several levels of aliases - interrupted', 'f <- 5\ng <- f\nf <- f+1\nh <- g', [{ type: 'aliases', criteria: ['1@f', '3@f', '2@g'] }], { aliases: { result: [['1@f', [[2, 1, 2, 1] as SourceLocation, [4, 6, 4, 6] as SourceLocation, [4, 1, 4, 1] as SourceLocation]], ['3@f', []], ['2@g', [[4, 1, 4, 1] as SourceLocation]]] } });
testQuery('branches - if/else', `a <- function(a){
print(a);
}
b <- function(a){
print("Hello");
}
x <- 4
if(x < 0){
c <- a
} else {
c <- b
}
c`, [{ type: 'aliases', criteria: ['1@a'] }], { aliases: { result: [['1@a', [[9, 2, 9, 2] as SourceLocation, [13, 1, 13, 1] as SourceLocation]]] } });
testQuery('lazy evaluation - value set at call', `f <- function(c, a=b) {
b <- c;
a()
}
g <- function(){ 42 }
f(g)`, [{ type: 'aliases', criteria: ['1@f', '1@a', '1@b', '5@g'] }], { aliases: { result: [['1@f', []], ['1@a', []], ['1@b', [[1, 18, 1, 20] as SourceLocation, [3, 2, 3, 4] as SourceLocation]], ['5@g', [[1, 15, 1, 15] as SourceLocation, [2, 7, 2, 7] as SourceLocation, [2, 2, 2, 2] as SourceLocation, [1, 20, 1, 20] as SourceLocation, [1, 18, 1, 20] as SourceLocation, [3, 2, 3, 4] as SourceLocation]]] } });

testQuery('lazy evaluation - ambigious definition', `a <- function() { -1 }
f <- function(c, a=b) {
b <- 4;
print(a);
b <- c;
a()
}
g <- function(){ 42 }
f(g)`, [{ type: 'aliases', criteria: ['1@a', '2@a', '2@b', '8@g'] }], { aliases: { result: [['1@a', []], ['2@a', []], ['2@b', [[2, 18, 2, 20] as SourceLocation, [4, 8, 4, 8] as SourceLocation]], ['8@g', [[2, 15, 2, 15] as SourceLocation, [5, 7, 5, 7] as SourceLocation, [5, 2, 5, 2] as SourceLocation]]] } });

testQuery('branches - only if', `a <- function(a){
print(a);
}
b <- function(a){
print("Hello");
}
x <- 4
c <- b
if(x < 0){
c <- a
}
c`, [{ type: 'aliases', criteria: ['1@a', '4@b'] }], { aliases: { result: [['1@a', [[10, 2, 10, 2] as SourceLocation, [12, 1, 12, 1] as SourceLocation]], ['4@b', [[8, 1, 8, 1] as SourceLocation, [12, 1, 12, 1] as SourceLocation]]] } });

testQuery('branches - overwrite in if', `a <- function(a){
print(a);
}
a
b <- function(a){
print("Hello");
}
x <- 4
c <- b
if(x < 0){
c <- a
c <- b
}
c`, [{ type: 'aliases', criteria: ['1@a', '5@b'] }], { aliases: { result: [['1@a', [[11, 2, 11, 2] as SourceLocation]], ['5@b', [[12, 2, 12, 2] as SourceLocation, [14, 1, 14, 1] as SourceLocation, [9, 1, 9, 1] as SourceLocation]]] } });
testQuery('Loop and if', `x <- 4
b <- function(a){
print("Hello");
}
a <- function(a){
print(a);
}
while(x > 0){
if(x %% 2){
c <- a
c()
}
c <- b
x <- x - 1
}
c()
a
b`, [{ type: 'aliases', criteria: ['2@b', '5@a'] }], { aliases: { result: [['2@b', [[13, 2, 13, 2] as SourceLocation, [16, 1, 16, 3] as SourceLocation]], ['5@a', [[10, 3, 10, 3] as SourceLocation, [11, 3, 11, 5] as SourceLocation]]] } });
}));
1 change: 1 addition & 0 deletions test/functionality/queries/inspect-recursion-query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ describe('Inspect Recursion Query', withTreeSitter(parser => {
/* a definition shadowing a built-in of the same name is looked up when the body runs, not when it is written */
testRecursion('a definition shadowing a built-in', 'c <- function(n) if(n > 0) c(n - 1) else 0', ['1@function']);
testRecursion('two definitions shadowing built-ins calling each other', 'c <- function(n) rev(n)\nrev <- function(n) c(n)', ['1@function', '2@function']);
//to be implemented later on: testRecursion('a function calls an alias of itself', 'f <- function(...) g\ng <- f\nf()', ['1@function']);
});

describe('what only looks like recursion', () => {
Expand Down
13 changes: 12 additions & 1 deletion wiki/Query API.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading