All files / services/document document-context.ts

100% Statements 125/125
96.2% Branches 76/79
95.45% Functions 21/22
100% Lines 117/117

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                                                                                  161x             9x                     161x         161x         161x         161x             161x           161x         161x   161x           17x 15x   15x 7x 11x 9x   2x         15x   15x   15x 9x 5x   5x         17x                   18x       10x   10x 9x   1x                     20x           161x           161x   161x 161x 161x                                   3x                                                                                 11x                 3x 2x 1x                     4x   4x   2x   2x                   21x 21x 21x   21x   12x     12x   12x 10x       2x   2x 1x       1x     2x 2x   2x 1x 1x     2x             8x                           28x 28x 28x   28x   28x 28x 17x 15x     15x 1x       14x 3x       11x 1x       11x 2x       11x 10x   2x 1x         1x                 23x 9x       23x 22x   20x                 5x 5x   5x 8x 7x 2x   5x     1x       5x                   8x 8x     8x   8x 2x     6x                   8x 2x     2x   1x 1x 1x     1x       7x                 5x 5x 5x   5x           15x    
import * as vscode from 'vscode';
import { Range } from 'vscode-languageserver-types';
import { container } from 'tsyringe';
import { Quad_Subject } from "@rdfjs/types";
import { Store, VocabularyRepository, _OWL, _RDF, _RDFS, _SH, _SKOS, _SKOS_XL, SH } from '@faubulous/mentor-rdf';
import { Uri, NamedNode, BlankNode, Literal } from '@faubulous/mentor-rdf';
import { PredicateUsageStats, LanguageTagUsageStats } from '@faubulous/mentor-rdf';
import { ServiceToken } from '@src/services/tokens';
import { ISettingsService } from '@src/services/core';
import { WorkspaceUri } from '@src/providers/workspace-uri';
import { TreeLabelStyle } from '@src/services/core/settings-service';
import { getConfig } from '@src/utilities/vscode/config';
import { IDocumentContext } from './document-context.interface';
 
/**
 * A literal value with optional language tag.
 */
export interface Label {
	/**
	 * The value of the literal.
	 */
	value: string;
 
	/**
	 * The language tag of the literal, if any.
	 */
	language: string | undefined;
}
 
/**
 * A class that provides access to RDF document specific data such as namespaces, graphs and token maps.
 */
export abstract class DocumentContext implements IDocumentContext {
	/**
	 * The URI of the document.
	 */
	readonly uri: vscode.Uri;
 
	/**
	 * The graphs in the triple store associated with the document.
	 */
	readonly graphs: string[] = [];
 
	/**
	 * Get the URI of the document graph in the triple store.
	 * @note This is a workspace-relative URI so that queries which are persisted in a repository are portable.
	 */
	get graphIri(): vscode.Uri {
		return WorkspaceUri.toWorkspaceUri(this.uri) || this.uri;
	}
 
	/**
	 * Get the base IRI of the document that can be used for resolving local names into IRIs.
	 */
	baseIri: string | undefined;
 
	/**
	 * Maps prefixes to namespace IRIs.
	 */
	namespaces: { [key: string]: string } = {};
 
	/**
	 * Maps prefixes to the location of their definition in the document.
	 */
	namespaceDefinitions: { [key: string]: Range[] } = {};
 
	/**
	 * Maps IRIs that appear as subjects to the locations where they appear in the document.
	 */
	subjects: { [key: string]: Range[] } = {};
 
	/**
	 * Maps IRIs of all resources to the locations where they appear in the document.
	 */
	references: { [key: string]: Range[] } = {};
 
	// TODO: Remove all type definitions from this map and query the combination of typeAssertion and typeDefinitions instead.
	/**
	 * Maps IRIs of subjects that have an asserted rdf:type to the location of the type assertion. This includes
	 * named individuals, classes and properties.
	 */
	typeAssertions: { [key: string]: Range[] } = {};
 
	/**
	 * Maps IRIs of subjects that are class or property definitions to the location of the definition. This includes
	 * only class defintions.
	 */
	typeDefinitions: { [key: string]: Range[] } = {};
 
