All files / languages/linters inline-single-use-blank-nodes-linter.ts

52.63% Statements 10/19
12.5% Branches 1/8
100% Functions 2/2
52.63% Lines 10/19

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                9x                     215x       63x     63x   63x 215x 215x                         63x   63x                                     63x      
import { IToken, RdfToken } from '@faubulous/mentor-rdf-parsers';
import { Diagnostic, DiagnosticSeverity } from 'vscode-languageserver/browser';
import { LintDiagnosticsContext } from '../linter-context';
import { Linter } from '../linter';
 
/**
 * The diagnostic code for single-use blank nodes that can be inlined.
 */
export const INLINE_SINGLE_USE_BLANK_NODE_CODE = 'InlineSingleUseBlankNode';
 
/**
 * Detects named blank nodes (e.g. `_:b0`) that are used only once as a subject,
 * and therefore can be inlined into a blank node property list `[ ... ]`.
 *
 * Blank node subjects with a single occurrence in the token stream are reported as
 * hints, indicating the blank node can be inlined.
 */
export class InlineSingleUseBlankNodesLinter implements Linter {
	visitToken(_context: LintDiagnosticsContext, _token: IToken, _index: number): Diagnostic[] {
		return [];
	}
 
	finalize(context: LintDiagnosticsContext): Diagnostic[] {
		const { document, tokens } = context;
 
		// Group all BLANK_NODE_LABEL tokens by label value.
		const occurrences = new Map<string, IToken[]>();
 
		for (const token of tokens) {
			Eif (token.tokenType?.name !== RdfToken.BLANK_NODE_LABEL.name) {
				continue;
			}
 
			const label = token.image;
			const list = occurrences.get(label);
 
			if (list) {
				list.push(token);
			} else {
				occurrences.set(label, [token]);
			}
		}
 
		const diagnostics: Diagnostic[] = [];
 
		for (const [label, tokenList] of occurrences) {
			if (tokenList.length !== 1) {
				continue;
			}
 
			const token = tokenList[0];
 
			diagnostics.push({
				code: INLINE_SINGLE_USE_BLANK_NODE_CODE,
				severity: DiagnosticSeverity.Hint,
				message: `Single-use blank node '${label}' can be inlined.`,
				source: 'Mentor',
				range: {
					start: document.positionAt(token.startOffset),
					end: document.positionAt((token.endOffset ?? token.startOffset) + 1),
				},
			});
		}
 
		return diagnostics;
	}
}