All files / services/document document-diagnostics-service.ts

95.03% Statements 153/161
79.01% Branches 64/81
100% Functions 32/32
94.77% Lines 145/153

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575                                                                                  36x         36x                     36x       36x         36x                   36x   36x 16x   1x 1x     3x   1x 1x         1x 1x       1x     1x   1x 1x               36x 9x                                           6x 6x       6x   6x 8x   8x   8x 1x     7x     8x 1x       7x       6x 6x                   6x 6x   6x   8x 2x       8x               18x                       3x   3x 1x     2x                     16x 2x   14x 14x                   2x       2x   2x   2x 1x                     15x 13x   13x 13x     13x     2x   2x 1x                   30x                             11x 1x     10x                 1x                       35x   35x       35x 2x 2x     33x 33x 29x           4x 3x     4x                                   29x           29x 3x 3x 3x   26x       26x             26x   26x 26x 26x     29x       29x           29x                           26x 24x 24x   24x             10x   10x   10x                   29x     4x   4x                         29x   17x   17x 17x       17x             17x 9x         8x         8x 8x 8x         8x           17x           29x 29x 29x   29x 147x     29x 225x 225x     225x 27x   27x 27x       225x 1143x       29x 147x     29x               21x               21x     21x   21x   21x 21x     21x       21x       1x 1x   1x 6x        
import * as vscode from 'vscode';
import type { ILexingError } from 'chevrotain';
import { createFileBlankNodeIdGenerator, IRecognitionException, IToken, RdfSyntax, tokenizeWithTriplate, TriplateLexingResult, TurtleQuadReader } from '@faubulous/mentor-rdf-parsers';
import { Diagnostic as LspDiagnostic, DiagnosticSeverity as LspDiagnosticSeverity, Range as LspRange } from 'vscode-languageserver-types';
import { ParserFactory } from '@src/languages/parser-factory';
import { SparqlUnusedVariableLinter } from '@src/languages/sparql/sparql-unused-variable-linter';
import { XmlParser } from '@src/languages/xml/xml-parser';
import { XmlDocument } from '@src/languages/xml/xml-document';
import { getConfig } from '@src/utilities/vscode/config';
import { createEventLoopYielder, yieldToEventLoop } from '@src/utilities/scheduling';
import { getNamespaceDefinition, PrefixMap } from '@src/utilities';
import { createPositionMapper, PositionMapper } from '@src/utilities/position';
import { LintingContext, LintingProvider } from '@src/providers/linting';
import {
	DeprecatedWorkspaceUriLinter,
	InlineSingleUseBlankNodesLinter,
	NamespacePrefixLinter,
	XsdAnyUriLiteralLinter,
	XsdDatatypeValidationLinter,
} from '@src/providers/linting/linters';
import { IDocumentContext, ITokenizedDocumentContext } from './document-context.interface';
import { IDocumentTokenSource, TokenDelivery } from './document-token-source.interface';
 
/**
 * Computes document diagnostics in the extension host: syntax (lexer/parser)
 * errors and lint rule results for the Turtle family and SPARQL, and parse
 * errors for RDF/XML.
 *
 * By default (`mentor.index.diagnoseFiles`), every loaded document is
 * validated — including the editor-invisible documents opened by the workspace
 * indexer — so the problems panel gives an overview of all issues in the
 * workspace after an index run. Because VS Code garbage-collects documents that
 * are not shown in an editor shortly after the indexer opened them, diagnostics
 * are kept when such documents close and are only removed when the file itself
 * is deleted or renamed. When the setting is disabled, only documents visible
 * in an editor are validated, which speeds up workspace indexing.
 *
 * Validation is triggered by token deliveries from the token source (document
 * loads and debounced edits) and by documents becoming visible.
 */
export class DocumentDiagnosticsService implements vscode.Disposable {
	private readonly _collection = vscode.languages.createDiagnosticCollection('mentor');
 
	/**
	 * Pluggable lint rules that apply to all token-based documents.
	 */
	private readonly _linters: LintingProvider[] = [
		new DeprecatedWorkspaceUriLinter(),
		new InlineSingleUseBlankNodesLinter(),
		new NamespacePrefixLinter(),
		new XsdAnyUriLiteralLinter(),
		new XsdDatatypeValidationLinter(),
	];
 