	/**
	 * Information about the language tags used in the document.
	 */
	predicateStats: PredicateUsageStats = {};
 
	private _primaryLanguage: string | undefined | null = null;
 
	/**
	 * The most often used language tag in the document.
	 */
	get primaryLanguage(): string | undefined {
		if (this._primaryLanguage === null && this.predicateStats) {
			let languageStats: LanguageTagUsageStats = {};
 
			for (let [_, value] of Object.entries(this.predicateStats)) {
				for (let [lang, count] of Object.entries(value.languageTags)) {
					if (!languageStats[lang]) {
						languageStats[lang] = count;
					} else {
						languageStats[lang] += count;
					}
				}
			}
 
			let maxFrequency = -1;
 
			this._primaryLanguage = undefined;
 
			for (let [lang, frequency] of Object.entries(languageStats)) {
				if (lang && frequency > maxFrequency) {
					maxFrequency = frequency;
 
					this._primaryLanguage = lang;
				}
			}
		}
 
		return this._primaryLanguage ?? undefined;
	}
 
	private _activeLanguageTag: string | undefined;
 
	/**
	 * The ISO 639-3 language tag of the user-selected display document language. This value
	 * can be used to restore the user's selection when switching between documents.
	 */
	get activeLanguageTag(): string | undefined {
		return this._activeLanguageTag;
	}
 
	set activeLanguageTag(value: string | undefined) {
		this._activeLanguageTag = value;
 
		if (value) {
			this._activeLanguage = value.split('-')[0];
		} else {
			this._activeLanguage = undefined;
		}
	}
 
	private _activeLanguage: string | undefined;
 
	/**
	 * The language portion of the active ISO 639-3 language tag without the regional part.
	 * e.g. 'en' for the language tags 'en' or 'en-gb'.
	 */
	get activeLanguage(): string | undefined {
		return this._activeLanguage;
	}
 
	/**
	 * The predicates to be used for retrieving labels and descriptions for resources.
	 */
	readonly predicates = {
		label: [] as string[],
		description: [] as string[]
	};
 
	constructor(documentUri: vscode.Uri) {
		const config = getConfig();
 
		this.uri = documentUri;
		this.predicates.label = config.get('predicates.label') ?? [];
		this.predicates.description = config.get('predicates.description') ?? [];
	}
 
	/**
	 * Indicates whether the document is fully loaded.
	 */
	abstract get isLoaded(): boolean;
 
	/**
	 * Indicates whether tokens have been set for this document.
	 * Used to determine if we need to wait for tokens from the language server.
	 */
	abstract get hasTokens(): boolean;
 
	/**
	 * Indicates whether the document is temporary and not persisted.
	 */
	get isTemporary(): boolean {
		return this.uri.scheme == 'git' || this.uri.scheme == 'untitled';
	}
 
	/**
	 * Loads triples into the triple store using existing tokens.
	 * This method assumes tokens have already been set via setTokens().
	 * @param data The file content.
	 */
	abstract loadTriples(data: string): Promise<void>;
 
	/**
	 * Infers new triples from the document, if not already done.
	 */
	abstract infer(): Promise<void>;
 
	/**
	 * Get the full IRI of a resource at the given position in the document.
	 * @param position The position in the document.
	 * @returns The full IRI of the resource or `undefined` if not found.
	 */
	abstract getIriAtPosition(position: vscode.Position): string | undefined;
 
	/**
	 * Get a literal value at the given position in the document.
	 * @param position The position in the document.
	 * @returns The literal value at the position or `undefined` if there is no literal value at that position.
	 */
	abstract getLiteralAtPosition(position: vscode.Position): string | undefined;
 
	/**
	 * Event handler for when the document is changed.
	 * @param e The document change event.
	 **/
	async onDidChangeDocument(e: vscode.TextDocumentChangeEvent): Promise<void> { };
 
	/**
	 * Get the text document with the given URI.
	 * @param uri The URI of the text document.
	 * @returns The text document if it is loaded, null otherwise.
	 */
	getTextDocument(): vscode.TextDocument | undefined {
		return vscode.workspace.textDocuments.find(d => d.uri.toString() === this.uri.toString());
	}
 
