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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ tptplus/server/out/
.env
RemoteSot.py
*.g4
!tptplus/server/parser/vendor/tptp-antlr/original/TPTP.g4
!tptplus/server/parser/vendor/tptp-antlr/optimized/TPTP.g4
SyntaxBNF
.DS_Store

Expand Down
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,11 +167,15 @@ Added error handling for "Format TPTP File": display error message and jump to p

### 0.1.11

Added title-menu button for "TPTP: Pretty-Print TPTP File"; improved error handling for pretty-printer.
Added title-menu button for command "TPTP: Pretty-Print TPTP File"; improved error handling for pretty-printer.

### 0.1.12

Added title-menu button for "TPTP: Type-Check with LEO-III"; improved error handling for pretty-printer; retired legacy formatter.
Added command "TPTP: Type-Check with LEO-III" and a title-menu button for it; improved error handling for pretty-printer; retired legacy formatter.

### 0.1.13

Added command "TPTP: Parse with ANTLR" and a title-menu button for it. It currently uses an unoptimized version of ANTLR grammar and can be slow.

---

Expand Down
5 changes: 3 additions & 2 deletions tptplus/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,6 @@
- v0.1.8 Fixed issue where some greater-than-signs are not handled correctly by command "Format TPTP File".
- v0.1.9 Added local pretty-printer so that "Format TPTP File" works without Internet connection. The original remote pretty-printer is kept as a fallback.
- v0.1.10 Added error handling for "Format TPTP File": display error message and jump to position of syntax error.
- v0.1.11 Added title-menu button for "TPTP: Pretty-Print TPTP File"; improved error handling for pretty-printer.
- v0.1.12 Added title-menu button for "TPTP: Type-Check with LEO-III"; improved error handling for pretty-printer; retired legacy formatter.
- v0.1.11 Added title-menu button for command "TPTP: Pretty-Print TPTP File"; improved error handling for pretty-printer.
- v0.1.12 Added command "TPTP: Type-Check with LEO-III" and a title-menu button for it; improved error handling for pretty-printer; retired legacy formatter.
- v0.1.13 Added command "TPTP: Parse with ANTLR" and a title-menu button for it. It currently uses an unoptimized version of ANTLR grammar and can be slow.
8 changes: 6 additions & 2 deletions tptplus/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,15 @@ Added error handling for "Format TPTP File": display error message and jump to p

### 0.1.11

Added title-menu button for "TPTP: Pretty-Print TPTP File"; improved error handling for pretty-printer.
Added title-menu button for command "TPTP: Pretty-Print TPTP File"; improved error handling for pretty-printer.

### 0.1.12

Added title-menu button for "TPTP: Type-Check with LEO-III"; improved error handling for pretty-printer; retired legacy formatter.
Added command "TPTP: Type-Check with LEO-III" and a title-menu button for it; improved error handling for pretty-printer; retired legacy formatter.

### 0.1.13

Added command "TPTP: Parse with ANTLR" and a title-menu button for it. It currently uses an unoptimized version of ANTLR grammar and can be slow.

---

Expand Down
186 changes: 186 additions & 0 deletions tptplus/client/src/antlrParser/command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import * as path from 'path';
import * as vscode from 'vscode';
import type { LanguageClient } from 'vscode-languageclient/node';

import { revealFirstAntlrError, toVsCodeDiagnostic } from './diagnostics';
import type { ParseWithAntlrResult } from './types';

// Set to false to use the original metagrammar-converted grammar; rebuild afterward.
const USE_OPTIMIZED_ANTLR_GRAMMAR = false;

const ANTLR_PARSE_COMMAND = 'tptp.parseWithAntlr';
const ANTLR_PARSE_REQUEST = 'tptp/parseWithAntlr';
const ANTLR_PARSE_RUNNING_CONTEXT_KEY = 'tptp.antlrParseRunning';

