From 8f903a0c7dcefecd97820e7b9d9d205c8bd65529 Mon Sep 17 00:00:00 2001 From: gmickus Date: Wed, 4 Sep 2024 13:47:56 +0300 Subject: [PATCH 1/2] Remove unused code --- src/extension.ts | 2 +- src/formatters/AAblFormatter.ts | 15 - src/formatters/AblAssignFormatter.ts | 200 ------------ src/formatters/AblBlockFormatter.ts | 142 -------- src/formatters/AblCaseFormatter.ts | 188 ----------- src/formatters/AblFindFormatter.ts | 226 ------------- src/formatters/AblForFormatter.ts | 294 ----------------- src/formatters/AblFormatterCommon.ts | 122 ------- src/formatters/AblFormatterRunner.ts | 413 ------------------------ src/formatters/AblIfFormatter.ts | 194 ----------- src/formatters/AblTemptableFormatter.ts | 141 -------- src/formatters/AblTokenFormatter.ts | 57 ---- src/formatters/IAblFormatter.ts | 10 - src/formatters/IAblFormatterRunner.ts | 14 - src/formatters/TreeLogger.ts | 43 --- src/model/FormatterSettings.ts | 73 ----- src/model/MyRange.ts | 13 - src/model/SourceChanges.ts | 5 - src/providers/AblFormatterFactory.ts | 115 ------- src/providers/AblFormatterProvider.ts | 2 +- src/providers/DebugManager.ts | 2 +- src/test/suite/extension.test.ts | 2 +- src/utils/ConfigurationManager.ts | 87 +++-- src/utils/ConfigurationManager2.ts | 112 ------- 24 files changed, 57 insertions(+), 2415 deletions(-) delete mode 100644 src/formatters/AAblFormatter.ts delete mode 100644 src/formatters/AblAssignFormatter.ts delete mode 100644 src/formatters/AblBlockFormatter.ts delete mode 100644 src/formatters/AblCaseFormatter.ts delete mode 100644 src/formatters/AblFindFormatter.ts delete mode 100644 src/formatters/AblForFormatter.ts delete mode 100644 src/formatters/AblFormatterCommon.ts delete mode 100644 src/formatters/AblFormatterRunner.ts delete mode 100644 src/formatters/AblIfFormatter.ts delete mode 100644 src/formatters/AblTemptableFormatter.ts delete mode 100644 src/formatters/AblTokenFormatter.ts delete mode 100644 src/formatters/IAblFormatter.ts delete mode 100644 src/formatters/IAblFormatterRunner.ts delete mode 100644 src/formatters/TreeLogger.ts delete mode 100644 src/model/FormatterSettings.ts delete mode 100644 src/model/MyRange.ts delete mode 100644 src/model/SourceChanges.ts delete mode 100644 src/providers/AblFormatterFactory.ts delete mode 100644 src/utils/ConfigurationManager2.ts diff --git a/src/extension.ts b/src/extension.ts index 5a78155..f14c89f 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -8,7 +8,7 @@ import { AblParserHelper } from "./parser/AblParserHelper"; import { register_memoryFileProvider } from "./model/MemoryFile"; import { FormatterCache } from "./model/FormatterCache"; import { AblDebugHoverProvider } from "./providers/AblDebugHoverProvider"; -import { ConfigurationManager2 } from "./utils/ConfigurationManager2"; +import { ConfigurationManager2 } from "./utils/ConfigurationManager"; import { enableFormatterDecorators } from "./v2/formatterFramework/enableFormatterDecorators"; import { DebugManager } from "./providers/DebugManager"; diff --git a/src/formatters/AAblFormatter.ts b/src/formatters/AAblFormatter.ts deleted file mode 100644 index 0d588cb..0000000 --- a/src/formatters/AAblFormatter.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { Range } from "vscode"; -import { IAblFormatterRunner } from "./IAblFormatterRunner"; -import { IAblFormatter } from "./IAblFormatter"; - -export abstract class AAblFormatter { - protected ablFormatterRunner: IAblFormatterRunner | undefined; - - protected ranges: Range[] = []; - - public constructor(ablFormatterRunner: IAblFormatterRunner) { - this.ablFormatterRunner = ablFormatterRunner; - } - - protected abstract getSelf(): IAblFormatter; -} diff --git a/src/formatters/AblAssignFormatter.ts b/src/formatters/AblAssignFormatter.ts deleted file mode 100644 index b948c11..0000000 --- a/src/formatters/AblAssignFormatter.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { SyntaxNode } from "web-tree-sitter"; -import { SourceChanges } from "../model/SourceChanges"; -import { AAblFormatter } from "./AAblFormatter"; -import { IAblFormatter } from "./IAblFormatter"; -import { Range, TextEdit } from "vscode"; -import { FormatterSettings } from "../model/FormatterSettings"; -import { SyntaxNodeType } from "../model/SyntaxNodeType"; - -type AssingLine = { - leftValue: string; - rightValue: string; -}; - -type AssignBlock = { - assignValues: AssingLine[]; - indentationColumn: number; - longestLeft: number; -}; - -export class AblAssignFormatter extends AAblFormatter implements IAblFormatter { - // Possible settings strcuture: - // Currently hardcoded configuration in UPPERCASE - // New line after assign YES | no - // assignments intendation NEW TAB* | no | by first line - // Align right expression YES | no - // Put ending dot in new line YES | no - // Format one line statements YES | no - // * Tab width should be inherited from global VSC setting - - private textEdit: TextEdit[] = []; - - parseNode(node: SyntaxNode): void { - if (node.type !== SyntaxNodeType.AssignStatement) { - return; - } - const assignments = node.children.filter(this.isAssignment); - - if (assignments.length === 1) { - return; - } - - let assingValues: AssingLine[] = []; - let longestLeft = 0; - const indentationColumn = node.children.filter(this.isAssign)[0] - .startPosition.column; - - if (this.ablFormatterRunner === undefined) { - return; - } - - assignments.forEach((assignment) => { - const leftChild = assignment.child(0); - const rightChild = assignment.child(2); - - if (leftChild === null || rightChild === null) { - return; - } - - if (this.ablFormatterRunner === undefined) { - return; - } - - const assignLine: AssingLine = { - leftValue: leftChild.text.trim(), - rightValue: rightChild.text.trim(), - }; - - assingValues.push(assignLine); - - if (assignLine.leftValue.length > longestLeft) { - longestLeft = assignLine.leftValue.length; - } - }); - - const assignBlock: AssignBlock = { - assignValues: assingValues, - longestLeft: longestLeft, - indentationColumn: indentationColumn, - }; - - const newBlock = this.getPrettyBlock(assignBlock); - // console.log(newBlock); - console.log(this.ablFormatterRunner - .getDocument() - .getText( - new Range( - node.startPosition.row, - 0, - node.endPosition.row, - node.endPosition.column - ) - ) - ); - - if ( - this.ablFormatterRunner - .getDocument() - .getText( - new Range( - node.startPosition.row, - 0, - node.endPosition.row, - node.endPosition.column - ) - ) === newBlock - ) { - return; - } - this.textEdit?.push( - new TextEdit( - new Range( - node.startPosition.row, - 0, - node.endPosition.row, - node.endPosition.column - ), - newBlock - ) - ); - } - - public getSourceChanges(): SourceChanges { - return { - textEdits: this.textEdit, - }; - } - - clearSourceChanges(): void { - this.textEdit.length = 0; - } - - private getPrettyBlock(assignBlock: AssignBlock): string { - const block = " " - .repeat(assignBlock.indentationColumn) - .concat( - FormatterSettings.casing! - ? SyntaxNodeType.AssignKeyword - : SyntaxNodeType.AssignKeyword.toLowerCase() - ) - .concat(FormatterSettings.newLineAfterAssign() ? "\r\n" : " ") - .concat(this.getAssigns(assignBlock)) - .concat(FormatterSettings.endDotLocationNew() ? "\r\n" : "") - .concat( - FormatterSettings.endDotLocationNew() - ? " ".repeat( - assignBlock.indentationColumn + - (FormatterSettings.endDotAlignment() - ? FormatterSettings.newLineAfterAssign() - ? FormatterSettings.tabSize() - : 7 - : 0) - ) - : "" - ) - .concat("."); - return block; - } - - private getAssigns(assignBlock: AssignBlock): string { - let assigns: string = ""; - assignBlock.assignValues.forEach((assignLine) => { - assigns = assigns.concat( - " " - .repeat( - FormatterSettings.newLineAfterAssign() - ? assignBlock.indentationColumn + FormatterSettings.tabSize() - : assigns === "" - ? 0 - : assignBlock.indentationColumn + 7 - ) - .concat(assignLine.leftValue) - .concat( - FormatterSettings.alignRightExpression() - ? " ".repeat( - assignBlock.longestLeft - - assignLine.leftValue.length - ) - : "" - ) - .concat(" = ") - .concat(assignLine.rightValue) - .concat("\r\n") - ); - }); - - return assigns.trimEnd(); - } - - private isAssignment(value: SyntaxNode): boolean { - return value.type === SyntaxNodeType.Assignment; - } - - private isAssign(value: SyntaxNode): boolean { - return value.type === SyntaxNodeType.AssignKeyword; - } - - protected getSelf(): IAblFormatter { - return this; - } -} diff --git a/src/formatters/AblBlockFormatter.ts b/src/formatters/AblBlockFormatter.ts deleted file mode 100644 index d175d81..0000000 --- a/src/formatters/AblBlockFormatter.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { SyntaxNode } from "web-tree-sitter"; -import { SourceChanges } from "../model/SourceChanges"; -import { AAblFormatter } from "./AAblFormatter"; -import { IAblFormatter } from "./IAblFormatter"; -import { Range, TextEdit } from "vscode"; -import { FormatterSettings } from "../model/FormatterSettings"; -import { SyntaxNodeType } from "../model/SyntaxNodeType"; - -export class AblBlockFormatter extends AAblFormatter implements IAblFormatter { - private indentationSize = FormatterSettings.tabSize(); - private codeLineIndentations: number[] = []; // Position is equal to line number (starts with 0), IndentationLevel - - parseNode(node: SyntaxNode): void { - if (!FormatterSettings.blockFormatting()) { - return; - } - - if (node.type === SyntaxNodeType.SourceCode) { - this.codeLineIndentations = Array(node.endPosition.row + 1).fill(0); - } - - if (this.isCodeBlock(node)) { - if ( - //Stupid workaround - node.type === SyntaxNodeType.CaseBody || - node.type === SyntaxNodeType.ClassBody - ) { - //TODO - // this.indentBlock( - // node.startPosition.row + 1, - // node.endPosition.row - // ); - } else { - this.indentBlock(node); - } - } - } - - private isCodeBlock(node: SyntaxNode): boolean { - if ( - node.type === SyntaxNodeType.Body || - node.type === SyntaxNodeType.CaseBody || - node.type === SyntaxNodeType.ClassBody - ) { - const startLine = node.startPosition.row; - const endLine = node.endPosition.row; - - // Check if the text is the same across the entire range - //WTF - // if (this.isTextSameAcrossRange(node.text, startLine, endLine)) { - // return true; - // } - return true; - } - - return false; - } - - private isTextSameAcrossRange( - text: string, - startLine: number, - endLine: number - ): boolean { - const lineText = this.ablFormatterRunner - ?.getDocument() - .getText(new Range(startLine, 0, endLine, 10000)); - - if (lineText === undefined || lineText.trim() !== text.trim()) { - return false; - } - - return true; - } - - private indentBlock(node: SyntaxNode) { - const childStatementNodes = node.children; - const targetIndentation = - node.parent !== null && node.parent.type !== "do_block" - ? node.parent.startPosition.column + this.indentationSize - : node.startPosition.column; - - // for each statements - childStatementNodes.forEach((childStatementNode) => { - const currentIndentation = childStatementNode.startPosition.column; - const indentationDiff = targetIndentation - currentIndentation; - console.log(targetIndentation, currentIndentation, indentationDiff); - - const startRow = childStatementNode.startPosition.row; - const endRow = childStatementNode.endPosition.row; - const length = endRow - startRow + 1; - - const statementRows = Array.from( - { length }, - (_, index) => startRow + index - ); - - statementRows.forEach((row) => { - this.codeLineIndentations[row] = indentationDiff; - }); - }); - } - - getSourceChanges(): SourceChanges { - console.log(this.codeLineIndentations); - - let textEdits: TextEdit[] = []; - this.codeLineIndentations.forEach((indentationLevel, index) => { - console.log("indentationLevel", indentationLevel); - const range = new Range(index, 0, index, 10000); - - textEdits.push( - new TextEdit(range, this.getTrimedLine(indentationLevel, range)) - ); - }); - - console.log(textEdits); - return { - textEdits: textEdits, - }; - } - - clearSourceChanges(): void { - let textEdits: TextEdit[] = []; - } - - private getTrimedLine(indentationLevel: number, range: Range): string { - const text = this.ablFormatterRunner?.getDocument().getText(range); - if (text === undefined) { - return ""; - } - - if (indentationLevel > 0) { - return " ".repeat(indentationLevel).concat(text); - } else { - return text.substring(-indentationLevel); - } - } - - protected getSelf(): IAblFormatter { - return this; - } -} diff --git a/src/formatters/AblCaseFormatter.ts b/src/formatters/AblCaseFormatter.ts deleted file mode 100644 index 2e56b08..0000000 --- a/src/formatters/AblCaseFormatter.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { SyntaxNode } from "web-tree-sitter"; -import { SourceChanges } from "../model/SourceChanges"; -import { AAblFormatter } from "./AAblFormatter"; -import { IAblFormatter } from "./IAblFormatter"; -import { AblFormatterCommon } from "./AblFormatterCommon"; -import { Range, TextEdit } from "vscode"; -import { FormatterSettings } from "../model/FormatterSettings"; -import { SyntaxNodeType } from "../model/SyntaxNodeType"; - -export class AblCaseFormatter extends AAblFormatter implements IAblFormatter { - private startColumn = 0; - private caseBlockValueColumn = 0; - private caseBlockWhenValueColumn = 0; - private caseKey = ""; // CASE - private recordValue = ""; - private caseBodyValue = ""; - - private textEdit: TextEdit[] = []; - - private ablFormatterCommon: AblFormatterCommon = new AblFormatterCommon(); - - - protected getSelf(): IAblFormatter { - return this; - } - - parseNode(node: SyntaxNode): void { - if (!FormatterSettings.caseFormatting()) { - return; - } - - if (node.type !== SyntaxNodeType.CaseStatement) { - return; - } - - if (this.ablFormatterRunner === undefined) { - return; - } - - this.collectCaseStructure(node); - - const newBlock = this.getPrettyBlock(); - - if ( - this.ablFormatterRunner - .getDocument() - .getText( - new Range( - node.startPosition.row, - node.startPosition.column, - node.endPosition.row, - node.endPosition.column - ) - ) === newBlock - ) { - return; - } - this.textEdit?.push( - new TextEdit( - new Range( - node.startPosition.row, - node.startPosition.column, - node.endPosition.row, - node.endPosition.column - ), - newBlock - ) - ); - } - - getSourceChanges(): SourceChanges { - return { - textEdits: this.textEdit, - }; - } - - clearSourceChanges(): void { - this.textEdit.length = 0; - } - - private collectCaseStructure(node: SyntaxNode) { - this.startColumn = node.startPosition.column; - this.caseKey = this.getCaseKey(node); - this.recordValue = this.getRecordValue(node, false); - this.caseBlockValueColumn = this.startColumn + FormatterSettings.tabSize(); - this.caseBlockWhenValueColumn = this.startColumn + FormatterSettings.tabSize() + - FormatterSettings.tabSize(); - - const bodyNode = this.getCaseBodyNode(node); - - if (bodyNode !== undefined) { - this.caseBodyValue = this.getCaseBodyBlock(bodyNode); - } - } - - private getCaseKey(node: SyntaxNode): string { - return this.ablFormatterCommon.getStatementKey(node, this.ablFormatterRunner); - } - - private getRecordValue(node: SyntaxNode, isSecond: boolean): string { - return this.ablFormatterCommon.getRecordValue(node, isSecond, this.ablFormatterRunner); - } - - private getCaseBodyNode(node: SyntaxNode): SyntaxNode | undefined { - return this.ablFormatterCommon.getNodeByType(node, SyntaxNodeType.CaseBody); - } - - private getCaseBodyBlock(node: SyntaxNode): string { - let resultString = ""; - - node.children.forEach((child) => { - if (this.ablFormatterRunner === undefined) { - return ""; - } - - const bodyNode = child; - - if (bodyNode === null) { - return ""; - } - - resultString = resultString + - this.getCaseBodyBranchBlock(bodyNode) + - "\r\n".concat(" ".repeat(this.caseBlockValueColumn)); - }); - - return resultString; - } - - private getCaseBodyBranchBlock(node: SyntaxNode): string { - let resultString = ""; - let doBlock = false; - - if (node.type === SyntaxNodeType.CaseWhenBranch || node.type === SyntaxNodeType.CaseOtherwiseBranch) { - - node.children.forEach((child) => { - if (child.type === SyntaxNodeType.DoBlock) { - doBlock = true; - } - }); - - node.children.forEach((child) => { - resultString = resultString.concat( - this.getCaseExpressionString(child, "\r\n".concat(" ".repeat(this.caseBlockWhenValueColumn)), doBlock) - ); - }); - - } - - return resultString.trim(); - } - - private getCaseExpressionString(node: SyntaxNode, separator: string, doBlock: boolean): string { - switch (node.type) { - case SyntaxNodeType.ThenKeyword: - if (doBlock) { - return node.text; - } else { - return ` ${node.text.trim()}${separator}`; - } - case SyntaxNodeType.AndKeyword: - case SyntaxNodeType.OrKeyword: - case SyntaxNodeType.OtherwiseKeyword: - return ` ${node.text.trim()}${separator}`; - case SyntaxNodeType.DoBlock: - return this.ablFormatterCommon.getDoBlock(node, this.caseBlockWhenValueColumn, this.caseBlockValueColumn); - default: - return node.text; - } - } - - private getPrettyBlock(): string { - const block = "" - .concat(this.caseKey.trim()) - .concat(" ") - .concat(this.recordValue.trim()) - .concat(":") - .concat(this.caseBodyValue === "" ? " " : "\r\n") - .concat(this.caseBodyValue === "" ? "" : " ".repeat(this.caseBlockValueColumn)) - .concat(this.caseBodyValue.trim()) - .concat("\r\n") - .concat(" ".repeat(this.startColumn)) - .concat(FormatterSettings.casing() ? "END CASE" : "end case") - .concat("."); - - return block; - } -} diff --git a/src/formatters/AblFindFormatter.ts b/src/formatters/AblFindFormatter.ts deleted file mode 100644 index 7726a09..0000000 --- a/src/formatters/AblFindFormatter.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { SyntaxNode } from "web-tree-sitter"; -import { SourceChanges } from "../model/SourceChanges"; -import { AAblFormatter } from "./AAblFormatter"; -import { IAblFormatter } from "./IAblFormatter"; -import { AblFormatterCommon } from "./AblFormatterCommon"; -import { MyRange } from "../model/MyRange"; -import { Range, TextEdit } from "vscode"; -import { SyntaxNodeType } from "../model/SyntaxNodeType"; - -export class AblFindFormatter extends AAblFormatter implements IAblFormatter { - // TODO find with current keyword structure - private startColumn = 0; - private recordValueColumn = 0; - private findKey = ""; // FIND - private findTypeKey = ""; // FIRST | LAST | NEXT | PREV - private recordValue = ""; - private constantValue = ""; - private ofKey = ""; // OF - private ofValue = ""; - private whereKey = ""; // WHERE - private whereValue = ""; - private useIndexKey = ""; //USE-INDEX - private useIndexValue = ""; //USE-INDEX - // TODO USING - private queryTuningLockKey = ""; // SHARE-LOCK | EXCLUSIVE-LOCK | NO-LOCK - private queryTuningNoWaitKey = ""; // NO-WAIT - private queryTuningNoPrefetchKey = ""; // NO-PREFETCH - private queryTuningNoErrorKey = ""; // NO-ERROR - - private textEdit: TextEdit[] = []; - - private ablFormatterCommon: AblFormatterCommon = new AblFormatterCommon(); - - protected getSelf(): IAblFormatter { - return this; - } - - parseNode(node: SyntaxNode): void { - if (node.type !== SyntaxNodeType.FindStatement) { - return; - } - - if (this.ablFormatterRunner === undefined) { - return; - } - - this.collectFindStructure(node); - - const newBlock = this.getPrettyBlock(); - - if ( - this.ablFormatterRunner - .getDocument() - .getText( - new Range( - node.startPosition.row, - node.startPosition.column, - node.endPosition.row, - node.endPosition.column - ) - ) === newBlock - ) { - return; - } - this.textEdit?.push( - new TextEdit( - new Range( - node.startPosition.row, - node.startPosition.column, - node.endPosition.row, - node.endPosition.column - ), - newBlock - ) - ); - } - - getSourceChanges(): SourceChanges { - return { - textEdits: this.textEdit, - }; - } - - clearSourceChanges(): void { - this.textEdit.length = 0; - } - - private collectFindStructure(node: SyntaxNode) { - this.startColumn = node.startPosition.column; - this.findKey = this.getFindKey(node); - this.findTypeKey = this.getFindTypeKey(node); - this.recordValue = this.getRecordValue(node, this.findTypeKey !== ""); - this.recordValueColumn = this.startColumn + 6 + this.findTypeKey.length; - - const whereNode = this.getWhereNode(node); - - if (whereNode !== undefined) { - this.whereKey = this.getWhereKey(whereNode); - - this.whereValue = this.getPrettyWhereBlock( - whereNode, - "\r\n".concat(" ".repeat(this.recordValueColumn)) - ); - } - - this.assignQueryTuningStatements(node); - } - - private getPrettyWhereBlock(node: SyntaxNode, separator: string): string { - return this.ablFormatterCommon.getPrettyWhereBlock(node, separator); - } - - private getExpressionString(node: SyntaxNode, separator: string): string { - return this.ablFormatterCommon.getExpressionString(node, separator); - } - - private getPrettyBlock(): string { - const block = "" - .concat(this.findKey) - .concat(this.findTypeKey === "" ? "" : " ") - .concat(this.findTypeKey.trim()) - .concat(this.recordValue === "" ? "" : " ") - .concat(this.recordValue.trim()) - .concat(this.whereKey === "" ? "" : " ") - .concat(this.whereKey.trim()) - .concat(this.whereValue === "" ? "" : " ") - .concat(this.whereValue === "" ? " " : "\r\n") - .concat( - this.whereValue === "" ? "" : " ".repeat(this.recordValueColumn) - ) - .concat(this.whereValue) - .concat(this.whereValue === "" ? "" : "\r\n") - .concat( - this.whereValue === "" ? "" : " ".repeat(this.recordValueColumn) - ) - .concat(this.queryTuningLockKey.trim()) - .concat(this.queryTuningNoWaitKey === "" ? "" : " ") - .concat(this.queryTuningNoWaitKey.trim()) - .concat(this.queryTuningNoPrefetchKey === "" ? "" : " ") - .concat(this.queryTuningNoPrefetchKey.trim()) - .concat(this.queryTuningNoErrorKey === "" ? "" : " ") - .concat(this.queryTuningNoErrorKey.trim()) - .concat("."); - return block; - } - - private getFindKey(node: SyntaxNode): string { - return this.ablFormatterCommon.getStatementKey(node, this.ablFormatterRunner); - } - - private getFindTypeKey(node: SyntaxNode): string { - const findTypeNode = node.child(1); - - if (findTypeNode === null) { - return ""; // ERROR - } - - if (this.ablFormatterRunner === undefined) { - return ""; //ERROR - } - - if ( - findTypeNode.type === SyntaxNodeType.FirstKeyword || - findTypeNode.type === SyntaxNodeType.LastKeyword || - findTypeNode.type === SyntaxNodeType.NextKeyword || - findTypeNode.type === SyntaxNodeType.PrevKeyword - ) { - return findTypeNode.text; - } else { - return ""; //EMPTY - } - } - - private getRecordValue(node: SyntaxNode, isSecond: boolean): string { - return this.ablFormatterCommon.getRecordValue(node, isSecond, this.ablFormatterRunner); - } - - private getWhereNode(node: SyntaxNode): SyntaxNode | undefined { - return this.ablFormatterCommon.getNodeByType(node, SyntaxNodeType.WhereClause); - } - - private getWhereKey(whereNode: SyntaxNode): string { - return this.ablFormatterCommon.getKeyByType(whereNode, SyntaxNodeType.WhereKeyword, this.ablFormatterRunner); - } - - private assignQueryTuningStatements(node: SyntaxNode): void { - node.children.forEach((child) => { - if (this.ablFormatterRunner === undefined) { - return; //ERROR - } - - if (child.type !== SyntaxNodeType.QueryTuning) { - return; - } - - const tuneNode = child.child(0); - - if (tuneNode === null) { - return ""; // ERROR - } - - const text = tuneNode.text; - - switch (tuneNode.type) { - case SyntaxNodeType.ShareLockKeyword: - case SyntaxNodeType.ExclLockKeyword: - case SyntaxNodeType.NoLockKeyword: { - this.queryTuningLockKey = text; - break; - } - case SyntaxNodeType.NoWaitKeyword: { - this.queryTuningNoWaitKey = text; - break; - } - case SyntaxNodeType.NoPrefetchKeyword: { - this.queryTuningNoPrefetchKey = text; - break; - } - case SyntaxNodeType.NoErrorKeyword: { - this.queryTuningNoErrorKey = text; - break; - } - } - }); - } -} diff --git a/src/formatters/AblForFormatter.ts b/src/formatters/AblForFormatter.ts deleted file mode 100644 index def8e01..0000000 --- a/src/formatters/AblForFormatter.ts +++ /dev/null @@ -1,294 +0,0 @@ -import { SyntaxNode } from "web-tree-sitter"; -import { SourceChanges } from "../model/SourceChanges"; -import { AAblFormatter } from "./AAblFormatter"; -import { IAblFormatter } from "./IAblFormatter"; -import { AblFormatterCommon } from "./AblFormatterCommon"; -import { Range, TextEdit } from "vscode"; -import { SyntaxNodeType } from "../model/SyntaxNodeType"; -import { FormatterSettings } from "../model/FormatterSettings"; - -export class AblForFormatter extends AAblFormatter implements IAblFormatter { - private startColumn = 0; - private recordValueColumn = 0; - private forBlockValueColumn = 0; - private tab = FormatterSettings.tabSize(); - private forKey = ""; // FOR - private forTypeKey = ""; // EACH | FIRST | LAST - private recordValue = ""; - private byValue = ""; // BY - private whereKey = ""; // WHERE - private whereValue = ""; - private forBodyValue = ""; - private useIndexValue = ""; //USE-INDEX - private queryTuningLockKey = ""; // SHARE-LOCK | EXCLUSIVE-LOCK | NO-LOCK - private queryTuningNoPrefetchKey = ""; // NO-PREFETCH - private endValue = ""; - - private textEdit: TextEdit[] = []; - - private ablFormatterCommon: AblFormatterCommon = new AblFormatterCommon(); - - protected getSelf(): IAblFormatter { - return this; - } - - parseNode(node: SyntaxNode): void { - if (node.type !== SyntaxNodeType.ForStatement) { - return; - } - - if (this.ablFormatterRunner === undefined) { - return; - } - - this.collectForStructure(node); - - const newBlock = this.getPrettyBlock(); - - if ( - this.ablFormatterRunner - .getDocument() - .getText( - new Range( - node.startPosition.row, - node.startPosition.column, - node.endPosition.row, - node.endPosition.column - ) - ) === newBlock - ) { - return; - } - this.textEdit?.push( - new TextEdit( - new Range( - node.startPosition.row, - node.startPosition.column, - node.endPosition.row, - node.endPosition.column - ), - newBlock - ) - ); - } - - getSourceChanges(): SourceChanges { - return { - textEdits: this.textEdit, - }; - } - - clearSourceChanges(): void { - this.textEdit.length = 0; - } - - private collectForStructure(node: SyntaxNode) { - this.startColumn = node.startPosition.column; - this.forKey = this.getForKey(node); - this.forTypeKey = this.getForTypeKey(node); - this.recordValue = this.getRecordValue(node, this.forTypeKey !== ""); - this.recordValueColumn = this.startColumn + this.forKey.length + this.forTypeKey.length + 1; // +1 is a space between FOR EACH - this.forBlockValueColumn = this.startColumn + this.tab; - - this.assignQueryTuningStatements(node); - - const whereNode = this.getWhereNode(node); - - if (whereNode !== undefined) { - this.whereKey = this.getWhereKey(whereNode); - - this.whereValue = this.getPrettyWhereBlock(whereNode, "\r\n".concat(" ".repeat(this.recordValueColumn))); - } - - this.assignByValue(node); - - const bodyNode = this.getForBodyNode(node); - - if (bodyNode !== undefined) { - this.forBodyValue = this.getPrettyBodyBlock(bodyNode, "\r\n".concat(" ".repeat(this.forBlockValueColumn)) - ); - } - - this.assignEndValue(node); - } - - private getForTypeKey(node: SyntaxNode): string { - const forTypeNode = node.child(1); - - if (forTypeNode === null) { - return ""; - } - - if (this.ablFormatterRunner === undefined) { - return ""; - } - - if ( - forTypeNode.type === SyntaxNodeType.EachKeyword || - forTypeNode.type === SyntaxNodeType.FirstKeyword || - forTypeNode.type === SyntaxNodeType.LastKeyword - ) { - return forTypeNode.text; - } else { - return ""; - } - } - - private getForKey(node: SyntaxNode): string { - return this.ablFormatterCommon.getStatementKey(node, this.ablFormatterRunner); - } - - private getRecordValue(node: SyntaxNode, isSecond: boolean): string { - return this.ablFormatterCommon.getRecordValue(node, isSecond, this.ablFormatterRunner); - } - - private assignQueryTuningStatements(node: SyntaxNode): void { - node.children.forEach((child) => { - if (this.ablFormatterRunner === undefined) { - return; - } - - if (child.type !== SyntaxNodeType.QueryTuning) { - return; - } - - const tuneNode = child.child(0); - - if (tuneNode === null) { - return ""; - } - - const text = tuneNode.text; - - switch (tuneNode.type) { - case SyntaxNodeType.ShareLockKeyword: - case SyntaxNodeType.ExclLockKeyword: { - this.queryTuningLockKey = text; - break; - } - case SyntaxNodeType.NoLockKeyword: { - this.queryTuningLockKey = text; - break; - } - case SyntaxNodeType.NoPrefetchKeyword: { - this.queryTuningNoPrefetchKey = text; - break; - } - } - }); - } - - private getWhereNode(node: SyntaxNode): SyntaxNode | undefined { - return this.ablFormatterCommon.getNodeByType(node, SyntaxNodeType.WhereClause); - } - - private getWhereKey(whereNode: SyntaxNode): string { - return this.ablFormatterCommon.getKeyByType(whereNode, SyntaxNodeType.WhereKeyword, this.ablFormatterRunner); - } - - private getPrettyWhereBlock(node: SyntaxNode, separator: string): string { - return this.ablFormatterCommon.getPrettyWhereBlock(node, separator); - } - - private assignByValue(node: SyntaxNode): void { - node.children.forEach((child) => { - if (child.type !== SyntaxNodeType.SortClause) { - return; - } - - if (this.ablFormatterRunner === undefined) { - return ""; - } - - const byNode = child; - - if (byNode === null) { - return ""; - } - - this.byValue = byNode.text; - - }); - } - - private getForBodyNode(node: SyntaxNode): SyntaxNode | undefined { - return this.ablFormatterCommon.getNodeByType(node, SyntaxNodeType.Body); - } - - private getPrettyBodyBlock(node: SyntaxNode, separator: string): string { - let resultString = ""; - - node.children.forEach((child) => { - if (this.ablFormatterRunner === undefined) { - return ""; - } - - const bodyNode = child; - - if (bodyNode === null) { - return ""; - } - - resultString = resultString + - bodyNode.text - + separator; - }); - - return resultString; - } - - private assignEndValue(node: SyntaxNode): void { - node.children.forEach((child) => { - if (child.type !== SyntaxNodeType.EndKeyword) { - return; - } - - if (this.ablFormatterRunner === undefined) { - return ""; - } - - const endNode = child; - - if (endNode === null) { - return ""; - } - - this.endValue = endNode.text; - - }); - } - - private getExpressionString(node: SyntaxNode, separator: string): string { - return this.ablFormatterCommon.getExpressionString(node, separator); - } - - private getPrettyBlock(): string { - const block = "" - .concat(this.forKey) - .concat(this.forTypeKey === "" ? "" : " ") - .concat(this.forTypeKey.trim()) - .concat(this.recordValue === "" ? "" : " ") - .concat(this.recordValue.trim()) - .concat(this.queryTuningLockKey === "" ? "" : " ") - .concat(this.queryTuningLockKey.trim()) - .concat(this.whereKey === "" ? "" : " ") - .concat(this.whereKey.trim()) - .concat(this.whereValue === "" ? "" : " ") - .concat(this.whereValue === "" ? " " : "\r\n") - .concat(this.whereValue === "" ? "" : " ".repeat(this.recordValueColumn)) - .concat(this.whereValue.trim()) - .concat(this.byValue === "" ? "" : " ") - .concat(this.byValue.trim()) - .concat(":") - .concat(this.forBodyValue === "" ? " " : "\r\n") - .concat(this.forBodyValue === "" ? "" : " ".repeat(this.forBlockValueColumn)) - .concat(this.forBodyValue.trim()) - .concat(this.queryTuningNoPrefetchKey === "" ? "" : " ") - .concat(this.queryTuningNoPrefetchKey.trim()) - .concat("\r\n") - .concat(" ".repeat(this.startColumn)) - .concat(this.endValue) - .concat("."); - return block; - } -} diff --git a/src/formatters/AblFormatterCommon.ts b/src/formatters/AblFormatterCommon.ts deleted file mode 100644 index 9a15564..0000000 --- a/src/formatters/AblFormatterCommon.ts +++ /dev/null @@ -1,122 +0,0 @@ -/** - * AblFormatterCommon - handles common formatting functionality for Formatters. - * - * @class - */ - -import { SyntaxNode } from "web-tree-sitter"; -import { IAblFormatterRunner } from "./IAblFormatterRunner"; -import { MyRange } from "../model/MyRange"; -import { FormatterSettings } from "../model/FormatterSettings"; -import { SyntaxNodeType } from "../model/SyntaxNodeType"; - -export class AblFormatterCommon { - public getExpressionString(node: SyntaxNode, separator: string): string { - switch (node.type.trim()) { - case "comparison_expression": - return node.text.trim(); - case "AND": - case "OR": - return ` ${node.text.trim()}${separator}`; - case "parenthesized_expression": - let resultString = ""; - - node.children.forEach((child) => { - child.children.forEach((child2) => { - resultString += this.getExpressionString(child2, separator); - }); - }); - - return `(${resultString})`; - default: - return ""; - } - } - - public getRecordValue(node: SyntaxNode, isSecond: boolean, ablFormatterRunner: IAblFormatterRunner | undefined): string { - const recordValue = isSecond ? node.child(2) : node.child(1); - - if (recordValue === null || ablFormatterRunner === undefined || recordValue.type !== "identifier") { - return ""; - } - - return recordValue.text; - } - - public getStatementKey(node: SyntaxNode, ablFormatterRunner: IAblFormatterRunner | undefined): string { - const statementNode = node.child(0); - - if (statementNode === null || ablFormatterRunner === undefined) { - return ""; - } - - return statementNode.text; - } - - public getNodeByType(node: SyntaxNode, type: string): SyntaxNode | undefined { - let nodeByType; - - node.children.forEach((child) => { - if (child.type !== type) { - return; - } - - nodeByType = child; - - if (nodeByType === null) { - return; - } - - }); - - return nodeByType; - } - - public getKeyByType(whereNode: SyntaxNode, type: string, ablFormatterRunner: IAblFormatterRunner | undefined): string { - const keyByType = whereNode.child(0); - - if (keyByType === null || ablFormatterRunner === undefined || keyByType.type !== type) { - return ""; - } - - return keyByType.text; - } - - public getPrettyWhereBlock(node: SyntaxNode, separator: string): string { - const logicalExpression = node.child(1); - let resultString = ""; - - if (logicalExpression === null) { - return node.text.trim(); - } - - if (logicalExpression.type !== "logical_expression") { - return logicalExpression.text.trim(); - } - - logicalExpression.children.forEach((child) => { - resultString = resultString.concat( - this.getExpressionString(child, separator) - ); - }); - - return resultString.replace(" (", "("); - } - - public getDoBlock(node: SyntaxNode, blockValueColumn: number, startColumn: number): string { - let resultString = ""; - - node.children.forEach((child) => { - if (child.type === SyntaxNodeType.Body) { - resultString = (FormatterSettings.casing() ? " DO:" : " do:") + - "\r\n".concat(" ".repeat(blockValueColumn)) + - child.text + - "\r\n".concat(" ".repeat(startColumn)) + - (FormatterSettings.casing() ? "END." : "end.") + - "\r\n".concat(" ".repeat(startColumn)); - } - }); - - return resultString; - } -} \ No newline at end of file diff --git a/src/formatters/AblFormatterRunner.ts b/src/formatters/AblFormatterRunner.ts deleted file mode 100644 index 1ad79c1..0000000 --- a/src/formatters/AblFormatterRunner.ts +++ /dev/null @@ -1,413 +0,0 @@ -import { Range, TextDocument, TextEdit, TextEditor, TextEditorEdit, WorkspaceEdit, window, workspace } from "vscode"; -import { ParseResult } from "../model/ParseResult"; -import { IAblFormatter } from "./IAblFormatter"; -import Parser, { SyntaxNode, Tree } from "web-tree-sitter"; -import { SourceChanges } from "../model/SourceChanges"; -import { IAblFormatterRunner } from "./IAblFormatterRunner"; -import { ConfigurationManager } from "../utils/ConfigurationManager"; -import { AblFormatterFactory } from "../providers/AblFormatterFactory"; -import { IParserHelper } from "../parser/IParserHelper"; -import { FileIdentifier } from "../model/FileIdentifier"; -import { MemoryFile } from "../model/MemoryFile"; -import { FormatterCache } from "../model/FormatterCache"; -import { SyntaxNodeType } from "../model/SyntaxNodeType"; -import * as crypto from 'crypto'; -import * as fs from 'fs'; - -export class AblFormatterRunner implements IAblFormatterRunner { - private document: TextDocument | undefined; - private inMemoryDocument: TextDocument | undefined; - private originalDocument: TextDocument | undefined; - private parserResult: ParseResult | undefined; - private ablBaseFormatters: IAblFormatter[] = []; - private ablFormatters: IAblFormatter[] = []; - private factory: AblFormatterFactory; - private accumulatedEdits: TextEdit[] = []; - private parserHelper: IParserHelper | undefined; - private editor = window.activeTextEditor; - private selection = this.editor!.selection; - private textRange: Range | undefined; - private documentText: string | undefined; - private filePath: string | undefined; - private changedRanges: Parser.Range[] | undefined; - private nodeByRanges: SyntaxNode | undefined; - private editableParent: SyntaxNode | undefined; - private formattedBefore: boolean = false; - private parserResultForSaving: ParseResult | undefined; - private enablePartialFormatting: boolean = false; - - public constructor(factory: AblFormatterFactory) { - this.factory = factory; - } - - public setDocument(document: TextDocument): IAblFormatterRunner { - this.document = document; - return this; - } - public setParserResult(parserResult: ParseResult): IAblFormatterRunner { - this.parserResult = parserResult; - return this; - } - public setParserHelper(parserHelper: IParserHelper): IAblFormatterRunner { - this.parserHelper = parserHelper; - return this; - } - - public start(): IAblFormatterRunner { - if (this.parserResult === undefined) { - console.log("Parser result is empty!"); - return this; - } - - const settingsString = this.getOverrideSettingsComment( - this.parserResult.tree.rootNode - ); - if (settingsString !== undefined) { - ConfigurationManager.setOverridingSettings( - JSON.parse(settingsString) - ); - } else { - ConfigurationManager.setOverridingSettings(undefined); - } - - this.ablBaseFormatters = this.factory.getBaseFormatters(); - this.ablFormatters = this.factory.getFormatters(); - - this.setBaseEdits(); - - return this; - } - - private async setBaseEdits(): Promise{ - this.filePath = this.document?.uri.fsPath; - const currentHash = await this.calculateHashOfFile(this.filePath!); - const cachedHash = FormatterCache.getHash(this.filePath!); - - this.formattedBefore = false; - - if (this.enablePartialFormatting && - cachedHash === currentHash) { - console.log('File has been formatted before.'); - - this.parserResult = this.parserHelper!.parse(new FileIdentifier(this.document!.fileName, this.document!.version), this.getDocument().getText()); - - FormatterCache.getTree(this.filePath!); - - this.changedRanges = FormatterCache.getTree(this.filePath!)!.getChangedRanges(this.parserResult.tree); - - this.changedRanges.forEach((range) => { - - // first find the changed node (keep in mind, searching by ranges not always returns the corect node) - this.nodeByRanges = this.findNodeByRanges(this.parserResult!.tree.rootNode, range); - - this.editableParent = this.getEditableParentForStatements(this.nodeByRanges!.parent!); - - if (this.editableParent === undefined) { - this.editableParent = this.getEditableParentForDoBlock(this.nodeByRanges!); - } - - if (this.editableParent === undefined) { - this.editableParent = this.nodeByRanges; - } - - if (this.editableParent !== undefined) { - this.formattedBefore = true; - } - }); - - } else { - console.log('File needs first time formatting.'); - } - - this.getText(false, this.editor!); - - // create the in-memory document - let memfile = MemoryFile.createDocument("ts"); - memfile.write(this.documentText!); - - // create a vscode.TextDocument from the in-memory document. - this.inMemoryDocument = await workspace.openTextDocument(memfile.getUri()); - this.originalDocument = this.getDocument(); - - this.setDocument(this.inMemoryDocument); - - this.parserResult = this.parserHelper!.parse(new FileIdentifier(this.document!.fileName, this.document!.version), this.getDocument().getText()); - - this.visitTree(this.parserResult.tree.rootNode, this.ablBaseFormatters); - - // Store the accumulated base edits (only block editing) - this.accumulatedEdits = this.getBaseSourceChanges().textEdits; - - this.applyEdits().then(() => { - FormatterCache.updateHash(this.filePath!, currentHash); - }); - } - - private async applyEdits(): Promise { - if (this.document) { - - let modifiedContent = ""; - - // Apply edits to in-memory file content - this.accumulatedEdits.forEach(edit => { - modifiedContent = modifiedContent + - edit.newText + - "\r\n"; - }); - - if (modifiedContent.length === 0) { - modifiedContent = this.getDocument().getText(); - } - - // create the in-memory document - let memfile = MemoryFile.createDocument("ts"); - memfile.write(modifiedContent); - - // create a vscode.TextDocument from the in-memory document. - this.inMemoryDocument = await workspace.openTextDocument(memfile.getUri()); - this.originalDocument = this.getDocument(); - - this.setDocument(this.inMemoryDocument); - - this.getText(false, this.editor!); - - // first adding changes by base formatters (currently block formatting) - this.editor!.edit((edit: TextEditorEdit) => { - edit.replace(this.textRange!, this.inMemoryDocument!.getText().trim()); - }, {undoStopBefore: false, undoStopAfter: false}) - .then(async success => { - if (!success) { - return; - } - - this.getText(false, this.editor!); - - this.parserResult = this.parserHelper!.parse(new FileIdentifier(this.document!.fileName, this.document!.version), this.documentText!); - - this.visitTree(this.parserResult.tree.rootNode, this.ablFormatters); - - this.addFormattersChanges(this.editor!, this.getSourceChanges().textEdits.length, 0); - - }); - } - } - - private addFormattersChanges(editor: TextEditor, count: number, startNum: number): void { - - if (startNum === count) { - return; - } - - this.selection = this.editor!.selection; - - /** - * Getting the correct editing range. - * Three cases: selected text, already formatted file (so formatting only the parent node) - * and the whole file text - **/ - if (this.selection && !this.selection.isEmpty) { - this.textRange = new Range(this.selection.start.line + this.getSourceChanges().textEdits[startNum].range.start.line, - this.selection.start.character + this.getSourceChanges().textEdits[startNum].range.start.character, - this.selection.start.line + this.getSourceChanges().textEdits[startNum].range.end.line, - this.getSourceChanges().textEdits[startNum].range.end.character); - } else if (this.formattedBefore) { - this.textRange = new Range(this.editableParent!.startPosition.row + this.getSourceChanges().textEdits[startNum].range.start.line, - this.getSourceChanges().textEdits[startNum].range.start.character, - this.editableParent!.startPosition.row + this.getSourceChanges().textEdits[startNum].range.end.line, - this.getSourceChanges().textEdits[startNum].range.end.character); - } else { - this.textRange = this.getSourceChanges().textEdits[startNum].range; - } - - editor.edit((edit: TextEditorEdit) => { - edit.replace(this.textRange!, this.getSourceChanges().textEdits[startNum].newText); - }, {undoStopBefore: false, undoStopAfter: false}) - .then(success => { - if (!success) { - return; - } - - this.clearSourceChanges(); - this.getText(true, this.editor!); - - this.parserResult = this.parserHelper!.parse(new FileIdentifier(editor.document!.fileName, editor.document!.version), this.documentText!); - - this.visitTree(this.parserResult.tree.rootNode, this.ablFormatters); - - startNum = startNum + 1; - - this.addFormattersChanges(editor, count, startNum); - - // saving the current tree to cache - this.parserResultForSaving = this.parserHelper!.parse(new FileIdentifier(editor.document!.fileName, editor.document!.version), editor.document!.getText()); - FormatterCache.setTree(this.filePath!, this.parserResultForSaving!.tree); - - }); - } - - /** - * Method for getting the correct text and it's ranges for editing. - * Three cases: selected text, already formatted file (so formatting only the parent node) - * and the whole file text - **/ - private getText(fromEditor: boolean, editor: TextEditor): void { - this.selection = this.editor!.selection; - - if (this.selection && !this.selection.isEmpty) { - this.textRange = new Range(this.selection.start.line, this.selection.start.character, this.selection.end.line, this.selection.end.character); - this.documentText = editor.document.getText(this.textRange); - } else if (this.formattedBefore) { - this.textRange = new Range(this.editableParent!.startPosition.row, 0, this.editableParent!.endPosition.row, this.editableParent!.endPosition.column); - this.documentText = editor.document.getText(this.textRange); - } else { - if (fromEditor) { - this.documentText = editor.document!.getText(); - } else { - this.textRange = new Range(this.document!.lineAt(0).range.start, this.document!.lineAt(this.document!.lineCount - 1).range.end); - this.documentText = this.getDocument().getText(); - } - } - } - - public getBaseSourceChanges(): SourceChanges { - let sourceChanges: SourceChanges = { textEdits: [] }; - - this.ablBaseFormatters.forEach((formatter) => { - sourceChanges.textEdits = sourceChanges.textEdits.concat( - formatter.getSourceChanges().textEdits - ); - }); - - return sourceChanges; - } - - public getSourceChanges(): SourceChanges { - let sourceChanges: SourceChanges = { textEdits: [] }; - - sourceChanges.textEdits.length = 0; - - this.ablFormatters.forEach((formatter) => { - sourceChanges.textEdits = sourceChanges.textEdits.concat( - formatter.getSourceChanges().textEdits - ); - }); - - return sourceChanges; - } - - public clearSourceChanges(): void { - - this.ablFormatters.forEach((formatter) => { - formatter.clearSourceChanges(); - }); - } - - public getDocument(): TextDocument { - if (this.document === undefined) { - throw new Error("Document is undefined!"); - } - return this.document; - } - - private visitTree(node: Parser.SyntaxNode, formatters: IAblFormatter[]) { - formatters.forEach((formatter) => formatter.parseNode(node)); - node.children.forEach((child) => { - this.visitTree(child, formatters); - }); - } - - public getOverrideSettingsComment(node: SyntaxNode): string | undefined { - const firstChildNode = node.child(0); - - if (firstChildNode === null) { - return undefined; - } - - if (!firstChildNode.text.includes("formatterSettingsOverride")) { - return undefined; - } - - const secondChildNode = node.child(1); - if (secondChildNode === null) { - return undefined; - } - - return secondChildNode.text.substring( - 2, - secondChildNode.text.length - 2 - ); - } - - private calculateHashOfFile(filePath: string): Promise { - return new Promise((resolve, reject) => { - const hash = crypto.createHash('md5'); - const stream = fs.createReadStream(filePath); - - stream.on('data', (data) => { - hash.update(data); - }); - - stream.on('end', () => { - const fileHash = hash.digest('hex'); - resolve(fileHash); - }); - - stream.on('error', (error) => { - reject(error); - }); - }); - } - - private findNodeByRanges(node: SyntaxNode, range: Parser.Range): SyntaxNode | undefined { - if (node.startIndex > range.startIndex && node.endIndex < range.endIndex) { - this.nodeByRanges = node; - return this.nodeByRanges; - } - - node.children.forEach((child) => { - if (this.nodeByRanges !== undefined) { - return this.nodeByRanges; - } - this.findNodeByRanges(child, range); - }); - - return this.nodeByRanges; - } - - private getEditableParentForStatements(node: SyntaxNode): SyntaxNode | undefined { - if (node.parent === null) { - this.editableParent = undefined; - return this.editableParent; - } - - if (node.parent.type === SyntaxNodeType.CaseStatement || - node.parent.type === SyntaxNodeType.IfStatement || - node.parent.type === SyntaxNodeType.TemptableDefinition || - node.parent.type === SyntaxNodeType.FindStatement || - node.parent.type === SyntaxNodeType.AssignStatement || - node.parent.type === SyntaxNodeType.ForStatement) { - this.editableParent = node.parent; - return this.editableParent; - } - - this.getEditableParentForStatements(node.parent); - - return this.editableParent; - } - - private getEditableParentForDoBlock(node: SyntaxNode): SyntaxNode | undefined { - if (node.parent === null) { - this.editableParent = undefined; - return this.editableParent; - } - - if (node.parent.type === SyntaxNodeType.DoBlock) { - this.editableParent = node.parent!; - return this.editableParent; - } - - this.getEditableParentForDoBlock(node.parent); - - return this.editableParent; - } -} diff --git a/src/formatters/AblIfFormatter.ts b/src/formatters/AblIfFormatter.ts deleted file mode 100644 index 6683fc0..0000000 --- a/src/formatters/AblIfFormatter.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { SyntaxNode } from "web-tree-sitter"; -import { SourceChanges } from "../model/SourceChanges"; -import { AAblFormatter } from "./AAblFormatter"; -import { IAblFormatter } from "./IAblFormatter"; -import { Range, TextEdit } from "vscode"; -import { FormatterSettings } from "../model/FormatterSettings"; -import { SyntaxNodeType } from "../model/SyntaxNodeType"; -import { AblFormatterCommon } from "./AblFormatterCommon"; - -export class AblIfFormatter extends AAblFormatter implements IAblFormatter { - private startColumn = 0; - private nextLineOfComparison = 3; - private ifBlockValueColumn = 0; - private ifBodyValue = ""; - - private textEdit: TextEdit[] = []; - - private ablFormatterCommon: AblFormatterCommon = new AblFormatterCommon(); - - protected getSelf(): IAblFormatter { - return this; - } - - parseNode(node: SyntaxNode): void { - if (!FormatterSettings.ifFormatting()) { - return; - } - - if (node.type !== SyntaxNodeType.IfStatement) { - return; - } - - if (this.ablFormatterRunner === undefined) { - return; - } - - this.collectIfStructure(node); - - const newBlock = this.getPrettyBlock(); - - if ( - this.ablFormatterRunner - .getDocument() - .getText( - new Range( - node.startPosition.row, - node.startPosition.column, - node.endPosition.row, - node.endPosition.column - ) - ) === newBlock - ) { - return; - } - this.textEdit?.push( - new TextEdit( - new Range( - node.startPosition.row, - node.startPosition.column, - node.endPosition.row, - node.endPosition.column - ), - newBlock - ) - ); - } - - getSourceChanges(): SourceChanges { - return { - textEdits: this.textEdit, - }; - } - - clearSourceChanges(): void { - this.textEdit.length = 0; - } - - private collectIfStructure(node: SyntaxNode) { - this.startColumn = node.startPosition.column; - this.ifBlockValueColumn = - this.startColumn + FormatterSettings.tabSize(); - this.ifBodyValue = this.getCaseBodyBranchBlock(node); - } - - private getCaseBodyBranchBlock(node: SyntaxNode): string { - let resultString = ""; - let doBlock = false; - - node.children.forEach((child) => { - if (child.type === SyntaxNodeType.DoBlock) { - doBlock = true; - } - }); - - node.children.forEach((child) => { - resultString = resultString.concat( - this.getIfExpressionString( - child, - "\r\n".concat(" ".repeat(this.ifBlockValueColumn)), - doBlock - ) - ); - }); - - return resultString.trim(); - } - - private getIfExpressionString( - node: SyntaxNode, - separator: string, - doBlock: boolean - ): string { - switch (node.type.trim()) { - case SyntaxNodeType.ThenKeyword: - if (doBlock) { - return node.text; - } else { - return ` ${node.text.trim()}${separator}`; - } - case SyntaxNodeType.ElseKeyword: - if (doBlock) { - return node.text; - } else { - return `${node.text.trim()}${separator}`; - } - case SyntaxNodeType.DoBlock: - return this.ablFormatterCommon.getDoBlock( - node, - this.ifBlockValueColumn, - this.startColumn - ); - case SyntaxNodeType.AblStatement: - return node.text + "\r\n".concat(" ".repeat(this.startColumn)); - case SyntaxNodeType.ElseStatement: - let resultElseString = ""; - let doElseBlock = false; - - node.children.forEach((child) => { - if (child.type === SyntaxNodeType.DoBlock) { - doElseBlock = true; - } - }); - - node.children.forEach((child) => { - resultElseString = resultElseString.concat( - this.getIfExpressionString( - child, - "\r\n".concat(" ".repeat(this.ifBlockValueColumn)), - doElseBlock - ) - ); - }); - - return resultElseString; - case SyntaxNodeType.BooleanLiteral: - return node.text.trim(); - case SyntaxNodeType.AvailableExpression: - return node.text.trim(); - case SyntaxNodeType.ParenthesizedExpression: - return node.text.trim(); - case SyntaxNodeType.LogicalExpression: - let resultLogicalExString = ""; - - node.children.forEach((child) => { - resultLogicalExString = resultLogicalExString.concat( - this.getIfExpressionString( - child, - "\r\n".concat( - " ".repeat( - this.startColumn + this.nextLineOfComparison - ) - ), - false - ) - ); - }); - - return resultLogicalExString; - case SyntaxNodeType.AndKeyword: - case SyntaxNodeType.OrKeyword: - return " " + node.text.trim() + separator; - case SyntaxNodeType.ComparisonExpression: - return node.text.trim(); - case SyntaxNodeType.IfKeyword: - return node.text.trim() + " "; - default: - return node.text.trim(); - } - } - - private getPrettyBlock(): string { - return "".concat(this.ifBodyValue.trim()); - } -} diff --git a/src/formatters/AblTemptableFormatter.ts b/src/formatters/AblTemptableFormatter.ts deleted file mode 100644 index 9f4724b..0000000 --- a/src/formatters/AblTemptableFormatter.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { SyntaxNode } from "web-tree-sitter"; -import { SourceChanges } from "../model/SourceChanges"; -import { AAblFormatter } from "./AAblFormatter"; -import { IAblFormatter } from "./IAblFormatter"; -import { Range, TextEdit } from "vscode"; -import { FormatterSettings } from "../model/FormatterSettings"; -import { SyntaxNodeType } from "../model/SyntaxNodeType"; - -export class AblTemptableFormatter - extends AAblFormatter - implements IAblFormatter -{ - private startColumn = 0; - private temptableValueColumn = 0; - private temptableBodyValue = ""; - - private textEdit: TextEdit[] = []; - - protected getSelf(): IAblFormatter { - return this; - } - - parseNode(node: SyntaxNode): void { - if (!FormatterSettings.temptableFormatting()) { - return; - } - - if (node.type !== SyntaxNodeType.TemptableDefinition) { - return; - } - - if (this.ablFormatterRunner === undefined) { - return; - } - - this.collectTemptableStructure(node); - - const newBlock = this.getPrettyBlock(); - - if ( - this.ablFormatterRunner - .getDocument() - .getText( - new Range( - node.startPosition.row, - node.startPosition.column, - node.endPosition.row, - node.endPosition.column - ) - ) === newBlock - ) { - return; - } - this.textEdit?.push( - new TextEdit( - new Range( - node.startPosition.row, - node.startPosition.column, - node.endPosition.row, - node.endPosition.column - ), - newBlock - ) - ); - } - - getSourceChanges(): SourceChanges { - return { - textEdits: this.textEdit, - }; - } - - clearSourceChanges(): void { - this.textEdit.length = 0; - } - - private collectTemptableStructure(node: SyntaxNode): void { - this.startColumn = node.startPosition.column; - this.temptableValueColumn = - this.startColumn + FormatterSettings.tabSize(); - this.temptableBodyValue = this.getTemptableBlock(node); - } - - private getTemptableBlock(node: SyntaxNode): string { - let resultString = ""; - - node.children.forEach((child) => { - resultString = resultString.concat( - this.getTemptableExpressionString( - child, - "\r\n".concat(" ".repeat(this.temptableValueColumn)) - ) - ); - }); - - return resultString.trim(); - } - - private getTemptableExpressionString( - node: SyntaxNode, - separator: string - ): string { - switch (node.type.trim()) { - case SyntaxNodeType.FieldDefinition: - case SyntaxNodeType.IndexDefinition: - let resultTemptableString = ""; - - node.children.forEach((child) => { - resultTemptableString = resultTemptableString.concat( - this.getTemptableExpressionString( - child, - "\r\n".concat(" ".repeat(this.temptableValueColumn)) - ) - ); - }); - - return separator + resultTemptableString; - case SyntaxNodeType.LikeKeyword: - if ( - node.parent!.type.trim() === - SyntaxNodeType.FieldDefinition || - node.parent!.type.trim() === SyntaxNodeType.IndexDefinition - ) { - return " " + node.text.trim(); - } else { - return separator + node.text.trim(); - } - case SyntaxNodeType.FieldKeyword: - case SyntaxNodeType.IndexKeyword: - return node.text.trim(); - default: - return " " + node.text.trim(); - } - } - - private getPrettyBlock(): string { - const block = "".concat(this.temptableBodyValue.trim()).concat("."); - - return block; - } -} diff --git a/src/formatters/AblTokenFormatter.ts b/src/formatters/AblTokenFormatter.ts deleted file mode 100644 index bb632d5..0000000 --- a/src/formatters/AblTokenFormatter.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { TextEdit } from "vscode"; -import { IAblFormatter } from "./IAblFormatter"; -import { SourceChanges } from "../model/SourceChanges"; -import Parser from "web-tree-sitter"; -import { MyRange } from "../model/MyRange"; -import { AAblFormatter } from "./AAblFormatter"; -import { FormatterSettings } from "../model/FormatterSettings"; - -export class AblTokenFormatter extends AAblFormatter implements IAblFormatter { - private targetIsLong = true; - private useUppercase = FormatterSettings.casing(); - private longDefine = "DEFINE"; - private shortDefine = "DEF"; - - public parseNode(node: Parser.SyntaxNode): void { - if ( - node.type === "DEFINE" || - node.type === "define" || - node.type === "DEFI" || - node.type === "defi" || - node.type === "DEF" || - node.type === "def" - ) { - const range = new MyRange(node); - - this.ranges.push(range); - } - } - - getSourceChanges(): SourceChanges { - let textEdits = new Array(); - - this.ranges.forEach((range) => { - const textEdit = new TextEdit( - range, - this.targetIsLong ? this.longDefine : this.shortDefine - ); - - textEdit.newText = this.useUppercase - ? textEdit.newText - : textEdit.newText.toLowerCase(); - - textEdits.push(textEdit); - }); - - return { - textEdits: textEdits, - }; - } - - clearSourceChanges(): void { - } - - protected getSelf(): IAblFormatter { - return this; - } -} diff --git a/src/formatters/IAblFormatter.ts b/src/formatters/IAblFormatter.ts deleted file mode 100644 index 5209bde..0000000 --- a/src/formatters/IAblFormatter.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { SourceChanges } from "../model/SourceChanges"; -import Parser from "web-tree-sitter"; - -export interface IAblFormatter { - parseNode(node: Parser.SyntaxNode): void; - - getSourceChanges(): SourceChanges; - - clearSourceChanges(): void; -} diff --git a/src/formatters/IAblFormatterRunner.ts b/src/formatters/IAblFormatterRunner.ts deleted file mode 100644 index e3f73b3..0000000 --- a/src/formatters/IAblFormatterRunner.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { TextDocument, } from "vscode"; -import { SourceChanges } from "../model/SourceChanges"; -import { ParseResult } from "../model/ParseResult"; -import { IParserHelper } from "../parser/IParserHelper"; - -export interface IAblFormatterRunner { - getSourceChanges(): SourceChanges; - getDocument(): TextDocument; - - start(): IAblFormatterRunner; - setDocument(document: TextDocument): IAblFormatterRunner; - setParserResult(parserResult: ParseResult): IAblFormatterRunner; - setParserHelper(parserHelper: IParserHelper): IAblFormatterRunner; -} diff --git a/src/formatters/TreeLogger.ts b/src/formatters/TreeLogger.ts deleted file mode 100644 index 6a68c21..0000000 --- a/src/formatters/TreeLogger.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { SyntaxNode } from "web-tree-sitter"; -import { SourceChanges } from "../model/SourceChanges"; -import { IAblFormatter } from "./IAblFormatter"; -import { AAblFormatter } from "./AAblFormatter"; -import { MyRange } from "../model/MyRange"; - -export class TreeLogger extends AAblFormatter implements IAblFormatter { - private errorCounter: number = 0; - - parseNode(node: SyntaxNode): void { - if (node.type === "ERROR") { - this.errorCounter++; - } - console.log( - node.id, - " \t ", - node.parent?.id, - " \t ", - node.type, - " \t ", - node.startIndex, - " \t ", - node.endIndex, - " \t ", - node.text, - " \t " - // " \t ", - // node.text - ); - } - getSourceChanges(): SourceChanges { - console.log("Number of parser errrors: " + this.errorCounter); - return { - textEdits: [], - }; - } - - clearSourceChanges(): void {} - - protected getSelf(): IAblFormatter { - return this; - } -} diff --git a/src/model/FormatterSettings.ts b/src/model/FormatterSettings.ts deleted file mode 100644 index f909360..0000000 --- a/src/model/FormatterSettings.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { ConfigurationManager } from "../utils/ConfigurationManager"; - -export class FormatterSettings { - public static tabSize() { - return ConfigurationManager.get("tabSize"); - } - - public static casing() { - return ConfigurationManager.getCasing(); - } - - // assign settings - public static assignFormatting() { - return ConfigurationManager.get("assignFormatting") ? true : false; - } - - public static newLineAfterAssign() { - return ConfigurationManager.get("assignFormattingAssignLocation") === "New" ? true : false; - } - - public static alignRightExpression() { - return ConfigurationManager.get("assignFormattingAlignRightExpression") === "Yes" ? true : false; - } - - public static endDotLocationNew() { - return ConfigurationManager.get("assignFormattingEndDotLocation") === "New" || - ConfigurationManager.get("assignFormattingEndDotLocation") === "New aligned" ? true : false; - } - - public static endDotAlignment() { - return ConfigurationManager.get("assignFormattingEndDotLocation") === "New aligned" ? true : false; - } - - //define settings - public static defineFormatting() { - return ConfigurationManager.get("defineFormatting") ? true : false; - } - - //find settings - public static findFormatting() { - return ConfigurationManager.get("findFormatting") ? true : false; - } - - //for settings - public static forFormatting() { - return ConfigurationManager.get("forFormatting") ? true : false; - } - - //case settings - public static caseFormatting() { - return ConfigurationManager.get("caseFormatting") ? true : false; - } - - //block settings - public static blockFormatting() { - return ConfigurationManager.get("blockFormatting") ? true : false; - } - - //if settings - public static ifFormatting() { - return ConfigurationManager.get("ifFormatting") ? true : false; - } - - //temp-table settings - public static temptableFormatting() { - return ConfigurationManager.get("temptableFormatting") ? true : false; - } - - //logging settings - public static treeLogging() { - return ConfigurationManager.get("treeLogging") ? true : false; - } -} diff --git a/src/model/MyRange.ts b/src/model/MyRange.ts deleted file mode 100644 index 1e79070..0000000 --- a/src/model/MyRange.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Range } from "vscode"; -import Parser from "web-tree-sitter"; - -export class MyRange extends Range { - public constructor(node: Parser.SyntaxNode) { - super( - node.startPosition.row, - node.startPosition.column, - node.endPosition.row, - node.endPosition.column - ); - } -} diff --git a/src/model/SourceChanges.ts b/src/model/SourceChanges.ts deleted file mode 100644 index ada9162..0000000 --- a/src/model/SourceChanges.ts +++ /dev/null @@ -1,5 +0,0 @@ -import * as vscode from "vscode"; - -export interface SourceChanges { - textEdits: vscode.TextEdit[]; -} diff --git a/src/providers/AblFormatterFactory.ts b/src/providers/AblFormatterFactory.ts deleted file mode 100644 index 3635050..0000000 --- a/src/providers/AblFormatterFactory.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { AblAssignFormatter } from "../formatters/AblAssignFormatter"; -import { AblFindFormatter } from "../formatters/AblFindFormatter"; -import { AblForFormatter } from "../formatters/AblForFormatter"; -import { AblCaseFormatter } from "../formatters/AblCaseFormatter"; -import { AblFormatterRunner } from "../formatters/AblFormatterRunner"; -import { AblTokenFormatter } from "../formatters/AblTokenFormatter"; -import { IAblFormatter } from "../formatters/IAblFormatter"; -import { IAblFormatterRunner } from "../formatters/IAblFormatterRunner"; -import { TreeLogger } from "../formatters/TreeLogger"; -import { ConfigurationManager } from "../utils/ConfigurationManager"; -import { AblBlockFormatter } from "../formatters/AblBlockFormatter"; -import { AblIfFormatter } from "../formatters/AblIfFormatter"; -import { AblTemptableFormatter } from "../formatters/AblTemptableFormatter"; - -export class AblFormatterFactory { - private runner: IAblFormatterRunner | undefined; - - private readonly baseFormatterNames = [ - "blockFormatting", - ]; - - private readonly formatterNames = [ - "forFormatting", - "findFormatting", - "ifFormatting", - "caseFormatting", - "assignFormatting", - "defineFormatting", - "treeLogging", - "temptableFormatting", - ]; - - public getBaseFormatters(): IAblFormatter[] { - console.log("Getting base formatters ... "); - const formatters = this.baseFormatterNames.map((formatterName) => { - if (this.enabled(formatterName)) { - const formatter = this.getFormatter(formatterName); - if (formatter !== undefined) { - console.log("Base formatter activated: ", formatterName); - return formatter; - } else { - console.log("Base formatter disabled: ", formatterName); - } - } - }); - - return formatters.filter( - (formatter): formatter is IAblFormatter => formatter !== undefined - ); - } - - public getFormatters(): IAblFormatter[] { - console.log("Getting formatters ... "); - const formatters = this.formatterNames.map((formatterName) => { - if (this.enabled(formatterName)) { - const formatter = this.getFormatter(formatterName); - if (formatter !== undefined) { - console.log("Formatter activated: ", formatterName); - return formatter; - } else { - console.log("Formatter disabled: ", formatterName); - } - } - }); - - return formatters.filter( - (formatter): formatter is IAblFormatter => formatter !== undefined - ); - } - - private enabled(formatterName: string): boolean { - if (ConfigurationManager.get(formatterName)!) { - return true; - } - - if (formatterName.startsWith("DEBUG-")) { - return true; - } - return false; - } - - private getFormatter(formatterName: string): IAblFormatter | undefined { - if (this.runner === undefined) { - return undefined; - } - - switch (formatterName) { - case "assignFormatting": - return new AblAssignFormatter(this.runner); - case "treeLogging": - return new TreeLogger(this.runner); - case "defineFormatting": - return new AblTokenFormatter(this.runner); - case "findFormatting": - return new AblFindFormatter(this.runner); - case "forFormatting": - return new AblForFormatter(this.runner); - case "caseFormatting": - return new AblCaseFormatter(this.runner); - case "blockFormatting": - return new AblBlockFormatter(this.runner); - case "ifFormatting": - return new AblIfFormatter(this.runner); - case "temptableFormatting": - return new AblTemptableFormatter(this.runner); - } - - return undefined; - } - - public getFormatterRunner(): IAblFormatterRunner { - this.runner = new AblFormatterRunner(this); - return this.runner; - } -} diff --git a/src/providers/AblFormatterProvider.ts b/src/providers/AblFormatterProvider.ts index 81557f6..ff891f3 100644 --- a/src/providers/AblFormatterProvider.ts +++ b/src/providers/AblFormatterProvider.ts @@ -2,7 +2,7 @@ import * as vscode from "vscode"; import { IParserHelper } from "../parser/IParserHelper"; import { FileIdentifier } from "../model/FileIdentifier"; import { FormattingEngine } from "../v2/formatterFramework/FormattingEngine"; -import { ConfigurationManager2 } from "../utils/ConfigurationManager2"; +import { ConfigurationManager2 } from "../utils/ConfigurationManager"; import { EOL } from "../v2/model/EOL"; import { DebugManager } from "./DebugManager"; diff --git a/src/providers/DebugManager.ts b/src/providers/DebugManager.ts index 06f527b..ba43de7 100644 --- a/src/providers/DebugManager.ts +++ b/src/providers/DebugManager.ts @@ -9,7 +9,7 @@ import { } from "vscode"; import { SyntaxNode, Tree } from "web-tree-sitter"; import { SyntaxNodeType } from "../model/SyntaxNodeType"; -import { ConfigurationManager2 } from "../utils/ConfigurationManager2"; +import { ConfigurationManager2 } from "../utils/ConfigurationManager"; import { IDebugManager } from "./IDebugManager"; export class DebugManager implements IDebugManager { diff --git a/src/test/suite/extension.test.ts b/src/test/suite/extension.test.ts index 761bbe3..752e94f 100644 --- a/src/test/suite/extension.test.ts +++ b/src/test/suite/extension.test.ts @@ -7,7 +7,7 @@ import * as vscode from "vscode"; import { AblParserHelper } from "../../parser/AblParserHelper"; import { FileIdentifier } from "../../model/FileIdentifier"; import { FormattingEngine } from "../../v2/formatterFramework/FormattingEngine"; -import { ConfigurationManager2 } from "../../utils/ConfigurationManager2"; +import { ConfigurationManager2 } from "../../utils/ConfigurationManager"; import Parser from "web-tree-sitter"; import { enableFormatterDecorators } from "../../v2/formatterFramework/enableFormatterDecorators"; import path from "path"; diff --git a/src/utils/ConfigurationManager.ts b/src/utils/ConfigurationManager.ts index 48e9681..0d0733b 100644 --- a/src/utils/ConfigurationManager.ts +++ b/src/utils/ConfigurationManager.ts @@ -1,50 +1,68 @@ -import { WorkspaceConfiguration, window, workspace, commands } from "vscode"; - -export class ConfigurationManager { - private static reloadConfig = true; - private static reloadExternalConfig = true; - private static configuration: WorkspaceConfiguration; - private static externalConfiguration: WorkspaceConfiguration; - private static overridingSettings: any | undefined; - public static readonly _ = workspace.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration("AblFormatter")) { - ConfigurationManager.reloadConfig = true; - window.showInformationMessage("ABL Formatter was changed!"); - } +import { commands, window, workspace, WorkspaceConfiguration } from "vscode"; +import { IConfigurationManager } from "./IConfigurationManager"; - if (e.affectsConfiguration("abl.completion")) { - ConfigurationManager.reloadExternalConfig = true; - window.showInformationMessage("ABL cassing was changed!"); - } - }); +export class ConfigurationManager2 implements IConfigurationManager { + private static instance: ConfigurationManager2; + private reloadConfig = true; + private reloadExternalConfig = true; + private configuration: WorkspaceConfiguration | undefined = undefined; + private externalConfiguration: WorkspaceConfiguration | undefined = + undefined; + private overridingSettings: any | undefined; + private tabSize: number | undefined; + + private constructor() { + workspace.onDidChangeConfiguration((e) => { + if (e.affectsConfiguration("AblFormatter")) { + this.reloadConfig = true; + window.showInformationMessage("ABL Formatter was changed2!"); + } - public static get(name: string): any { - if (ConfigurationManager.reloadConfig) { - ConfigurationManager.reloadConfig = false; - ConfigurationManager.configuration = - workspace.getConfiguration("AblFormatter"); + if (e.affectsConfiguration("abl.completion")) { + this.reloadExternalConfig = true; + window.showInformationMessage("ABL cassing was changed2!"); + } + }); + } + + public static getInstance(): ConfigurationManager2 { + if (!ConfigurationManager2.instance) { + ConfigurationManager2.instance = new ConfigurationManager2(); } + return ConfigurationManager2.instance; + } + public get(name: string) { + if (this.reloadConfig) { + this.reloadConfig = false; + this.configuration = workspace.getConfiguration("AblFormatter"); + } return this.getConfig(name); } - public static getCasing(): any { - if (ConfigurationManager.reloadExternalConfig) { - ConfigurationManager.reloadExternalConfig = false; - ConfigurationManager.externalConfiguration = + public setTabSize(tabSize: number): void { + this.tabSize = tabSize; + } + + public getTabSize(): number { + return this.tabSize || 4; // Default to 4 if not set + } + + public getCasing() { + if (this.reloadExternalConfig) { + this.reloadExternalConfig = false; + this.externalConfiguration = workspace.getConfiguration("abl.completion"); } - return this.getCassingConfig(); } - public static setOverridingSettings(settings: any) { + public setOverridingSettings(settings: any): void { this.overridingSettings = settings; } - private static getCassingConfig(): any { - const config = - ConfigurationManager.externalConfiguration.get("upperCase"); + private getCassingConfig(): any { + const config = this.externalConfiguration?.get("upperCase"); if (config === undefined || (config !== true && config !== false)) { window @@ -77,8 +95,9 @@ export class ConfigurationManager { return config; } - private static getConfig(name: string): any { - const config = ConfigurationManager.configuration.get(name); + private getConfig(name: string): any { + const config = this.configuration?.get(name); + if (this.overridingSettings !== undefined) { const overridingConfig = this.overridingSettings["AblFormatter." + name]; diff --git a/src/utils/ConfigurationManager2.ts b/src/utils/ConfigurationManager2.ts deleted file mode 100644 index 0d0733b..0000000 --- a/src/utils/ConfigurationManager2.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { commands, window, workspace, WorkspaceConfiguration } from "vscode"; -import { IConfigurationManager } from "./IConfigurationManager"; - -export class ConfigurationManager2 implements IConfigurationManager { - private static instance: ConfigurationManager2; - private reloadConfig = true; - private reloadExternalConfig = true; - private configuration: WorkspaceConfiguration | undefined = undefined; - private externalConfiguration: WorkspaceConfiguration | undefined = - undefined; - private overridingSettings: any | undefined; - private tabSize: number | undefined; - - private constructor() { - workspace.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration("AblFormatter")) { - this.reloadConfig = true; - window.showInformationMessage("ABL Formatter was changed2!"); - } - - if (e.affectsConfiguration("abl.completion")) { - this.reloadExternalConfig = true; - window.showInformationMessage("ABL cassing was changed2!"); - } - }); - } - - public static getInstance(): ConfigurationManager2 { - if (!ConfigurationManager2.instance) { - ConfigurationManager2.instance = new ConfigurationManager2(); - } - return ConfigurationManager2.instance; - } - - public get(name: string) { - if (this.reloadConfig) { - this.reloadConfig = false; - this.configuration = workspace.getConfiguration("AblFormatter"); - } - return this.getConfig(name); - } - - public setTabSize(tabSize: number): void { - this.tabSize = tabSize; - } - - public getTabSize(): number { - return this.tabSize || 4; // Default to 4 if not set - } - - public getCasing() { - if (this.reloadExternalConfig) { - this.reloadExternalConfig = false; - this.externalConfiguration = - workspace.getConfiguration("abl.completion"); - } - return this.getCassingConfig(); - } - - public setOverridingSettings(settings: any): void { - this.overridingSettings = settings; - } - - private getCassingConfig(): any { - const config = this.externalConfiguration?.get("upperCase"); - - if (config === undefined || (config !== true && config !== false)) { - window - .showErrorMessage( - `abl.completion.upperCase setting not set or set incorrectly. Update settings file. Current value - ${config}. Expected values - true or false `, - "Settings" - ) - .then((selection) => { - switch (selection) { - case "Settings": - commands.executeCommand( - "workbench.action.openWorkspaceSettingsFile" - ); - return; - default: - return; - } - }); - } - - if (this.overridingSettings !== undefined) { - const overridingConfig = - this.overridingSettings["abl.completion.upperCase"]; - - if (overridingConfig !== undefined) { - window.showInformationMessage("Found overriding settings!"); - return overridingConfig; - } - } - return config; - } - - private getConfig(name: string): any { - const config = this.configuration?.get(name); - - if (this.overridingSettings !== undefined) { - const overridingConfig = - this.overridingSettings["AblFormatter." + name]; - - if (overridingConfig !== undefined) { - window.showInformationMessage("Found overriding settings!"); - return overridingConfig; - } - } - return config; - } -} From 83a3d3b02e47d421bac0d34ccbeae6fd5e6c8fdd Mon Sep 17 00:00:00 2001 From: gmickus Date: Wed, 4 Sep 2024 15:56:47 +0300 Subject: [PATCH 2/2] Delete FormatterCache.ts and MemoryFile.ts --- src/extension.ts | 7 +-- src/model/FormatterCache.ts | 79 -------------------------------- src/model/MemoryFile.ts | 89 ------------------------------------- 3 files changed, 1 insertion(+), 174 deletions(-) delete mode 100644 src/model/FormatterCache.ts delete mode 100644 src/model/MemoryFile.ts diff --git a/src/extension.ts b/src/extension.ts index f14c89f..0627ff4 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -5,8 +5,6 @@ import Parser from "web-tree-sitter"; import { AblFormatterProvider } from "./providers/AblFormatterProvider"; import { Constants } from "./model/Constants"; import { AblParserHelper } from "./parser/AblParserHelper"; -import { register_memoryFileProvider } from "./model/MemoryFile"; -import { FormatterCache } from "./model/FormatterCache"; import { AblDebugHoverProvider } from "./providers/AblDebugHoverProvider"; import { ConfigurationManager2 } from "./utils/ConfigurationManager"; import { enableFormatterDecorators } from "./v2/formatterFramework/enableFormatterDecorators"; @@ -15,7 +13,6 @@ import { DebugManager } from "./providers/DebugManager"; // This method is called when your extension is activated // Your extension is activated the very first time the command is executed export async function activate(context: vscode.ExtensionContext) { - register_memoryFileProvider(context); const debugManager = DebugManager.getInstance(context); await Parser.init().then(() => {}); @@ -60,6 +57,4 @@ export async function activate(context: vscode.ExtensionContext) { } // This method is called when your extension is deactivated -export function deactivate() { - FormatterCache.clearCache(); -} +export function deactivate() {} diff --git a/src/model/FormatterCache.ts b/src/model/FormatterCache.ts deleted file mode 100644 index 86b6dea..0000000 --- a/src/model/FormatterCache.ts +++ /dev/null @@ -1,79 +0,0 @@ -import * as fs from "fs"; -import * as path from "path"; -import { extensions } from "vscode"; -import Parser, { Tree } from "web-tree-sitter"; - -export class FormatterCache { - private static cache = new Map(); - - private static getCacheFilePath(): string { - const basePath = extensions.getExtension( - "BalticAmadeus.AblFormatter" - )?.extensionPath; - - if (basePath === undefined) { - console.log("ERRRRRRRRRRRRRRRRRor. Cache file cannot be created!"); - return ""; - } - - return path.join(basePath, "cache.json"); - } - - public static getHash(filePath: string): string | undefined { - const cache = this.loadCache(); - return cache[filePath]; - } - - public static updateHash(filePath: string, hash: string): void { - const cache = this.loadCache(); - cache[filePath] = hash; - this.saveCache(cache); - } - - private static loadCache(): { [filePath: string]: string } { - try { - const data = fs.readFileSync(this.getCacheFilePath(), "utf-8"); - return JSON.parse(data); - } catch (error) { - // If file doesn't exist or cannot be parsed, return an empty object - return {}; - } - } - - private static saveCache(cache: { [filePath: string]: string }): void { - try { - fs.writeFileSync( - this.getCacheFilePath(), - JSON.stringify(cache, null, 2), - "utf-8" - ); - } catch (error) { - console.log( - "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", - error - ); - } - } - - private static clearCacheFile() { - try { - fs.unlinkSync(this.getCacheFilePath()); - } catch (error) { - // Handle error if file deletion fails - console.error("Error clearing cache file:", error); - } - } - - public static clearCache() { - this.cache.clear(); - this.clearCacheFile(); - } - - public static getTree(key: string): Parser.Tree { - return this.cache.get(key); - } - - public static setTree(key: string, tree: Tree) { - this.cache.set(key, tree); - } -} diff --git a/src/model/MemoryFile.ts b/src/model/MemoryFile.ts deleted file mode 100644 index 0704849..0000000 --- a/src/model/MemoryFile.ts +++ /dev/null @@ -1,89 +0,0 @@ -import * as vscode from 'vscode'; - -const _SCHEME = "inmemoryfile"; - -/** - * Registration function for In-Memory files. - **/ -export function register_memoryFileProvider ({ subscriptions }: vscode.ExtensionContext) -{ - const myProvider = new (class implements vscode.TextDocumentContentProvider - { - provideTextDocumentContent(uri: vscode.Uri): string - { - let memDoc = MemoryFile.getDocument (uri); - if (memDoc === null) - {return "";} - return memDoc.read (); - } - })(); - subscriptions.push(vscode.workspace.registerTextDocumentContentProvider( - _SCHEME, myProvider)); -} - -/** - * Management class for in-memory files. - **/ -class MemoryFileManagement -{ - private static _documents: {[key: string]: MemoryFile} = {}; - private static _lastDocId: number = 0; - - public static getDocument(uri: vscode.Uri) : MemoryFile | null - { - return MemoryFileManagement._documents[uri.path]; - } - - private static _getNextDocId(): string{ - MemoryFileManagement._lastDocId++; - return "_" + MemoryFileManagement._lastDocId + "_"; - } - - public static createDocument(extension = "") - { - let path = MemoryFileManagement._getNextDocId (); - - if (extension !== "") - {path += "." + extension;} - - let self = new MemoryFile(path); - - MemoryFileManagement._documents[path] = self; - - return self; - } -} - -/** - * A file in memory - **/ -export class MemoryFile -{ - public static getDocument(uri: vscode.Uri) : MemoryFile | null { - return MemoryFileManagement.getDocument (uri); - } - - public static createDocument(extension = "") { - return MemoryFileManagement.createDocument (extension); - } - - public content: string = ""; - public uri: vscode.Uri; - - constructor (path: string) - { - this.uri = vscode.Uri.from ({scheme: _SCHEME, path: path}); - } - - public write(strContent: string){ - this.content += strContent; - } - - public read(): string { - return this.content; - } - - public getUri(): vscode.Uri { - return this.uri; - } -} \ No newline at end of file