	/**
	 * Get the prefix for a namespace IRI.
	 * @param namespaceIri The namespace IRI.
	 * @returns The prefix for the namespace IRI or `undefined`.
	 */
	getPrefixForNamespaceIri(namespaceIri: string): string | undefined {
		for (let [prefix, iri] of Object.entries(this.namespaces)) {
			if (iri === namespaceIri) {
				return prefix;
			}
		}
	}
 
	/**
	 * Updates a namespace prefix definition in the document.
	 * @param oldPrefix The prefix to be replaced.
	 * @param newPrefix The prefix to replace the old prefix.
	 */
	updateNamespacePrefix(oldPrefix: string, newPrefix: string) {
		const uri = this.namespaces[oldPrefix];
 
		if (!uri) return;
 
		delete this.namespaces[oldPrefix];
 
		this.namespaces[newPrefix] = uri;
	}
 
	/**
	 * Get the label of a resource according to the current user preferences for the display of labels.
	 * @param subjectUri URI of the resource.
	 * @returns A label for the resource as a string literal.
	 */
	getResourceLabel(subjectUri: string): Label {
		// TODO: Fix #10 in mentor-rdf; Refactor node identifiers to be node instances instead of strings.
		const subject = subjectUri.includes(':') ? new NamedNode(subjectUri) : new BlankNode(subjectUri);
		const settings = container.resolve<ISettingsService>(ServiceToken.SettingsService);
		const treeLabelStyle = settings.get<TreeLabelStyle>('view.definitionTree.labelStyle', TreeLabelStyle.AnnotatedLabels);
 
		switch (treeLabelStyle) {
			case TreeLabelStyle.AnnotatedLabels: {
				const predicates = this.predicates.label.map(p => new NamedNode(p));
 
				// First, try to find a description in the current graph.
				let result = this._getResourceAnnotationFromPredicates(this.graphs, subject, predicates);
 
				if (result) {
					return result;
				}
 
				// If none is found, try to find a description in the default graph.
				result = this._getResourceAnnotationFromPredicates(undefined, subject, predicates);
 
				if (result) {
					return result;
				}
 
				// Fallback to URI labels without prefixes.
				break;
			}
			case TreeLabelStyle.UriLabelsWithPrefix: {
				const namespace = Uri.getNamespaceIri(subjectUri);
				let prefix = "?";
 
				for (let [p] of Object.entries(this.namespaces).filter(([_, ns]) => ns == namespace)) {
					prefix = p;
					break;
				}
 
				return {
					value: `${prefix}:${Uri.getLocalPart(subjectUri) || subjectUri}`,
					language: undefined
				};
			}
		}
 
		return {
			value: decodeURIComponent(Uri.getLocalPart(subjectUri) || subjectUri),
			language: undefined
		};
	}
 
	/**
	 * Get an annotation to a resource from a list of predicates. Either in the active document language or in the primary language.
	 * @param graphUris URIs of the graphs to query.
	 * @param subject A subject node.
	 * @param predicates A list of predicates to reqtrieve the label from.
	 * @returns The label of the resource as a string literal.
	 */
	private _getResourceAnnotationFromPredicates(graphUris: string[] | string | undefined, subject: NamedNode | BlankNode, predicates: NamedNode[]): Label | undefined {
		let languageLabel: Literal | undefined = undefined;
		let primaryLabel: Literal | undefined = undefined;
		let fallbackLabel: Literal | undefined = undefined;
 
		const store = container.resolve<Store>(ServiceToken.Store);
 
		for (let p of predicates) {
			for (let q of store.matchAll(graphUris, subject, p, null, false)) {
				if (q.object.termType === 'Literal') {
					const literal = q.object as Literal;
 
					// Prefer to return non-empty values.
					if (literal.value.length == 0) {
						continue;
					}
 
					// Check if the literal language matches the active language
					if (literal.language === this.activeLanguageTag) {
						return literal;
					}
 
					// Store the literal if it matches the active language without the regional part.
					if (this.activeLanguage && literal.language.startsWith(this.activeLanguage)) {
						languageLabel = literal;
					}
 
					// Store the literal if it matches the primary language
					if (this.primaryLanguage === literal.language) {
						primaryLabel = literal;
					}
 
					// Store the first literal as a fallback value.
					if (!fallbackLabel) {
						fallbackLabel = literal;
					}
				} else if (p.value === SH.path) {
					return {
						value: this.getPropertyPathLabel(q.object as Quad_Subject),
						language: undefined
					};
				} else {
					return {
						value: Uri.getLocalPart(q.object.value) || '',
						language: undefined
					};
				}
			}
 
			// If we have found a label given the current predicates, we can stop 
			// searching as the predicates are ordered in priority.
			if (languageLabel || primaryLabel || fallbackLabel) {
				break;
			}
		}
 
		if (languageLabel) return languageLabel;
		if (primaryLabel) return primaryLabel;
 
		return fallbackLabel;
	}
 