	/**
	 * Additional lint rules that only apply to SPARQL documents.
	 */
	private readonly _sparqlLinters: LintingProvider[] = [
		new SparqlUnusedVariableLinter(),
	];
 
	private readonly _subscriptions: vscode.Disposable[] = [];
 
	/**
	 * The URIs of loaded documents whose validation waits for the event loop.
	 */
	private readonly _pendingLoadValidations = new Set<string>();
 
	/**
	 * @param tokenSource The token source whose deliveries trigger validation.
	 * @param _getContext Returns the document context for a URI, or `undefined` when
	 * none is loaded. Injected as a function to avoid a construction-order cycle with
	 * the document context service.
	 */
	constructor(
		tokenSource: IDocumentTokenSource,
		private readonly _getContext: (uri: string) => IDocumentContext | undefined
	) {
		this._subscriptions.push(
			tokenSource.onDidDeliverTokens(delivery => this._handleTokenDelivery(delivery)),
			vscode.window.onDidChangeVisibleTextEditors(editors => {
				for (const editor of editors) {
					this._validate(editor.document);
				}
			}),
			vscode.workspace.onDidCloseTextDocument(document => this._handleDocumentClosed(document)),
			vscode.workspace.onDidDeleteFiles(e => {
				for (const uri of e.files) {
					this._collection.delete(uri);
				}
			}),
			vscode.workspace.onDidRenameFiles(e => {
				// The renamed file is re-indexed under its new URI, which re-validates it.
				for (const file of e.files) {
					this._collection.delete(file.oldUri);
				}
			}),
			vscode.workspace.onDidChangeConfiguration(e => {
				Eif (e.affectsConfiguration('mentor.index.diagnoseFiles')) {
					// Reset to the new scope: drop everything and re-validate what is
					// visible; a re-index repopulates the workspace-wide overview.
					this._collection.clear();
 
					for (const editor of vscode.window.visibleTextEditors) {
						this._validate(editor.document);
					}
				}
			})
		);
 
		// Validate the editors that are already visible at construction time. Documents
		// without a loaded context yet are picked up by the token deliveries that follow.
		for (const editor of vscode.window.visibleTextEditors) {
			this._validate(editor.document);
		}
	}
 
	/**
	 * Runs an explicit syntax and lint validation over the given files and
	 * publishes the results to the Problems panel — used by the Diagnose Workspace
	 * command. Reads each file's content (from an already-open document when
	 * present, otherwise from disk) and validates it in-process via
	 * {@link diagnoseContent}, without opening a `vscode.TextDocument`. Files that
	 * were not indexed (no context) or cannot be read are skipped.
	 * @param uris The files to validate.
	 * @param onProgress Optional callback invoked once per file with the number
	 * processed so far and the total, for status bar progress.
	 * @param token Optional token that stops the validation before the next file.
	 * @returns The number of files validated and how many have at least one error.
	 */
	async diagnoseFiles(
		uris: readonly vscode.Uri[],
		onProgress?: (processed: number, total: number) => void,
		token?: vscode.CancellationToken
	): Promise<{ validated: number; filesWithErrors: number }> {
		let validated = 0;
		let filesWithErrors = 0;
 
		// Validation is CPU-bound; yield between files so a workspace-wide pass
		// does not block the extension host.
		const eventLoop = createEventLoopYielder();
 
		for (let i = 0; i < uris.length; i++) {
			const uri = uris[i];
 
			await eventLoop.yieldIfBusy();
 
			if (token?.isCancellationRequested) {
				break;
			}
 
			onProgress?.(i + 1, uris.length);
 
			// Only indexed files have a context to validate against.
			if (!this._getContext(uri.toString())) {
				continue;
			}
 
			// Prefer an already-open document's live text; otherwise read the bytes.
			const openDocument = vscode.workspace.textDocuments.find(d => d.uri.toString() === uri.toString());
 
			let content: string;
 
			if (openDocument) {
				content = openDocument.getText();
			} else E{
				try {
					content = new TextDecoder().decode(await vscode.workspace.fs.readFile(uri));
				} catch {
					// Binary/undecodable files cannot be validated as text.
					continue;
				}
			}
 
			this.diagnoseContent(uri, content);
			validated++;
 
			const problems = this._collection.get(uri) ?? [];
 
			if (problems.some(d => d.severity === vscode.DiagnosticSeverity.Error)) {
				filesWithErrors++;
			}
		}
 
		return { validated, filesWithErrors };
	}
 
