All files / languages/turtle/services turtle-prefix-definition-service.ts

100% Statements 172/172
90.82% Branches 99/109
100% Functions 19/19
100% Lines 163/163

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                                                              48x 48x   48x             48x         48x         48x             4x   4x   3x     3x   3x 5x 4x 4x       3x     2x 2x 2x 2x       4x 4x 2x         4x 2x   2x                 5x   5x   4x 4x     4x   4x 8x   8x     5x   5x   5x 5x   5x 3x 3x 3x   3x     3x 1x   1x 1x   1x         5x         8x 2x       4x                 12x   12x   12x 11x     12x                     15x   15x 5x   10x                     2x   2x 4x   4x 2x     2x   2x                     15x 1x   14x 14x   14x 1x   13x                           14x 11x 3x 1x 2x 1x   1x                         10x     10x 10x   10x     10x 10x   4x 4x   4x   4x       10x 1x       10x 7x                         5x     5x 6x   3x     3x 3x 3x   3x 3x   3x   1x         5x   5x 1x       5x   5x 5x       5x 5x   5x 9x 9x   9x     5x                                           18x     18x 13x   5x           13x     13x   3x   3x     2x             13x 12x   12x   3x   3x 2x     3x       13x                 6x   6x     5x     5x     5x   5x   5x 9x   9x 3x     6x   3x   3x 1x       5x   2x   2x 1x       4x   4x     1x     3x     3x       5x 4x     5x       4x    
import * as vscode from 'vscode';
import { Uri } from '@faubulous/mentor-rdf';
import { IToken, RdfToken, TokenType } from '@faubulous/mentor-rdf-parsers';
import { isUpperCaseToken, getFirstTokenOfType, getLastTokenOfType } from '@faubulous/mentor-rdf-parsers';
import { DocumentContextService } from '@src/services/document/document-context-service';
import { PrefixLookupService } from '@src/services/document/prefix-lookup-service';
import { getIriFromIriReference } from '@src/utilities';
import { TurtleDocument } from '@src/languages';
import { TurtleFeatureProvider } from '@src/languages/turtle/turtle-feature-provider';
import { getConfig } from '@src/utilities/vscode/config';
 
/**
 * Specifies a how a namespace prefix should be defined in a document.
 */
export interface PrefixDefinition {
	/**
	 * The namespace prefix.
	 */
	prefix: string;
 
	/**
	 * The namespace IRI or `undefined` if the IRI should be looked up.
	 */
	namespaceIri: string | undefined;
}
 
/**
 * A service for declaring prefixes in RDF documents.
 */
export class TurtlePrefixDefinitionService extends TurtleFeatureProvider {
	constructor(
		private readonly contextService: DocumentContextService,
		private readonly prefixLookupService: PrefixLookupService
	) {
		super();
	}
 
	/**
	 * The default token type for prefix definitions. This is used when appending 
	 * new prefixes to the end of the prefix definition list.
	 */
	private _defaultPrefixTokenType = RdfToken.PREFIX;
 
	/**
	 * A set of supported token types for prefix definitions.
	 */
	private _prefixTokenTypes = new Set([RdfToken.PREFIX.name, RdfToken.TTL_PREFIX.name]);
 
	/**
	 * A set of supported token types for base IRI definitions.
	 */
	private _baseTokenTypes = new Set([RdfToken.BASE.name, RdfToken.TTL_BASE.name]);
 