/** Shows cancellable progress for startup and parsing, without imposing a deadline. */
async function requestAntlrParse(
client: LanguageClient,
clientReady: Promise<void>,
document: vscode.TextDocument
): Promise<ParseWithAntlrResult | undefined> {
return vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: 'Parsing with ANTLR',
cancellable: true
},
async (progress, token) => {
progress.report({ message: path.basename(document.fileName) });
let cancellation: vscode.Disposable | undefined;
const cancelled = new Promise<undefined>(resolve => {
cancellation = token.onCancellationRequested(() => resolve(undefined));
if (token.isCancellationRequested) {
resolve(undefined);
}
});
const request = async (): Promise<ParseWithAntlrResult | undefined> => {
await clientReady;
if (token.isCancellationRequested) {
return undefined;
}
return client.sendRequest<ParseWithAntlrResult>(
ANTLR_PARSE_REQUEST,
{
uri: document.uri.toString(),
useOptimizedGrammar: USE_OPTIMIZED_ANTLR_GRAMMAR
},
token
);
};

try {
// Close progress promptly even if cancellation happens during startup.
// The same token also forwards cancellation to the server's worker.
const result = await Promise.race([request(), cancelled]);
return token.isCancellationRequested ? undefined : result;
} catch (error: unknown) {
if (token.isCancellationRequested) {
return undefined;
}
throw error;
} finally {
cancellation?.dispose();
}
}
);
}

function writeTptpAntlrParseLog(
output: vscode.OutputChannel,
document: vscode.TextDocument,
result: ParseWithAntlrResult
): void {
output.appendLine(`[${new Date().toISOString()}] ${document.uri.fsPath}`);
output.appendLine(`Grammar: ${USE_OPTIMIZED_ANTLR_GRAMMAR ? 'optimized' : 'original'}`);
output.appendLine(`Elapsed: ${result.summary.elapsedMs}ms`);
output.appendLine(`Syntax errors: ${result.summary.syntaxErrorCount}`);

if (result.diagnostics.length === 0) {
output.appendLine('No ANTLR diagnostics.');
} else {
result.diagnostics.forEach(diagnostic => {
output.appendLine(
`${diagnostic.range.start.line + 1}:${diagnostic.range.start.character + 1} ${diagnostic.message}`
);
});
}

output.appendLine('');
}

function createAntlrParserCommandHandler(
client: LanguageClient,
clientReady: Promise<void>,
diagnostics: vscode.DiagnosticCollection,
output: vscode.OutputChannel
): () => Promise<void> {
let parseRunning = false;

return async (): Promise<void> => {
if (parseRunning) {
vscode.window.showInformationMessage('ANTLR is already parsing a TPTP file.');
return;
}

const editor = vscode.window.activeTextEditor;
if (!editor || editor.document.languageId !== 'tptp') {
vscode.window.showErrorMessage('No TPTP file is currently open.');
return;
}

if (editor.document.uri.scheme !== 'file') {
vscode.window.showErrorMessage(
'The TPTP ANTLR parser currently supports file-backed TPTP documents only.'
);
return;
}

parseRunning = true;
try {
await vscode.commands.executeCommand('setContext', ANTLR_PARSE_RUNNING_CONTEXT_KEY, true);

const document = editor.document;
const parsedDocumentVersion = document.version;
diagnostics.delete(document.uri);
const result = await requestAntlrParse(client, clientReady, document);
if (result === undefined) {
vscode.window.showInformationMessage('ANTLR parse cancelled.');
return;
}
if (document.isClosed || document.version !== parsedDocumentVersion) {
vscode.window.showWarningMessage(
'TPTP file changed or was closed while parsing. Please run the parser again.'
);
return;
}

const parseDiagnostics = result.diagnostics.map(toVsCodeDiagnostic);
diagnostics.set(document.uri, parseDiagnostics);
writeTptpAntlrParseLog(output, document, result);

if (result.ok) {
vscode.window.showInformationMessage(
`ANTLR parse succeeded in ${result.summary.elapsedMs}ms.`
);
} else {
vscode.window.showWarningMessage(
`ANTLR parse found ${result.summary.syntaxErrorCount} error(s).`
);
await revealFirstAntlrError(document, parseDiagnostics);
}
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
output.appendLine(`[${new Date().toISOString()}] TPTP ANTLR parser request failed`);
output.appendLine(message);
output.show(true);
vscode.window.showErrorMessage(`TPTP ANTLR parser request failed: ${message}`);
} finally {
parseRunning = false;
await vscode.commands.executeCommand('setContext', ANTLR_PARSE_RUNNING_CONTEXT_KEY, false);
}
};
}