	/**
	 * Get a rendered version of a SHACL path as a string according to the current user preferences for label display.
	 * @param node The object of a SHACL path triple.
	 * @returns A rendered version of the SHACL path as a string.
	 */
	getPropertyPathLabel(node: Quad_Subject): string {
		let result = [];
		const vocabulary = container.resolve<VocabularyRepository>(ServiceToken.VocabularyRepository);
 
		for (let c of vocabulary.getPropertyPathTokens(this.graphs, node)) {
			if (typeof (c) === 'string') {
				if (c === '|' || c === '/') {
					result.push(` ${c} `);
				} else {
					result.push(c);
				}
			} else {
				result.push(this.getResourceLabel(c.value).value);
			}
		}
 
		return result.join('');
	}
 
	/**
	 * Get the description of a resource.
	 * @param subjectUri URI of the resource.
	 * @returns A description for the resource as a string literal.
	 */
	getResourceDescription(subjectUri: string): Label | undefined {
		// TODO: Fix #10 in mentor-rdf; This is a hack: we need to return nodes from the Mentor RDF API instead of strings.
		const subject = subjectUri.includes(':') ? new NamedNode(subjectUri) : new BlankNode(subjectUri);
		const predicates = this.predicates.description.map(p => new NamedNode(p));
 
		// First, try to find a description in the current graph.
		let result = this._getResourceAnnotationFromPredicates(this.graphs, subject, predicates);
 
		if (result) {
			return result;
		}
 
		return this._getResourceAnnotationFromPredicates(undefined, subject, predicates);
	}
 
	/**
	 * Get the IRI of a resource. Resolves relative file IRIs with regards to the directory of the current document.
	 * @param subjectIri IRI of the resource.
	 * @returns A IRI for the resource as a string literal.
	 */
	getResourceIri(subjectIri: string): string {
		// TODO: Add support for virtual file systems provided by vscode such as vscode-vfs.
		if (subjectIri.startsWith('file')) {
			const u = vscode.Uri.parse(subjectIri);
 
			// Resolve relative file IRIs with regards to the directory of the current document.
			if (u.authority === '..') {
				// For a file URI the namespace is the directory of the current document.
				const directory = Uri.getNamespaceIri(this.uri.toString());
				const filePath = subjectIri.split('//')[1];
				const fileUrl = vscode.Uri.joinPath(vscode.Uri.parse(directory), filePath);
 
				// Allow navigating to the relative file.
				return '[' + filePath + '](' + fileUrl + ')';
			}
		}
 
		return subjectIri;
	}
 
	/**
	 * Get the tooltip for a resource.
	 * @param subjectUri URI of the resource.
	 * @returns A markdown string containing the label, description and URI of the resource.
	 */
	getResourceTooltip(subjectUri: string): vscode.MarkdownString {
		const iri = this.getResourceIri(subjectUri);
		const label = this.getResourceLabel(subjectUri);
		const description = this.getResourceDescription(subjectUri);
 
		let lines = [
			`**${label.value}**`,
			description?.value,
			iri
		];
 
		return new vscode.MarkdownString(lines.filter(line => line).join('\n\n'), true);
	}
}