	/**
	 * Sort the prefixes in a document.
	 * @param document The RDF document.
	 */
	public async sortPrefixes(document: vscode.TextDocument): Promise<vscode.WorkspaceEdit> {
		const context = this.contextService.getDocumentContext(document, TurtleDocument);
 
		if (!context) return new vscode.WorkspaceEdit();
 
		const edit = new vscode.WorkspaceEdit();
 
		// Collect prefix lines with their line numbers.
		const prefixLines: { line: number; text: string }[] = [];
 
		for (const token of context.tokens) {
			if (this._prefixTokenTypes.has(token.tokenType.name)) {
				const line = (token.startLine ?? 1) - 1;
				prefixLines.push({ line, text: document.lineAt(line).text });
			}
		}
 
		if (prefixLines.length === 0) return edit;
 
		// Sort lines by extracted prefix name.
		prefixLines.sort((a, b) => {
			const prefixA = a.text.match(/(?:@?prefix\s+)(\S*:)/i)?.[1]?.toLowerCase() ?? '';
			const prefixB = b.text.match(/(?:@?prefix\s+)(\S*:)/i)?.[1]?.toLowerCase() ?? '';
			return prefixA.localeCompare(prefixB);
		});
 
		// Replace the prefix block with sorted lines.
		const firstLine = Math.min(...prefixLines.map(p => p.line));
		const lastLine = Math.max(...prefixLines.map(p => p.line));
		const range = new vscode.Range(
			new vscode.Position(firstLine, 0),
			new vscode.Position(lastLine, document.lineAt(lastLine).text.length)
		);
 
		const sortedText = prefixLines.map(p => p.text).join('\n');
		edit.replace(document.uri, range, sortedText);
 
		return edit;
	}
 
	/**
	 * Delete prefix definitions from a document.
	 * @param document The RDF document.
	 * @param prefixes The prefixes to delete.
	 */
	public async deletePrefixes(document: vscode.TextDocument, prefixes: string[]): Promise<vscode.WorkspaceEdit> {
		const context = this.contextService.getDocumentContext(document, TurtleDocument);
 
		if (!context) return new vscode.WorkspaceEdit();
 
		const edit = new vscode.WorkspaceEdit();
		const prefixCount = Object.keys(context.namespaces).length;
 
		// Number of processed prefixes.
		let n = 0;
 
		for (let i = 0; i < context.tokens.length; i++) {
			const currentToken = context.tokens[i];
 
			switch (currentToken.tokenType.name) {
				case RdfToken.PREFIX.name:
				case RdfToken.TTL_PREFIX.name: {
					n = n + 1;
 
					const nextToken = context.tokens[i + 1];
 
					Eif (nextToken) {
						const prefix = nextToken.image.split(':')[0];
 
						if (prefixes.includes(prefix)) {
							let line = (nextToken.startLine ?? 1) - 1;
							let start = new vscode.Position(line, 0);
							let end = new vscode.Position(line + 1, 0);
 
							edit.delete(document.uri, new vscode.Range(start, end));
 
							// Delete any empty lines following the prefix definition of all prefixes but the last.
							while (n < prefixCount && line + 1 < document.lineCount && document.lineAt(line + 1).isEmptyOrWhitespace) {
								line++;
 
								start = new vscode.Position(line, 0);
								end = new vscode.Position(line + 1, 0);
 
								edit.delete(document.uri, new vscode.Range(start, end));
							}
						}
					}
 
					break;
				}
			}
 
			// Break if all prefixes have been caputred by the edit.
			if (edit.size === prefixes.length) {
				break;
			}
		}
 
		return edit;
	}
 
	/**
	 * Implement missing prefixes in a document.
	 * @param context The RDF document context.
	 * @param prefixes The prefixes to implement.
	 */
	public async implementPrefixes(document: vscode.TextDocument, prefixes: PrefixDefinition[]): Promise<vscode.WorkspaceEdit> {
		const edit = new vscode.WorkspaceEdit();
 
		const context = this.contextService.getDocumentContext(document, TurtleDocument);
 
		if (context) {
			await this._implementPrefixes(edit, document, context, prefixes);
		}
 
		return edit;
	}
 
	/**
	 * Implement missing prefixes in a document respecting the prefix definition mode set by the user.
	 * @param edit The workspace edit.
	 * @param document The text document.
	 * @param context The RDF document context.
	 * @param prefixes The prefixes to be implemented.
	 */
	private async _implementPrefixes(edit: vscode.WorkspaceEdit, document: vscode.TextDocument, context: TurtleDocument, prefixes: PrefixDefinition[]) {
		const mode = await getConfig().get('prefixes.prefixDefinitionMode');
 
		if (mode === 'Sorted') {
			await this._implementPrefixesSorted(edit, document, context, prefixes);
		} else {
			await this._implementPrefixesAppended(edit, document, context, prefixes);
		}
	}
 
