Skip to content

Commit

Permalink
refactor: simplify shared module
Browse files Browse the repository at this point in the history
  • Loading branch information
johnsoncodehk committed Oct 31, 2022
1 parent a522f45 commit ab8cf5c
Show file tree
Hide file tree
Showing 23 changed files with 140 additions and 184 deletions.
4 changes: 2 additions & 2 deletions packages/language-server/src/utils/nodeFileSystemHost.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as shared from '@volar/shared';
import * as vscode from 'vscode-languageserver';
import { URI } from 'vscode-uri';
import { FileSystem, FileSystemHost } from '../types';
import { IterableWeakSet } from './iterableWeakSet';
import { createUriMap } from './uriMap';

let currentCwd = '';

Expand All @@ -11,7 +11,7 @@ export function createNodeFileSystemHost(
capabilities: vscode.ClientCapabilities,
): FileSystemHost {

const instances = shared.createUriMap<FileSystem>();
const instances = createUriMap<FileSystem>();
const onDidChangeWatchedFilesCb = new Set<(params: vscode.DidChangeWatchedFilesParams, reason: 'lsp' | 'web-cache-updated') => void>();
const caches = new IterableWeakSet<Map<string, boolean>>();

Expand Down
3 changes: 2 additions & 1 deletion packages/language-server/src/utils/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { ConfigurationHost } from '@volar/language-service';
import * as html from 'vscode-html-languageservice';
import * as path from 'typesafe-path';
import { CancellationTokenHost } from './cancellationPipe';
import { createUriMap } from './uriMap';

export interface Project extends ReturnType<typeof createProject> { }

Expand All @@ -37,7 +38,7 @@ export async function createProject(
let vueLs: embeddedLS.LanguageService | undefined;
let parsedCommandLine = createParsedCommandLine(ts, sys, shared.getPathOfUri(rootUri.toString()), tsConfig, plugins);

const scripts = shared.createUriMap<{
const scripts = createUriMap<{
version: number,
fileName: string,
snapshot: ts.IScriptSnapshot | undefined,
Expand Down
3 changes: 2 additions & 1 deletion packages/language-server/src/utils/snapshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { TextDocument } from 'vscode-languageserver-textdocument';
import * as vscode from 'vscode-languageserver';
import * as shared from '@volar/shared';
import type * as ts from 'typescript/lib/tsserverlibrary';
import { createUriMap } from './uriMap';

interface IncrementalScriptSnapshotChange {
applied: boolean,
Expand Down Expand Up @@ -173,7 +174,7 @@ function _combineContinuousChangeRanges(a: ts.TextChangeRange, b: ts.TextChangeR

export function createSnapshots(connection: vscode.Connection) {

const snapshots = shared.createUriMap<IncrementalScriptSnapshot>();
const snapshots = createUriMap<IncrementalScriptSnapshot>();
const onDidChangeContents = new Set<(params: vscode.DidChangeTextDocumentParams) => void>();
const onDidCloses = new Set<(params: vscode.DidCloseTextDocumentParams) => void>();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { URI } from 'vscode-uri';
import { getUriByPath as _getUriByPath } from './path';
import * as shared from '@volar/shared';

export * as _ from 'vscode-uri';

Expand Down Expand Up @@ -42,7 +42,7 @@ export function createUriMap<T>(map: Options<T> = new Map<string, T>()) {
pathToUriKeys.set(rootUri, map);
}
if (!map.has(path)) {
map.set(path, _getUriByPath(rootUri, path).toLowerCase());
map.set(path, shared.getUriByPath(rootUri, path).toLowerCase());
}
return map.get(path)!;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/language-server/src/utils/webFileSystemHost.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import * as shared from '@volar/shared';
import * as path from 'typesafe-path';
import { FileType } from 'vscode-html-languageservice';
import * as vscode from 'vscode-languageserver';
import { URI } from 'vscode-uri';
import { FsReadDirectoryRequest, FsReadFileRequest, FsStatRequest } from '../protocol';
import { FileSystem, FileSystemHost } from '../types';
import { matchFiles } from './ts/utilities';
import { createUriMap } from './uriMap';

let currentCwd = '/';

Expand All @@ -18,7 +18,7 @@ interface Dir {

export function createWebFileSystemHost(): FileSystemHost {

const instances = shared.createUriMap<FileSystem>();
const instances = createUriMap<FileSystem>();
const onDidChangeWatchedFilesCb = new Set<(params: vscode.DidChangeWatchedFilesParams, reason: 'lsp' | 'web-cache-updated') => void>();
const root: Dir = {
dirs: new Map(),
Expand Down
3 changes: 2 additions & 1 deletion packages/language-server/src/utils/workspaceProjects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { getInferredCompilerOptions } from './inferredCompilerOptions';
import { URI } from 'vscode-uri';
import { ConfigurationHost } from '@volar/language-service';
import { CancellationTokenHost } from './cancellationPipe';
import { createUriMap } from './uriMap';

export const rootTsConfigNames = ['tsconfig.json', 'jsconfig.json'];

Expand All @@ -29,7 +30,7 @@ export async function createWorkspaceProjects(

const sys = fsHost.getWorkspaceFileSystem(rootUri);
const documentRegistry = ts.createDocumentRegistry(sys.useCaseSensitiveFileNames, shared.normalizeFileName(rootUri.fsPath));
const projects = shared.createUriMap<Project>();
const projects = createUriMap<Project>();
const rootTsConfigs = new Set(sys.readDirectory(rootUri.fsPath, rootTsConfigNames, undefined, ['**/*']) as path.OsPath[]);
const disposeWatch = fsHost.onDidChangeWatchedFiles(async (params, reason) => {
const disposes: Promise<any>[] = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as shared from '@volar/shared';
import { transformLocations } from '@volar/transforms';
import * as vscode from 'vscode-languageserver-protocol';
import type { LanguageServiceRuntimeContext } from '../types';
import { getOverlapRange } from '../utils/common';
import * as dedupe from '../utils/dedupe';
import { languageFeatureWorker } from '../utils/featureWorkers';
import { embeddedEditToSourceEdit } from './rename';
Expand Down Expand Up @@ -50,7 +51,7 @@ export function register(context: LanguageServiceRuntimeContext) {
let maxEnd: number | undefined;

for (const mapping of sourceMap.mappings) {
const overlapRange = shared.getOverlapRange2(offsetRange.start, offsetRange.end, mapping.sourceRange[0], mapping.sourceRange[1]);
const overlapRange = getOverlapRange(offsetRange.start, offsetRange.end, mapping.sourceRange[0], mapping.sourceRange[1]);
if (overlapRange) {
const start = sourceMap.toGeneratedOffset(overlapRange.start)?.[0];
const end = sourceMap.toGeneratedOffset(overlapRange.end)?.[0];
Expand Down
4 changes: 2 additions & 2 deletions packages/language-service/src/languageFeatures/hover.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as vscode from 'vscode-languageserver-protocol';
import type { LanguageServiceRuntimeContext } from '../types';
import * as shared from '@volar/shared';
import { languageFeatureWorker } from '../utils/featureWorkers';
import { isInsideRange } from '../utils/common';

export function register(context: LanguageServiceRuntimeContext) {

Expand All @@ -26,7 +26,7 @@ export function register(context: LanguageServiceRuntimeContext) {
},
hovers => ({
contents: hovers.map(getHoverTexts).flat(),
range: hovers.find(hover => hover.range && shared.isInsideRange(hover.range, { start: position, end: position }))?.range ?? hovers[0].range,
range: hovers.find(hover => hover.range && isInsideRange(hover.range, { start: position, end: position }))?.range ?? hovers[0].range,
}),
);
};
Expand Down
3 changes: 2 additions & 1 deletion packages/language-service/src/languageFeatures/inlayHints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as shared from '@volar/shared';
import { transformTextEdit } from '@volar/transforms';
import * as vscode from 'vscode-languageserver-protocol';
import type { LanguageServiceRuntimeContext } from '../types';
import { getOverlapRange } from '../utils/common';
import { languageFeatureWorker } from '../utils/featureWorkers';

export function register(context: LanguageServiceRuntimeContext) {
Expand Down Expand Up @@ -35,7 +36,7 @@ export function register(context: LanguageServiceRuntimeContext) {
let maxEnd: number | undefined;

for (const mapping of sourceMap.mappings) {
const overlapRange = shared.getOverlapRange2(offsetRange.start, offsetRange.end, mapping.sourceRange[0], mapping.sourceRange[1]);
const overlapRange = getOverlapRange(offsetRange.start, offsetRange.end, mapping.sourceRange[0], mapping.sourceRange[1]);
if (overlapRange) {
const start = sourceMap.toGeneratedOffset(overlapRange.start)?.[0];
const end = sourceMap.toGeneratedOffset(overlapRange.end)?.[0];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getWordRange } from '@volar/shared';
import * as vscode from 'vscode-languageserver-protocol';
import type { LanguageServiceRuntimeContext } from '../types';
import { getWordRange } from '../utils/common';
import { languageFeatureWorker } from '../utils/featureWorkers';

// https://github.com/microsoft/vscode/blob/dcf27391b7dd7c1cece483806af75b4f87188e70/extensions/html/language-configuration.json#L35
Expand Down
55 changes: 55 additions & 0 deletions packages/language-service/src/utils/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import type * as vscode from 'vscode-languageserver-protocol';
import type { TextDocument } from 'vscode-languageserver-textdocument';

export function getOverlapRange(
range1Start: number,
range1End: number,
range2Start: number,
range2End: number,
): { start: number, end: number; } | undefined {

const start = Math.max(range1Start, range2Start);
const end = Math.min(range1End, range2End);

if (start > end)
return undefined;

return {
start,
end,
};
}

export function isInsideRange(parent: vscode.Range, child: vscode.Range) {
if (child.start.line < parent.start.line) return false;
if (child.end.line > parent.end.line) return false;
if (child.start.line === parent.start.line && child.start.character < parent.start.character) return false;
if (child.end.line === parent.end.line && child.end.character > parent.end.character) return false;
return true;
}

export function getWordRange(wordPattern: RegExp, position: vscode.Position, document: TextDocument): vscode.Range | undefined {
const lineStart: vscode.Position = {
line: position.line,
character: 0,
};
const lineEnd: vscode.Position = {
line: position.line + 1,
character: 0,
};
const offset = document.offsetAt(position);
const lineStartOffset = document.offsetAt(lineStart);
const lineText = document.getText({ start: lineStart, end: lineEnd });
for (const match of lineText.matchAll(wordPattern)) {
if (match.index === undefined) continue;
const matchStart = match.index + lineStartOffset;
const matchEnd = matchStart + match[0].length;
if (offset >= matchStart && offset <= matchEnd) {
return {
start: document.positionAt(matchStart),
end: document.positionAt(matchEnd),
};
}
}
return undefined;
}
15 changes: 12 additions & 3 deletions packages/pug-language-service/src/baseParse.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Segment, toString } from 'muggle-string';
import * as shared from '@volar/shared';
import { buildMappings } from '@volar/source-map';
import * as pugLex from 'pug-lexer';
import { TextDocument } from 'vscode-languageserver-textdocument';
Expand Down Expand Up @@ -220,12 +219,12 @@ export function baseParse(pugCode: string) {
for (const token of tokens) {
if (token.type === 'newline' || token.type === 'outdent') {
let currentLine = token.loc.start.line - 2;
let prevLine = shared.getLineText(pugTextDocument, currentLine);
let prevLine = getLineText(pugTextDocument, currentLine);
while (prevLine.trim() === '') {
ends.push(pugTextDocument.offsetAt({ line: currentLine + 1, character: 0 }) - 1);
if (currentLine <= 0) break;
currentLine--;
prevLine = shared.getLineText(pugTextDocument, currentLine);
prevLine = getLineText(pugTextDocument, currentLine);
}
}
}
Expand Down Expand Up @@ -370,3 +369,13 @@ export interface BlockCommentNode {
line: number,
column: number,
}

function getLineText(document: TextDocument, line: number) {
const endOffset = document.offsetAt({ line: line + 1, character: 0 });
const end = document.positionAt(endOffset);
const text = document.getText({
start: { line: line, character: 0 },
end: end.line === line ? end : document.positionAt(endOffset - 1),
});
return text;
}
2 changes: 0 additions & 2 deletions packages/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
},
"dependencies": {
"typesafe-path": "^0.2.2",
"vscode-languageserver-protocol": "^3.17.2",
"vscode-languageserver-textdocument": "^1.0.7",
"vscode-uri": "^3.0.6"
}
}
88 changes: 0 additions & 88 deletions packages/shared/src/common.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@

import type * as vscode from 'vscode-languageserver-protocol';
import type { TextDocument } from 'vscode-languageserver-textdocument';

export function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Expand Down Expand Up @@ -37,87 +33,3 @@ export function languageIdToSyntax(languageId: string) {
export function notEmpty<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined;
}

export function isInsideRange(parent: vscode.Range, child: vscode.Range) {
if (child.start.line < parent.start.line) return false;
if (child.end.line > parent.end.line) return false;
if (child.start.line === parent.start.line && child.start.character < parent.start.character) return false;
if (child.end.line === parent.end.line && child.end.character > parent.end.character) return false;
return true;
}

export function getWordRange(wordPattern: RegExp, position: vscode.Position, document: TextDocument): vscode.Range | undefined {
const lineStart: vscode.Position = {
line: position.line,
character: 0,
};
const lineEnd: vscode.Position = {
line: position.line + 1,
character: 0,
};
const offset = document.offsetAt(position);
const lineStartOffset = document.offsetAt(lineStart);
const lineText = document.getText({ start: lineStart, end: lineEnd });
for (const match of lineText.matchAll(wordPattern)) {
if (match.index === undefined) continue;
const matchStart = match.index + lineStartOffset;
const matchEnd = matchStart + match[0].length;
if (offset >= matchStart && offset <= matchEnd) {
return {
start: document.positionAt(matchStart),
end: document.positionAt(matchEnd),
};
}
}
return undefined;
}

export function getOverlapRange(
range1: vscode.Range,
range2: vscode.Range,
): vscode.Range | undefined {

const start: vscode.Position = {
line: Math.max(range1.start.line, range2.start.line),
character: range1.start.line === range2.start.line ? Math.max(range1.start.character, range2.start.character) : range1.start.line > range2.start.line ? range1.start.character : range2.start.character,
};
const end: vscode.Position = {
line: Math.min(range1.end.line, range2.end.line),
character: range1.end.line === range2.end.line ? Math.min(range1.end.character, range2.end.character) : range1.end.line < range2.end.line ? range1.end.character : range2.end.character,
};

if (start.line > end.line || (start.line === end.line && start.character > end.character))
return undefined;

return {
start,
end,
};
}

export function getOverlapRange2(
range1Start: number,
range1End: number,
range2Start: number,
range2End: number,
): { start: number, end: number; } | undefined {

const start = Math.max(range1Start, range2Start);
const end = Math.min(range1End, range2End);

if (start > end)
return undefined;

return {
start,
end,
};
}

export function getLineText(document: TextDocument, line: number) {
const text = document.getText({
start: { line: line, character: 0 },
end: { line: line + 1, character: 0 },
});
return text.slice(0, -1);
}
3 changes: 0 additions & 3 deletions packages/shared/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
export * from './common';
export * from './ts';
export * from './path';
export * from './uriMap';

// fix build
export * as _1 from 'vscode-languageserver-textdocument';
export * as _2 from 'vscode-uri';
3 changes: 1 addition & 2 deletions packages/shared/src/path.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { URI } from 'vscode-uri';
import type { DocumentUri } from 'vscode-languageserver-textdocument';
import * as path from 'typesafe-path';

export function getPathOfUri(uri: DocumentUri) {
export function getPathOfUri(uri: string) {
return URI.parse(uri).fsPath.replace(/\\/g, '/') as path.PosixPath;
}

Expand Down

0 comments on commit ab8cf5c

Please sign in to comment.