Skip to content

Feat Dynamic Export Analysis #187

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
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
4 changes: 4 additions & 0 deletions libraries/analysis-javascript/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ export * from "./lib/constant/ConstantVisitor";
export * from "./lib/dependency/DependencyFactory";
export * from "./lib/dependency/DependencyVisitor";

export * from "./lib/dynamic/action/Action";
export * from "./lib/dynamic/action/ActionFactory";
export * from "./lib/dynamic/action/Executor";

export * from "./lib/target/export/Export";
export * from "./lib/target/export/ExportDefaultDeclaration";
export * from "./lib/target/export/ExportFactory";
Expand Down
40 changes: 39 additions & 1 deletion libraries/analysis-javascript/lib/RootContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import { ConstantPool } from "./constant/ConstantPool";
import { ConstantPoolFactory } from "./constant/ConstantPoolFactory";
import { ConstantPoolManager } from "./constant/ConstantPoolManager";
import { DependencyFactory } from "./dependency/DependencyFactory";
import { Action } from "./dynamic/action/Action";
import { ActionFactory } from "./dynamic/action/ActionFactory";
import { Events } from "./Events";
import { Export } from "./target/export/Export";
import { ExportFactory } from "./target/export/ExportFactory";
Expand All @@ -51,6 +53,8 @@ export class RootContext extends CoreRootContext<t.Node> {

protected _constantPoolFactory: ConstantPoolFactory;

protected _actionFactory: ActionFactory;

protected _targetFiles: Set<string>;
protected _analysisFiles: Set<string>;

Expand All @@ -66,6 +70,7 @@ export class RootContext extends CoreRootContext<t.Node> {

// Mapping: filepath -> target name -> Exports
protected _exportMap: Map<string, Export[]>;
protected _actionMap: Map<string, Map<string, Action>>;

constructor(
rootPath: string,
Expand All @@ -78,7 +83,8 @@ export class RootContext extends CoreRootContext<t.Node> {
exportFactory: ExportFactory,
typeExtractor: TypeExtractor,
typeResolver: TypeModelFactory,
constantPoolFactory: ConstantPoolFactory
constantPoolFactory: ConstantPoolFactory,
actionFactory: ActionFactory
) {
super(
rootPath,
Expand All @@ -95,6 +101,7 @@ export class RootContext extends CoreRootContext<t.Node> {
this._typeExtractor = typeExtractor;
this._typeResolver = typeResolver;
this._constantPoolFactory = constantPoolFactory;
this._actionFactory = actionFactory;
}

get rootPath(): string {
Expand Down Expand Up @@ -133,6 +140,11 @@ export class RootContext extends CoreRootContext<t.Node> {
return this._sources.get(absoluteTargetPath);
}

protected async getActions(filePath: string) {
const factory = new ActionFactory(1000);
return await factory.extract(filePath, this.getSource(filePath), this.getAbstractSyntaxTree(filePath));
}

getExports(filePath: string): Export[] {
const absolutePath = this.resolvePath(filePath);

Expand All @@ -159,6 +171,28 @@ export class RootContext extends CoreRootContext<t.Node> {
return this._exportMap.get(absolutePath);
}

async extractAllActions() {
if (!this._actionMap) {
this._actionMap = new Map();

for (const filepath of this._analysisFiles) {
this._actionMap.set(filepath, await this.getActions(filepath));
}

this._actionFactory.exit()
}

return this._actionMap;
}

getAllActions() {
if (!this._actionMap) {
throw new Error("First call extractAllActions before calling getAllActions")
}

return this._actionMap;
}

getAllExports(): Map<string, Export[]> {
if (!this._exportMap) {
this._exportMap = new Map();
Expand Down Expand Up @@ -354,4 +388,8 @@ export class RootContext extends CoreRootContext<t.Node> {
RootContext.LOGGER.info("Extracting constants done");
return constantPoolManager;
}

exit() {
this._actionFactory.exit();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,33 +15,27 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { prng } from "@syntest/prng";

import { StatementPool } from "../../../StatementPool";
import { Getter } from "../../../statements/action/Getter";
export type Action = {
type: ActionType;

import { CallGenerator } from "./CallGenerator";
// identification
id: string;
filePath: string;
// location: Location; ??

export class GetterGenerator extends CallGenerator<Getter> {
override generate(
depth: number,
variableIdentifier: string,
typeIdentifier: string,
exportIdentifier: string,
name: string,
_statementPool: StatementPool
): Getter {
const constructor_ = this.sampler.sampleConstructorCall(
depth + 1,
exportIdentifier
);
// ancestory
children: {
[key: string]: Action;
};
parentId: string | undefined

return new Getter(
variableIdentifier,
typeIdentifier,
name,
prng.uniqueId(),
constructor_
);
}
}
// properties
constructable: boolean
name: string
};

export type ActionType =
| "function"
| "object"
| "constant" // maybe nice
106 changes: 106 additions & 0 deletions libraries/analysis-javascript/lib/dynamic/action/ActionFactory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* Copyright 2020-2023 Delft University of Technology and SynTest contributors
*
* This file is part of SynTest Framework - SynTest JavaScript.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { ChildProcess, fork } from "node:child_process";
import * as path from "node:path";

import * as t from "@babel/types";
import { getLogger, Logger } from "@syntest/logging";

import { Action } from "./Action";
import { ExecuteMessage, ResultMessage } from "./Executor";

export class ActionFactory {
protected static LOGGER: Logger;

private executionTimeout: number;
private _process: ChildProcess;

constructor(executionTimeout: number) {
ActionFactory.LOGGER = getLogger(ActionFactory.name);

this.executionTimeout = executionTimeout;
// eslint-disable-next-line unicorn/prefer-module
this._process = fork(path.join(__dirname, "Executor.js"));
}

exit() {
if (this._process) {
this._process.kill();
}
}

async extract(filePath: string, source: string, ast: t.Node) {
// try catch maybe?
return await this._extract(filePath, source, ast);
}

private async _extract(filePath: string, source: string, ast: t.Node): Promise<Map<string, Action>> {
if (!this._process.connected || this._process.killed) {
// eslint-disable-next-line unicorn/prefer-module
this._process = fork(path.join(__dirname, "Executor.js"));
}
const childProcess = this._process;

return await new Promise<Map<string, Action>>((resolve, reject) => {
const timeout = setTimeout(() => {
ActionFactory.LOGGER.warn(
`Execution timeout reached killing process, timeout: ${this.executionTimeout}`
);
childProcess.removeAllListeners();
childProcess.kill();
reject("timeout");
}, this.executionTimeout);

childProcess.on("message", (message: ResultMessage) => {
if (typeof message !== "object") {
return reject(
new TypeError("Invalid data received from child process")
);
}

if (message.message === "result") {
childProcess.removeAllListeners();
clearTimeout(timeout);

//
const actionMap = new Map<string, Action>()

for (const key of Object.keys(message.actions)) {
actionMap.set(key, message.actions[key])
}

return resolve(actionMap);
}
});

childProcess.on("error", (error) => {
reject(error);
});

const executeMessage: ExecuteMessage = {
message: "execute",
filePath: filePath,
source: source,
ast: ast
};

childProcess.send(executeMessage);
});
}
}
Loading