	/**
	 * Delete empty lines after a token in a document.
	 * @param edit The workspace edit.
	 * @param document The text document.
	 * @param token The token after which to delete empty lines.
	 */
	private _deleteEmptyLinesAfterToken(edit: vscode.WorkspaceEdit, document: vscode.TextDocument, token: IToken) {
		let position = new vscode.Position(token.endLine ?? 0, 0);
 
		while (position.line < document.lineCount) {
			const line = document.lineAt(position.line);
 
			if (!line.isEmptyOrWhitespace) {
				break;
			}
 
			edit.delete(document.uri, line.rangeIncludingLineBreak);
 
			position = position.translate(1, 0);
		}
	}
 
	/**
	 * Get the token type for prefix definitions in a document. This is determined by checking the first prefix definition in the document or defaulting to the default token type if no prefix definitions are found.
	 * @param document The text document.
	 * @param context The RDF document context.
	 * @returns The token type for prefix definitions in the document.
	 */
	private _getPrefixTokenType(document: vscode.TextDocument, context: TurtleDocument): TokenType {
		if (document.languageId === 'xml') {
			return { name: 'XML_PREFIX' };
		} else {
			const hasDefaultPrefix = getFirstTokenOfType(context.tokens, this._defaultPrefixTokenType.name) !== undefined;
			const hasTurtlePrefixes = getFirstTokenOfType(context.tokens, RdfToken.TTL_PREFIX.name) !== undefined;
 
			if (hasTurtlePrefixes && !hasDefaultPrefix) {
				return RdfToken.TTL_PREFIX;
			} else {
				return this._defaultPrefixTokenType;
			}
		}
	}
 
	/**
	 * Implement a prefix for a IRI in a document using the provided token type for the prefix definition.
	 * @param tokenType The token type of the prefix definition.
	 * @param upperCase Whether the prefix should be in uppercase.
	 * @param prefix The prefix to implement.
	 * @param namespaceIri The namespace IRI for which to implement a prefix.
	 * @returns The prefix definition string.
	 */
	private _getPrefixDefinition(tokenType: TokenType, upperCase: boolean, prefix: string, namespaceIri: string): string {
		if (tokenType.name === RdfToken.PREFIX.name) {
			return `${upperCase ? 'PREFIX' : 'prefix'} ${prefix}: <${namespaceIri}>`;
		} else if (tokenType.name === RdfToken.TTL_PREFIX.name) {
			return `@prefix ${prefix}: <${namespaceIri}> .`;
		} else if (tokenType.name === 'XML_PREFIX') {
			return `xmlns:${prefix}="${namespaceIri}"`;
		} else {
			throw new Error(`Unsupported token type for prefix definition: ${tokenType}`);
		}
	}
 
	/**
	 * Implement missing prefixes in a document by appending the new prefixes to the end of the prefix definition list.
	 * @param document The text document.
	 * @param context The RDF document context.
	 * @param prefixes The prefixes to be implemented.
	 * @param tokenType The token type of the prefix token.
	 */
	private async _implementPrefixesAppended(edit: vscode.WorkspaceEdit, document: vscode.TextDocument, context: TurtleDocument, prefixes: PrefixDefinition[]) {
		// Insert the new prefix declaration after the last prefix declaration in the document.
		const lastPrefix = getLastTokenOfType(context.tokens, this._prefixTokenTypes);
 
		// Determine the token type for prefix definitions in the document and if they should be uppercase.
		const tokenType = this._getPrefixTokenType(document, context);
		const upperCase = isUpperCaseToken(lastPrefix ?? context.tokens[0]);
 
		let insertPosition = new vscode.Position(lastPrefix ? (lastPrefix.endLine ?? 0) : 0, 0);
 
		// 1. Append the new prefixes to the end of the prefix definition list.
		prefixes.sort()
			.filter(x => !context.namespaces[x.prefix] && !x.namespaceIri)
			.forEach(x => {
				const iri = x.namespaceIri ?? this.prefixLookupService.getUriForPrefix(context.uri.toString(), x.prefix);
				const definition = this._getPrefixDefinition(tokenType, upperCase, x.prefix, iri);
 
				edit.insert(context.uri, insertPosition, definition + '\n');
 
				insertPosition = insertPosition.translate(1, 0);
			});
 
		// 2. Delete leading new lines if there are any prefixes.
		if (lastPrefix) {
			this._deleteEmptyLinesAfterToken(edit, document, lastPrefix);
		}
 
		// 3. Insert a new line at the end of the document if there were any edits. Note: this also includes the deleted new lines.
		if (edit.size > 0) {
			edit.insert(context.uri, insertPosition, '\n');
		}
	}
 