	/**
	 * Indicates whether all indexed files are validated (workspace-wide problems
	 * overview) or only documents visible in an editor.
	 */
	private _isWorkspaceScope(): boolean {
		return getConfig().get('index.diagnoseFiles', true);
	}
 
	/**
	 * Removes diagnostics for closed documents — but only when validation is
	 * scoped to visible editors, or the document is discarded with its close
	 * (e.g. untitled). With workspace-wide validation, VS Code garbage-collecting
	 * the editor-invisible documents opened by the indexer must not erase the
	 * problems overview.
	 * @param document The closed document.
	 */
	private _handleDocumentClosed(document: vscode.TextDocument): void {
		const isDiscarded = document.uri.scheme === 'untitled' || document.uri.scheme === 'git';
 
		if (this._isWorkspaceScope() && !isDiscarded) {
			return;
		}
 
		this._collection.delete(document.uri);
	}
 
	/**
	 * Validates a document whose tokens were delivered. An edit is validated right
	 * away, so that errors show as soon as possible. A document load is validated
	 * after the event loop has polled for I/O: requests that only need the tokens,
	 * such as go to definition, are answered before the diagnostics are computed.
	 * @param delivery The token delivery.
	 */
	private _handleTokenDelivery(delivery: TokenDelivery): void {
		if (delivery.consumed) {
			this._validateAfterYield(delivery.uri);
		} else {
			this._pendingLoadValidations.delete(delivery.uri);
			this._validateIfInScope(delivery.uri);
		}
	}
 
	/**
	 * Validates the document for a URI once the event loop has polled for I/O,
	 * unless an edit validated it in the meantime.
	 * @param uri The document URI.
	 */
	private async _validateAfterYield(uri: string): Promise<void> {
		Iif (this._pendingLoadValidations.has(uri)) {
			return;
		}
 
		this._pendingLoadValidations.add(uri);
 
		await yieldToEventLoop();
 
		if (this._pendingLoadValidations.delete(uri)) {
			this._validateIfInScope(uri);
		}
	}
 
	/**
	 * Validates the document for a URI when it is in scope: any loaded document
	 * when `index.diagnoseFiles` is enabled, otherwise only documents
	 * visible in an editor.
	 * @param uri The document URI.
	 */
	private _validateIfInScope(uri: string): void {
		if (this._isWorkspaceScope()) {
			const document = vscode.workspace.textDocuments.find(d => d.uri.toString() === uri);
 
			Eif (document) {
				this._validate(document);
			}
 
			return;
		}
 
		const editor = vscode.window.visibleTextEditors.find(e => e.document.uri.toString() === uri);
 
		if (editor) {
			this._validate(editor.document);
		}
	}
 
	/**
	 * Computes and publishes diagnostics for an open document, using its own
	 * `positionAt` for offset → position mapping.
	 * @param document The document to validate.
	 */
	private _validate(document: vscode.TextDocument): void {
		this._diagnose(document.uri, document.getText(), offset => document.positionAt(offset));
	}
 
	/**
	 * Computes and publishes syntax and lint diagnostics for an indexed file
	 * directly from its content, without opening a `vscode.TextDocument`. Mirrors
	 * how SHACL validation publishes from the in-memory context: offsets are
	 * mapped to positions with a content-backed mapper instead of a document.
	 * Used by the workspace indexer so `index.diagnoseFiles` gives a workspace-wide
	 * overview without the per-file document-open cost. Skips files without a
	 * loaded context.
	 * @param uri The document URI.
	 * @param content The document text (as read for indexing).
	 */
	diagnoseContent(uri: vscode.Uri, content: string): void {
		if (!this._getContext(uri.toString())) {
			return;
		}
 
		this._diagnose(uri, content, createPositionMapper(content));
	}
 
	/**
	 * Removes the published diagnostics of a file that no longer exists, so that its
	 * problems disappear from the Problems panel.
	 * @param uri The URI of the removed file.
	 */
	deleteDiagnostics(uri: vscode.Uri): void {
		this._collection.delete(uri);
	}
 
