Skip to content
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

feat: provide diagnostics for cycles in calcs #270

Closed
wants to merge 7 commits into from
Closed
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
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off",
"typescript.preferences.quoteStyle": "single",
"editor.insertSpaces": false
"editor.insertSpaces": false,
"editor.formatOnSave": true
}
4 changes: 4 additions & 0 deletions client/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ export function activate(context: vscode.ExtensionContext) {
);
});

vscode.commands.registerCommand("septic.detectCycles", async () => {
let result = await client.sendRequest(protocol.detectCycles, {});
return result;
});
client.start();
}

Expand Down
6 changes: 5 additions & 1 deletion client/src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { RequestType } from "vscode-languageclient";
import { Diagnostic, RequestType } from "vscode-languageclient";

export const fsReadFile = new RequestType<{ uri: string }, number[], any>(
"septic/fs_readfile"
Expand All @@ -16,3 +16,7 @@ export const findYamlFiles = new RequestType<{}, string[], any>(
export const globFiles = new RequestType<{ uri: string }, string[], any>(
"septic/globFiles"
);

export const detectCycles = new RequestType<{}, Diagnostic[], any>(
"septic/detectCycles"
);
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@
],
"main": "./client/out/extension",
"contributes": {
"commands": [
{"command": "septic.detectCycles",
"title": "Septic: Detect Cycles in Calcs"}
],
"configuration": {
"type": "object",
"title": "Septic",
Expand Down
63 changes: 60 additions & 3 deletions server/src/language-service/diagnosticsProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { Diagnostic, DiagnosticSeverity, Range } from "vscode-languageserver";
import {
Diagnostic,
DiagnosticRelatedInformation,
DiagnosticSeverity,
Range,
} from "vscode-languageserver";
import { ISepticConfigProvider } from "./septicConfigProvider";
import { ITextDocument } from "./types/textDocument";
import {
Expand Down Expand Up @@ -33,7 +38,6 @@ import {
getCalcParamIndexInfo,
getIndexOfParam,
getValueOfAlgExpr,
formatCalcMarkdown,
formatDataType,
} from "../septic";
import { SettingsManager } from "../settings";
Expand Down Expand Up @@ -65,6 +69,7 @@ export enum DiagnosticCode {
algMaxLength = "E206",
missingPublicProperty = "E207", // Combine with under
unknownPublicProperty = "E208",
cycleAlg = "W209",
missingListLengthValue = "E301",
mismatchLengthList = "E302",
missingAttributeValue = "E303",
Expand Down Expand Up @@ -98,14 +103,16 @@ function createDiagnostic(
severity: DiagnosticSeverity,
range: Range,
message: string,
code: DiagnosticCode
code: DiagnosticCode,
relatedInformation: DiagnosticRelatedInformation[] = []
): Diagnostic {
return {
severity: severity,
range: range,
message: message,
code: code,
source: "septic",
relatedInformation: relatedInformation,
};
}

Expand Down Expand Up @@ -152,6 +159,7 @@ export function getDiagnostics(
const diagnostics: Diagnostic[] = [];
diagnostics.push(...validateObjects(cnfg, doc, refProvider));
diagnostics.push(...validateAlgs(cnfg, doc, refProvider));
diagnostics.push(...validateAlgCycles(refProvider, doc));
let disabledLines = getDisabledLines(cnfg.comments, doc);
let filteredDiags = diagnostics.filter((diag) => {
let disabledLine = disabledLines.get(diag.range.start.line);
Expand Down Expand Up @@ -968,3 +976,52 @@ function getDiagnosticCodes(codes: string): string[] {
});
return diagnosticCodes;
}

export function validateAlgCycles(
refProvider: SepticReferenceProvider,
doc: ITextDocument
): Diagnostic[] {
const diagnostics: Diagnostic[] = [];
for (let cycle of refProvider.getCycles()) {
let cycleStr = [...cycle.nodes, cycle.nodes[0]]
.map((node) => node.name)
.join("->");
const relatedInformation: DiagnosticRelatedInformation[] = [];
const rootNode = cycle.nodes[0];
const rootObject = refProvider.getObject(rootNode.name, "CalcPvr");
if (!rootObject) {
continue;
}
for (let node of cycle.nodes.slice(1)) {
let nodeObj = refProvider.getObject(node.name, "CalcPvr");
if (!nodeObj) {
continue;
}
relatedInformation.push(
DiagnosticRelatedInformation.create(
{
uri: doc.uri,
range: {
start: doc.positionAt(nodeObj.identifier!.start),
end: doc.positionAt(nodeObj.identifier!.end),
},
},
`Cycle in algs detected for CalcPvr. ${cycleStr}`
)
);
}
diagnostics.push(
createDiagnostic(
DiagnosticSeverity.Warning,
{
start: doc.positionAt(rootObject.identifier!.start),
end: doc.positionAt(rootObject.identifier!.end),
},
`Cycle in algs detected for CalcPvr. ${cycleStr}`,
DiagnosticCode.cycleAlg,
relatedInformation
)
);
}
return diagnostics;
}
6 changes: 5 additions & 1 deletion server/src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { RequestType } from "vscode-languageserver";
import { Diagnostic, RequestType } from "vscode-languageserver";

export const fsReadFile = new RequestType<{ uri: string }, number[], any>(
"septic/fs_readfile"
Expand All @@ -16,3 +16,7 @@ export const findYamlFiles = new RequestType<{}, string[], any>(
export const globFiles = new RequestType<{ uri: string }, string[], any>(
"septic/globFiles"
);

export const detectCycles = new RequestType<{}, Diagnostic[], any>(
"septic/detectCycles"
);
120 changes: 120 additions & 0 deletions server/src/septic/cycle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import {
AlgBinary,
AlgExpr,
AlgCalc,
AlgGrouping,
AlgLiteral,
AlgTokenType,
AlgUnary,
IAlgVisitor,
parseAlg,
} from "./algParser";

export class CycleDetectorVisitor implements IAlgVisitor {
variables: AlgLiteral[] = [];

visit(expr: AlgExpr) {
expr.accept(this);
}

visitBinary(expr: AlgBinary): void {
expr.left.accept(this);
expr.right?.accept(this);
}

visitLiteral(expr: AlgLiteral): void {
if (expr.type === AlgTokenType.identifier) {
this.variables.push(expr);
}
}

visitGrouping(expr: AlgGrouping): void {
expr.expr.accept(this);
}

visitCalc(expr: AlgCalc): void {
if (expr.identifier === "setgood") {
return;
}
expr.params.forEach((param) => {
param.accept(this);
});
}

visitUnary(expr: AlgUnary): void {
expr.right.accept(this);
}
}

export interface Alg {
calcPvrName: string;
content: string;
}

export interface Cycle {
nodes: Node[];
}

interface Node {
name: string;
neighbors: Set<string>;
}

export function findAlgCycles(algs: Alg[]): Cycle[] {
const graph: Map<string, Node> = new Map<string, Node>();
for (let alg of algs) {
let expr;
try {
expr = parseAlg(alg.content);
} catch {
continue;
}
let cycleVisitor = new CycleDetectorVisitor();
cycleVisitor.visit(expr);
for (let variable of cycleVisitor.variables) {
let node = graph.get(variable.value);
if (!node) {
node = {
name: variable.value,
neighbors: new Set<string>(),
};
graph.set(node.name, node);
}
node.neighbors.add(alg.calcPvrName);
}
}

const visited: Map<string, boolean> = new Map<string, boolean>();
const cycles: Cycle[] = [];
for (let node of graph.values()) {
if (!visited.get(node.name)) {
dfs(graph, node, visited, [], cycles);
}
}
return cycles;
}

function dfs(
graph: Map<string, Node>,
node: Node,
visited: Map<string, boolean>,
stack: Node[],
cycles: Cycle[]
) {
visited.set(node.name, true);
stack.push(node);
for (let neighbor of node.neighbors) {
let neighborNode = graph.get(neighbor);
if (!neighborNode) {
continue;
}
if (!visited.get(neighbor)) {
dfs(graph, neighborNode, visited, stack, cycles);
} else if (stack.includes(neighborNode)) {
cycles.push({
nodes: stack.slice(stack.indexOf(neighborNode)),
});
}
}
stack.pop();
}
2 changes: 1 addition & 1 deletion server/src/septic/docFormatting.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { bold, code, h4, horizontalRule } from "../util/markdown";
import { bold, code, h4, horizontalRule } from "../util";
import {
ISepticObjectDocumentation,
SepticAttributeDocumentation,
Expand Down
1 change: 1 addition & 0 deletions server/src/septic/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export * from "./reference";
export * from "./septicScgContext";
export * from "./docFormatting";
export * from "./calc";
export * from "./cycle";
5 changes: 3 additions & 2 deletions server/src/septic/reference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { Cycle } from "./cycle";
import { SepticObject } from "./septicElements";
import { SepticObjectHierarchy } from "./septicMetaInfo";

Expand Down Expand Up @@ -46,13 +47,13 @@ export const defaultRefValidationFunction: RefValidationFunction = (
};

export interface SepticReferenceProvider {
load(): Promise<void>;
getXvrRefs(name: string): SepticReference[] | undefined;
getAllXvrObjects(): SepticObject[];
getObjectsByIdentifier(identifier: string): SepticObject[];
validateRef(
name: string,
validationFunction: RefValidationFunction
): boolean;
updateObjectParents(hierarchy: SepticObjectHierarchy): Promise<void>;
update(): Promise<void>;
getCycles(): Cycle[];
}
Loading