	/**
	 * Implement missing prefixes in a document by maintaining a sorted list of prefixes at the beginning of the document.
	 * @param document The text document.
	 * @param context The RDF document context.
	 * @param prefixes The prefixes to be implemented.
	 * @param tokenType The token type of the prefix token.
	 */
	private async _implementPrefixesSorted(edit: vscode.WorkspaceEdit, document: vscode.TextDocument, context: TurtleDocument, prefixes: PrefixDefinition[]) {
		// 1. Delete the existing prefix definitions.
		let currentLine = 0;
 
		// Iterate over all tokens in the document...
		for (let token of context.tokens) {
			if (this._prefixTokenTypes.has(token.tokenType.name)) {
				// If we see a prefix token, delete the line and all preceding empty lines.
				const line = (token.startLine ?? 1) - 1;
 
				// Delete lines from the current line up to the start line of the prefix token
				while (currentLine <= line) {
					const start = new vscode.Position(currentLine, 0);
					const end = new vscode.Position(currentLine + 1, 0);
 
					edit.delete(context.uri, new vscode.Range(start, end));
					currentLine += 1;
				}
			} else if (token.startLine && token.startLine !== currentLine) {
				// If the token is on a new line and not a prefix token, we're done.
				break;
			}
		}
 
		// 2. Delete leading new lines and insert a new line at the beginning of the document.
		const lastPrefix = getLastTokenOfType(context.tokens, this._prefixTokenTypes);
 
		if (lastPrefix) {
			this._deleteEmptyLinesAfterToken(edit, document, lastPrefix);
		}
 
		// 3. Implement the prefixes in a sorted order.
		const namespaceMap = { ...context.namespaces };
 
		for (const x of prefixes) {
			namespaceMap[x.prefix] = x.namespaceIri ?? this.prefixLookupService.getUriForPrefix(context.uri.toString(), x.prefix);
		}
 
		// Determine the token type for prefix definitions in the document and if they should be uppercase.
		const tokenType = this._getPrefixTokenType(document, context);
		const upperCase = isUpperCaseToken(lastPrefix ?? context.tokens[0]);
 
		for (const prefix of Object.keys(namespaceMap).sort()) {
			const namespaceIri = namespaceMap[prefix];
			const definition = this._getPrefixDefinition(tokenType, upperCase, prefix, namespaceIri);
 
			edit.insert(context.uri, new vscode.Position(0, 0), definition + '\n');
		}
 
		edit.insert(context.uri, new vscode.Position(0, 0), '\n');
	}
 