	/**
	 * Computes and publishes diagnostics for a locally tokenized document,
	 * mirroring the language server's validation: lexer errors, parser and
	 * semantic errors, and lint rule results.
	 * @param uri The document URI.
	 * @param content The document text.
	 * @param positionAt Maps a character offset to a position.
	 */
	private _diagnose(uri: vscode.Uri, content: string, positionAt: PositionMapper): void {
		const context = this._getContext(uri.toString());
 
		Iif (!context) {
			return;
		}
 
		if (!content.length) {
			this._collection.set(uri, []);
			return;
		}
 
		try {
			if (context.isTokenized()) {
				this._collection.set(uri, this._computeDiagnostics(uri, context, content, positionAt));
			} else {
				// Structurally parsed documents (RDF/XML): the parse either succeeds
				// or the catch below reports the failure, matching the previous
				// language server behavior. A text the document context has just
				// parsed without error is not parsed a second time.
				if (!(context instanceof XmlDocument && context.isParsedFrom(content))) {
					new XmlParser().parse(content);
				}
 
				this._collection.set(uri, []);
			}
		} catch (e) {
			this._collection.set(uri, [
				new vscode.Diagnostic(
					new vscode.Range(0, 0, 0, 0),
					e ? e.toString() : 'An error occurred while parsing the document.',
					vscode.DiagnosticSeverity.Error
				),
			]);
		}
	}
 
	private _computeDiagnostics(uri: vscode.Uri, context: ITokenizedDocumentContext, content: string, positionAt: PositionMapper): vscode.Diagnostic[] {
		// Reuse the token streams and errors captured by the context's parse()
		// when they were produced from exactly this content — the normal case,
		// because validation follows a token delivery or a document load. Only
		// the linters then run per validation.
		const cached = context.getParseResult(content);
 
		let tokens: IToken[];
		let lexErrors: ILexingError[];
		let errors: IRecognitionException[];
 
		if (cached) {
			tokens = cached.tokens;
			lexErrors = cached.lexErrors;
			errors = [...cached.parserErrors, ...cached.semanticErrors];
		} else {
			const lexer = ParserFactory.getLexer(context.syntax);
 
			// The lexer instance is shared — set the generator on every call so a
			// file-scoped generator does not leak between documents.
			lexer.blankNodeIdGenerator = createFileBlankNodeIdGenerator(uri.toString());
 
			// Triplate-aware tokenization: the parser consumes placeholder `parseTokens`
			// (so its CST/error recovery stay correct) while `tokens` is the faithful
			// stream that the lint diagnostics consume. `lexErrors` are the characters
			// the lexer could not match — it skips them (no token is emitted), so they
			// are only surfaced here.
			const lexingResult = tokenizeWithTriplate(lexer, content);
 
			tokens = lexingResult.tokens;
			lexErrors = lexingResult.errors;
			errors = this._getSyntaxErrors(context.syntax, lexingResult);
		}
 
		const linters = context.syntax === RdfSyntax.Sparql
			? [...this._linters, ...this._sparqlLinters]
			: this._linters;
 
		const diagnostics = [
			...this._getLexDiagnostics(positionAt, lexErrors),
			...this._getParseDiagnostics(positionAt, content, errors),
			...this._getLintDiagnostics(positionAt, content, tokens, linters),
		];
 
		return diagnostics.map(d => this._toVscodeDiagnostic(d));
	}
 
	/**
	 * Returns the syntax errors of a lexed document. A Turtle document is read
	 * with the quad reader first, the way the document context reads it (see
	 * `TurtleDocument._analyze`): a document the reader accepts has no syntax
	 * errors, and only a rejected one goes through the grammar parser with error
	 * recovery, which lists every error but costs far more.
	 * @param syntax The syntax of the document.
	 * @param lexingResult The tokens of the document.
	 * @returns The parser and semantic errors.
	 */
	private _getSyntaxErrors(syntax: RdfSyntax, lexingResult: TriplateLexingResult): IRecognitionException[] {
		if (syntax === RdfSyntax.Turtle && !lexingResult.template) {
			try {
				new TurtleQuadReader().read(lexingResult.tokens);
 
				return [];
			} catch {
				// A syntax error, or the reader giving up (e.g. on a pathologically nested
				// document): the grammar parser reports what it finds.
			}
		}
 
		const parser = ParserFactory.getParser(syntax);
 
		parser.parse(lexingResult.parseTokens, false);
 
		return [...parser.errors, ...parser.semanticErrors];
	}
 