/** Registers the ANTLR parser command and its diagnostic lifecycle. */
export function registerAntlrParserCommand(
client: LanguageClient,
clientReady: Promise<void>
): vscode.Disposable {
const diagnostics = vscode.languages.createDiagnosticCollection('tptpAntlr');
const output = vscode.window.createOutputChannel('TPTP ANTLR Parser');
const commandHandler = createAntlrParserCommandHandler(
client,
clientReady,
diagnostics,
output
);

return vscode.Disposable.from(
diagnostics,
output,
vscode.commands.registerCommand(ANTLR_PARSE_COMMAND, commandHandler),
vscode.workspace.onDidChangeTextDocument(event => {
diagnostics.delete(event.document.uri);
})
);
}
54 changes: 54 additions & 0 deletions tptplus/client/src/antlrParser/diagnostics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import * as vscode from 'vscode';

import type { LspDiagnostic } from './types';

function toVsCodeSeverity(severity: number | undefined): vscode.DiagnosticSeverity {
switch (severity) {
case 2:
return vscode.DiagnosticSeverity.Warning;
case 3:
return vscode.DiagnosticSeverity.Information;
case 4:
return vscode.DiagnosticSeverity.Hint;
case 1:
default:
return vscode.DiagnosticSeverity.Error;
}
}

/** Converts a language-server diagnostic into its VS Code client representation. */
export function toVsCodeDiagnostic(diagnostic: LspDiagnostic): vscode.Diagnostic {
const range = new vscode.Range(
diagnostic.range.start.line,
diagnostic.range.start.character,
diagnostic.range.end.line,
diagnostic.range.end.character
);
const result = new vscode.Diagnostic(
range,
diagnostic.message,
toVsCodeSeverity(diagnostic.severity)
);
result.source = diagnostic.source;
return result;
}

/** Opens Problems and highlights the first ANTLR error in the parsed document. */
export async function revealFirstAntlrError(
document: vscode.TextDocument,
diagnostics: readonly vscode.Diagnostic[]
): Promise<void> {
const firstError = diagnostics[0];
if (!firstError) {
return;
}

await vscode.commands.executeCommand('workbench.action.showErrorsWarnings');
const range = firstError.range;
const editor = await vscode.window.showTextDocument(document, {
preview: false,
selection: range
});
editor.selection = new vscode.Selection(range.start, range.end);
editor.revealRange(range, vscode.TextEditorRevealType.InCenterIfOutsideViewport);
}
25 changes: 25 additions & 0 deletions tptplus/client/src/antlrParser/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export interface LspPosition {
line: number;
character: number;
}

export interface LspRange {
start: LspPosition;
end: LspPosition;
}

export interface LspDiagnostic {
range: LspRange;
message: string;
severity?: number;
source?: string;
}

export interface ParseWithAntlrResult {
ok: boolean;
diagnostics: LspDiagnostic[];
summary: {
elapsedMs: number;
syntaxErrorCount: number;
};
}
4 changes: 3 additions & 1 deletion tptplus/client/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {

import { errorMessage } from './errorMessage';
import { createSystemB4TptpForm } from './systemTptpForms';
import { registerAntlrParserCommand } from './antlrParser/command';
import { registerPrettyPrintCommand } from './prettyPrint/command';
import { registerTypeCheckCommand } from './typeCheck/command';

Expand Down Expand Up @@ -2410,7 +2411,8 @@ export function activate(context: ExtensionContext) {
);

// Start the client (and server)
client.start();
const clientReady = client.start();
context.subscriptions.push(registerAntlrParserCommand(client, clientReady));
}

export function deactivate(): Thenable<void> | undefined {
Expand Down
Loading
Loading