	/**
	 * Resolve a unique prefix for a namespace IRI in the context of a document.
	 * 
	 * The logic is as follows:
	 * 1. If the IRI has a prefix defined in the local document, reuse it.
	 * 2. If not in the local document, check other documents - reuse the prefix if found.
	 * 3. If no prefix is defined anywhere, use the defaultValue.
	 * 4. Ensure the returned prefix is unique by appending numbers if there's a conflict.
	 * 5. For empty prefixes:
	 *    - Valid if same namespace IRI in same document.
	 *    - Valid if another document has it and current document has no empty prefix definition.
	 *    - Never disambiguate empty prefixes with numbers - fall back to defaultValue instead.
	 * 
	 * @param context The RDF document context.
	 * @param namespaceIri The namespace IRI to resolve a prefix for.
	 * @param defaultValue The default prefix to use if no prefix is found.
	 * @returns A unique prefix for the namespace IRI.
	 */
	getUniquePrefixForIri(context: TurtleDocument, namespaceIri: string, defaultValue: string): string {
		const documentUri = context.uri.toString();
 
		// Step 1: Check if the namespace IRI already has a prefix defined in the current document.
		for (const [prefix, iri] of Object.entries(context.namespaces)) {
			if (iri === namespaceIri) {
				// The exact prefix for this IRI already exists in this document - reuse it.
				return prefix;
			}
		}
 
		// Step 2: Look up the prefix in other documents, configuration, or default prefixes.
		// Note: getPrefixForIri returns empty prefix only from other documents, not as defaultValue.
		let prefix = this.prefixLookupService.getPrefixForIri(documentUri, namespaceIri, defaultValue);
 
		// Step 3: Handle empty prefix special rules.
		if (prefix === '') {
			// Check if the current document already has an empty prefix definition.
			const localEmptyPrefixIri = context.namespaces[''];
 
			if (localEmptyPrefixIri !== undefined) {
				// Current document has an empty prefix, but for a different IRI (we already
				// checked same IRI in step 1). We cannot use empty prefix - fall back to default.
				prefix = defaultValue;
			}
			// Otherwise, empty prefix from another document can be used since this document
			// doesn't have an empty prefix definition.
		}
 
		// Step 4: Ensure uniqueness for non-empty prefixes.
		if (prefix !== '') {
			const existingNamespaceIri = context.namespaces[prefix];
 
			if (existingNamespaceIri && existingNamespaceIri !== namespaceIri) {
				// There's a conflict - append a number to make it unique.
				let n = 1;
 
				while (context.namespaces[prefix + n] !== undefined) {
					n++;
				}
 
				prefix = prefix + n;
			}
		}
 
		return prefix;
	}
 
	/**
	 * Implement a prefix for a IRI in a document.
	 * @param document The RDF document.
	 * @param iri The namespace IRI for which to implement a prefix.
	 */
	async implementPrefixForIri(document: vscode.TextDocument, iri: string): Promise<vscode.WorkspaceEdit> {
		const context = this.contextService.getDocumentContext(document, TurtleDocument);
 
		if (!context) return new vscode.WorkspaceEdit();
 
		// The provided IRI may be a full IRI or a namespace IRI.
		const namespaceIri = Uri.getNamespaceIri(iri);
 
		// Resolve the prefix using the new logic.
		const prefix = this.getUniquePrefixForIri(context, namespaceIri, 'ns');
 
		// Check if the prefix is already defined with the exact same namespace IRI.
		const existingNamespaceIri = context.namespaces[prefix];
 
		const edit = new vscode.WorkspaceEdit();
 
		for (let i = 0; i < context.tokens.length; i++) {
			const token = context.tokens[i];
 
			if (token.tokenType.name !== RdfToken.IRIREF.name || !token.image.includes(namespaceIri)) {
				continue;
			}
 
			if (i > 0) {
				// Do not replace the IRI in a base definition.
				const t1 = context.tokens[i - 1];
 
				if (this._baseTokenTypes.has(t1.tokenType.name)) {
					continue;
				}
			}
 
			if (i > 1) {
				// Do not replace the IRI in a prefix definition.
				const t2 = context.tokens[i - 2];
 
				if (this._prefixTokenTypes.has(t2.tokenType.name)) {
					continue;
				}
			}
 
			const localName = getIriFromIriReference(token.image).substring(namespaceIri.length);
 
			if (!this._isValidLocalName(localName)) {
				// Skip if the local name contains a URI characters, indicating it's not a valid prefixed name.
				// See: https://github.com/faubulous/mentor-vscode/issues/55
				continue;
			}
 
			const range = context.getRangeFromToken(token);
 
			// Delete the entire IRI token.
			edit.replace(document.uri, range, `${prefix}:${localName}`);
		}
 
		// Only implement the prefix if not already defined.
		if (!existingNamespaceIri || existingNamespaceIri !== namespaceIri) {
			await this._implementPrefixes(edit, document, context, [{ prefix, namespaceIri }]);
		}
 
		return edit;
	}
 
	private _isValidLocalName(localName: string): boolean {
		return /^[A-Za-z0-9_\-\.]+$/.test(localName);
	}
}