	/**
	 * Maps lexer errors to diagnostics. The lexer skips characters it cannot
	 * match (no token is emitted for them) and records them here, so these are
	 * the only signal for invalid characters — e.g. junk appended to an IRI —
	 * that leaves a token stream which still parses.
	 */
	private _getLexDiagnostics(positionAt: PositionMapper, errors: ILexingError[]): LspDiagnostic[] {
		return errors.map(
			(error): LspDiagnostic => {
				// Guarantee a visible range even for a zero-length error.
				const length = Math.max(error.length ?? 0, 1);
 
				return {
					severity: LspDiagnosticSeverity.Error,
					message: error.message,
					range: {
						start: positionAt(error.offset),
						end: positionAt(error.offset + length),
					},
				};
			}
		);
	}
 
	private _getParseDiagnostics(positionAt: PositionMapper, content: string, errors: IRecognitionException[]): LspDiagnostic[] {
		return errors.map(
			(error): LspDiagnostic => {
				const { message, name, context, token } = error;
 
				const ruleStack = context ? context.ruleStack : null;
				const source = ruleStack && ruleStack.length > 0
					? ruleStack[ruleStack.length - 1]
					: undefined;
 
				const constructedDiagnostic: Partial<LspDiagnostic> = {
					code: name,
					message,
					source,
					severity: LspDiagnosticSeverity.Error,
				};
 
				if (token.tokenType?.name !== 'EOF') {
					constructedDiagnostic.range = LspRange.create(
						positionAt(token.startOffset),
						positionAt((token.endOffset ?? token.startOffset) + 1)
					);
				} else {
					const { previousToken = {} } = error as any; // chevrotain doesn't have this typed fully, but it exists for early exit exceptions
 
					let rangeStart;
					let rangeEnd;
 
					if (typeof previousToken.endOffset !== 'undefined') {
						rangeStart = Math.min(previousToken.endOffset + 1, content.length);
						rangeEnd = Math.min(previousToken.endOffset + 2, content.length);
					} else E{
						rangeStart = rangeEnd = content.length;
					}
 
					constructedDiagnostic.range = LspRange.create(
						positionAt(rangeStart),
						positionAt(rangeEnd)
					);
				}
 
				return constructedDiagnostic as LspDiagnostic;
			}
		);
	}
 
	private _getLintDiagnostics(positionAt: PositionMapper, content: string, tokens: IToken[], linters: LintingProvider[]): LspDiagnostic[] {
		const prefixes: PrefixMap = {};
		const context: LintingContext = { positionAt, content, tokens, prefixes };
		const result: LspDiagnostic[] = [];
 
		for (const linter of linters) {
			linter.reset?.();
		}
 
		for (let i = 0; i < tokens.length; i++) {
			const token = tokens[i];
			const type = token.tokenType?.name;
 
			// Keep the shared prefix map current so IRI-resolving providers see up-to-date prefixes.
			if (type === 'PREFIX' || type === 'TTL_PREFIX') {
				const ns = getNamespaceDefinition(tokens, token);
 
				Eif (ns) {
					prefixes[ns.prefix] = ns.uri;
				}
			}
 
			for (const linter of linters) {
				result.push(...linter.visitToken(context, token, i));
			}
		}
 
		for (const linter of linters) {
			result.push(...(linter.finalize?.(context) ?? []));
		}
 
		return result;
	}
 
	/**
	 * Converts an LSP protocol diagnostic — as produced by the shared diagnostics
	 * functions — into a vscode API diagnostic.
	 */
	private _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
		);
 
		// LSP severities are 1-based (Error = 1); vscode severities are 0-based (Error = 0).
		const severity = (diagnostic.severity ?? 1) - 1;
 
		// LSP allows MarkupContent messages; the diagnostics produced here are always plain strings.
		const message = typeof diagnostic.message === 'string' ? diagnostic.message : diagnostic.message.value;
 
		const result = new vscode.Diagnostic(range, message, severity);
 
		result.source = diagnostic.source;
		result.code = diagnostic.code;
 
		// LSP and vscode diagnostic tags share the same values (Unnecessary = 1, Deprecated = 2).
		Iif (diagnostic.tags) {
			result.tags = diagnostic.tags as unknown as vscode.DiagnosticTag[];
		}
 
		return result;
	}
 
	dispose(): void {
		this._pendingLoadValidations.clear();
		this._collection.dispose();
 
		for (const subscription of this._subscriptions) {
			subscription.dispose();
		}
	}
}