Move json sources to /src/

This commit is contained in:
Alex Dima 2021-11-13 19:46:33 +01:00
parent a8df4018f1
commit c41a5ce8aa
No known key found for this signature in database
GPG key ID: 39563C1504FDD0C9
15 changed files with 39 additions and 184 deletions

14
src/json/json.worker.ts Normal file
View file

@ -0,0 +1,14 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as worker from 'monaco-editor-core/esm/vs/editor/editor.worker';
import { JSONWorker } from './jsonWorker';
self.onmessage = () => {
// ignore the first message
worker.initialize((ctx, createData) => {
return new JSONWorker(ctx, createData);
});
};

143
src/json/jsonMode.ts Normal file
View file

@ -0,0 +1,143 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { WorkerManager } from './workerManager';
import type { JSONWorker } from './jsonWorker';
import { LanguageServiceDefaults } from './monaco.contribution';
import * as languageFeatures from './languageFeatures';
import { createTokenizationSupport } from './tokenization';
import { Uri, IDisposable, languages } from '../fillers/monaco-editor-core';
export function setupMode(defaults: LanguageServiceDefaults): IDisposable {
const disposables: IDisposable[] = [];
const providers: IDisposable[] = [];
const client = new WorkerManager(defaults);
disposables.push(client);
const worker: languageFeatures.WorkerAccessor = (...uris: Uri[]): Promise<JSONWorker> => {
return client.getLanguageServiceWorker(...uris);
};
function registerProviders(): void {
const { languageId, modeConfiguration } = defaults;
disposeAll(providers);
if (modeConfiguration.documentFormattingEdits) {
providers.push(
languages.registerDocumentFormattingEditProvider(
languageId,
new languageFeatures.DocumentFormattingEditProvider(worker)
)
);
}
if (modeConfiguration.documentRangeFormattingEdits) {
providers.push(
languages.registerDocumentRangeFormattingEditProvider(
languageId,
new languageFeatures.DocumentRangeFormattingEditProvider(worker)
)
);
}
if (modeConfiguration.completionItems) {
providers.push(
languages.registerCompletionItemProvider(
languageId,
new languageFeatures.CompletionAdapter(worker)
)
);
}
if (modeConfiguration.hovers) {
providers.push(
languages.registerHoverProvider(languageId, new languageFeatures.HoverAdapter(worker))
);
}
if (modeConfiguration.documentSymbols) {
providers.push(
languages.registerDocumentSymbolProvider(
languageId,
new languageFeatures.DocumentSymbolAdapter(worker)
)
);
}
if (modeConfiguration.tokens) {
providers.push(languages.setTokensProvider(languageId, createTokenizationSupport(true)));
}
if (modeConfiguration.colors) {
providers.push(
languages.registerColorProvider(
languageId,
new languageFeatures.DocumentColorAdapter(worker)
)
);
}
if (modeConfiguration.foldingRanges) {
providers.push(
languages.registerFoldingRangeProvider(
languageId,
new languageFeatures.FoldingRangeAdapter(worker)
)
);
}
if (modeConfiguration.diagnostics) {
providers.push(new languageFeatures.DiagnosticsAdapter(languageId, worker, defaults));
}
if (modeConfiguration.selectionRanges) {
providers.push(
languages.registerSelectionRangeProvider(
languageId,
new languageFeatures.SelectionRangeAdapter(worker)
)
);
}
}
registerProviders();
disposables.push(languages.setLanguageConfiguration(defaults.languageId, richEditConfiguration));
let modeConfiguration = defaults.modeConfiguration;
defaults.onDidChange((newDefaults) => {
if (newDefaults.modeConfiguration !== modeConfiguration) {
modeConfiguration = newDefaults.modeConfiguration;
registerProviders();
}
});
disposables.push(asDisposable(providers));
return asDisposable(disposables);
}
function asDisposable(disposables: IDisposable[]): IDisposable {
return { dispose: () => disposeAll(disposables) };
}
function disposeAll(disposables: IDisposable[]) {
while (disposables.length) {
disposables.pop().dispose();
}
}
const richEditConfiguration: languages.LanguageConfiguration = {
wordPattern: /(-?\d*\.\d\w*)|([^\[\{\]\}\:\"\,\s]+)/g,
comments: {
lineComment: '//',
blockComment: ['/*', '*/']
},
brackets: [
['{', '}'],
['[', ']']
],
autoClosingPairs: [
{ open: '{', close: '}', notIn: ['string'] },
{ open: '[', close: ']', notIn: ['string'] },
{ open: '"', close: '"', notIn: ['string'] }
]
};

192
src/json/jsonWorker.ts Normal file
View file

@ -0,0 +1,192 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as jsonService from 'vscode-json-languageservice';
import type { worker } from '../fillers/monaco-editor-core';
import { URI } from 'vscode-uri';
import { DiagnosticsOptions } from './monaco.contribution';
let defaultSchemaRequestService;
if (typeof fetch !== 'undefined') {
defaultSchemaRequestService = function (url) {
return fetch(url).then((response) => response.text());
};
}
export class JSONWorker {
private _ctx: worker.IWorkerContext;
private _languageService: jsonService.LanguageService;
private _languageSettings: DiagnosticsOptions;
private _languageId: string;
constructor(ctx: worker.IWorkerContext, createData: ICreateData) {
this._ctx = ctx;
this._languageSettings = createData.languageSettings;
this._languageId = createData.languageId;
this._languageService = jsonService.getLanguageService({
workspaceContext: {
resolveRelativePath: (relativePath: string, resource: string) => {
const base = resource.substr(0, resource.lastIndexOf('/') + 1);
return resolvePath(base, relativePath);
}
},
schemaRequestService: createData.enableSchemaRequest && defaultSchemaRequestService
});
this._languageService.configure(this._languageSettings);
}
async doValidation(uri: string): Promise<jsonService.Diagnostic[]> {
let document = this._getTextDocument(uri);
if (document) {
let jsonDocument = this._languageService.parseJSONDocument(document);
return this._languageService.doValidation(document, jsonDocument, this._languageSettings);
}
return Promise.resolve([]);
}
async doComplete(
uri: string,
position: jsonService.Position
): Promise<jsonService.CompletionList> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
return this._languageService.doComplete(document, position, jsonDocument);
}
async doResolve(item: jsonService.CompletionItem): Promise<jsonService.CompletionItem> {
return this._languageService.doResolve(item);
}
async doHover(uri: string, position: jsonService.Position): Promise<jsonService.Hover> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
return this._languageService.doHover(document, position, jsonDocument);
}
async format(
uri: string,
range: jsonService.Range,
options: jsonService.FormattingOptions
): Promise<jsonService.TextEdit[]> {
let document = this._getTextDocument(uri);
let textEdits = this._languageService.format(document, range, options);
return Promise.resolve(textEdits);
}
async resetSchema(uri: string): Promise<boolean> {
return Promise.resolve(this._languageService.resetSchema(uri));
}
async findDocumentSymbols(uri: string): Promise<jsonService.SymbolInformation[]> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
let symbols = this._languageService.findDocumentSymbols(document, jsonDocument);
return Promise.resolve(symbols);
}
async findDocumentColors(uri: string): Promise<jsonService.ColorInformation[]> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
let colorSymbols = this._languageService.findDocumentColors(document, jsonDocument);
return Promise.resolve(colorSymbols);
}
async getColorPresentations(
uri: string,
color: jsonService.Color,
range: jsonService.Range
): Promise<jsonService.ColorPresentation[]> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
let colorPresentations = this._languageService.getColorPresentations(
document,
jsonDocument,
color,
range
);
return Promise.resolve(colorPresentations);
}
async getFoldingRanges(
uri: string,
context?: { rangeLimit?: number }
): Promise<jsonService.FoldingRange[]> {
let document = this._getTextDocument(uri);
let ranges = this._languageService.getFoldingRanges(document, context);
return Promise.resolve(ranges);
}
async getSelectionRanges(
uri: string,
positions: jsonService.Position[]
): Promise<jsonService.SelectionRange[]> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
let ranges = this._languageService.getSelectionRanges(document, positions, jsonDocument);
return Promise.resolve(ranges);
}
private _getTextDocument(uri: string): jsonService.TextDocument {
let models = this._ctx.getMirrorModels();
for (let model of models) {
if (model.uri.toString() === uri) {
return jsonService.TextDocument.create(
uri,
this._languageId,
model.version,
model.getValue()
);
}
}
return null;
}
}
// URI path utilities, will (hopefully) move to vscode-uri
const Slash = '/'.charCodeAt(0);
const Dot = '.'.charCodeAt(0);
function isAbsolutePath(path: string) {
return path.charCodeAt(0) === Slash;
}
function resolvePath(uriString: string, path: string): string {
if (isAbsolutePath(path)) {
const uri = URI.parse(uriString);
const parts = path.split('/');
return uri.with({ path: normalizePath(parts) }).toString();
}
return joinPath(uriString, path);
}
function normalizePath(parts: string[]): string {
const newParts: string[] = [];
for (const part of parts) {
if (part.length === 0 || (part.length === 1 && part.charCodeAt(0) === Dot)) {
// ignore
} else if (part.length === 2 && part.charCodeAt(0) === Dot && part.charCodeAt(1) === Dot) {
newParts.pop();
} else {
newParts.push(part);
}
}
if (parts.length > 1 && parts[parts.length - 1].length === 0) {
newParts.push('');
}
let res = newParts.join('/');
if (parts[0].length === 0) {
res = '/' + res;
}
return res;
}
function joinPath(uriString: string, ...paths: string[]): string {
const uri = URI.parse(uriString);
const parts = uri.path.split('/');
for (let path of paths) {
parts.push(...path.split('/'));
}
return uri.with({ path: normalizePath(parts) }).toString();
}
export interface ICreateData {
languageId: string;
languageSettings: DiagnosticsOptions;
enableSchemaRequest: boolean;
}
export function create(ctx: worker.IWorkerContext, createData: ICreateData): JSONWorker {
return new JSONWorker(ctx, createData);
}

View file

@ -0,0 +1,716 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { LanguageServiceDefaults } from './monaco.contribution';
import type { JSONWorker } from './jsonWorker';
import {
Uri,
Position,
Range,
IRange,
CancellationToken,
IDisposable,
editor,
languages,
MarkerSeverity,
IMarkdownString
} from '../fillers/monaco-editor-core';
import * as lsTypes from 'vscode-languageserver-types';
export interface WorkerAccessor {
(...more: Uri[]): Promise<JSONWorker>;
}
// --- diagnostics --- ---
export class DiagnosticsAdapter {
private _disposables: IDisposable[] = [];
private _listener: { [uri: string]: IDisposable } = Object.create(null);
constructor(
private _languageId: string,
private _worker: WorkerAccessor,
defaults: LanguageServiceDefaults
) {
const onModelAdd = (model: editor.IModel): void => {
let modeId = model.getLanguageId();
if (modeId !== this._languageId) {
return;
}
let handle: number;
this._listener[model.uri.toString()] = model.onDidChangeContent(() => {
clearTimeout(handle);
handle = window.setTimeout(() => this._doValidate(model.uri, modeId), 500);
});
this._doValidate(model.uri, modeId);
};
const onModelRemoved = (model: editor.IModel): void => {
editor.setModelMarkers(model, this._languageId, []);
let uriStr = model.uri.toString();
let listener = this._listener[uriStr];
if (listener) {
listener.dispose();
delete this._listener[uriStr];
}
};
this._disposables.push(editor.onDidCreateModel(onModelAdd));
this._disposables.push(
editor.onWillDisposeModel((model) => {
onModelRemoved(model);
this._resetSchema(model.uri);
})
);
this._disposables.push(
editor.onDidChangeModelLanguage((event) => {
onModelRemoved(event.model);
onModelAdd(event.model);
this._resetSchema(event.model.uri);
})
);
this._disposables.push(
defaults.onDidChange((_) => {
editor.getModels().forEach((model) => {
if (model.getLanguageId() === this._languageId) {
onModelRemoved(model);
onModelAdd(model);
}
});
})
);
this._disposables.push({
dispose: () => {
editor.getModels().forEach(onModelRemoved);
for (let key in this._listener) {
this._listener[key].dispose();
}
}
});
editor.getModels().forEach(onModelAdd);
}
public dispose(): void {
this._disposables.forEach((d) => d && d.dispose());
this._disposables = [];
}
private _resetSchema(resource: Uri): void {
this._worker().then((worker) => {
worker.resetSchema(resource.toString());
});
}
private _doValidate(resource: Uri, languageId: string): void {
this._worker(resource)
.then((worker) => {
return worker.doValidation(resource.toString()).then((diagnostics) => {
const markers = diagnostics.map((d) => toDiagnostics(resource, d));
let model = editor.getModel(resource);
if (model && model.getLanguageId() === languageId) {
editor.setModelMarkers(model, languageId, markers);
}
});
})
.then(undefined, (err) => {
console.error(err);
});
}
}
function toSeverity(lsSeverity: number): MarkerSeverity {
switch (lsSeverity) {
case lsTypes.DiagnosticSeverity.Error:
return MarkerSeverity.Error;
case lsTypes.DiagnosticSeverity.Warning:
return MarkerSeverity.Warning;
case lsTypes.DiagnosticSeverity.Information:
return MarkerSeverity.Info;
case lsTypes.DiagnosticSeverity.Hint:
return MarkerSeverity.Hint;
default:
return MarkerSeverity.Info;
}
}
function toDiagnostics(resource: Uri, diag: lsTypes.Diagnostic): editor.IMarkerData {
let code = typeof diag.code === 'number' ? String(diag.code) : <string>diag.code;
return {
severity: toSeverity(diag.severity),
startLineNumber: diag.range.start.line + 1,
startColumn: diag.range.start.character + 1,
endLineNumber: diag.range.end.line + 1,
endColumn: diag.range.end.character + 1,
message: diag.message,
code: code,
source: diag.source
};
}
// --- completion ------
function fromPosition(position: Position): lsTypes.Position {
if (!position) {
return void 0;
}
return { character: position.column - 1, line: position.lineNumber - 1 };
}
function fromRange(range: IRange): lsTypes.Range {
if (!range) {
return void 0;
}
return {
start: {
line: range.startLineNumber - 1,
character: range.startColumn - 1
},
end: { line: range.endLineNumber - 1, character: range.endColumn - 1 }
};
}
function toRange(range: lsTypes.Range): Range {
if (!range) {
return void 0;
}
return new Range(
range.start.line + 1,
range.start.character + 1,
range.end.line + 1,
range.end.character + 1
);
}
interface InsertReplaceEdit {
/**
* The string to be inserted.
*/
newText: string;
/**
* The range if the insert is requested
*/
insert: lsTypes.Range;
/**
* The range if the replace is requested.
*/
replace: lsTypes.Range;
}
function isInsertReplaceEdit(
edit: lsTypes.TextEdit | InsertReplaceEdit
): edit is InsertReplaceEdit {
return (
typeof (<InsertReplaceEdit>edit).insert !== 'undefined' &&
typeof (<InsertReplaceEdit>edit).replace !== 'undefined'
);
}
function toCompletionItemKind(kind: number): languages.CompletionItemKind {
let mItemKind = languages.CompletionItemKind;
switch (kind) {
case lsTypes.CompletionItemKind.Text:
return mItemKind.Text;
case lsTypes.CompletionItemKind.Method:
return mItemKind.Method;
case lsTypes.CompletionItemKind.Function:
return mItemKind.Function;
case lsTypes.CompletionItemKind.Constructor:
return mItemKind.Constructor;
case lsTypes.CompletionItemKind.Field:
return mItemKind.Field;
case lsTypes.CompletionItemKind.Variable:
return mItemKind.Variable;
case lsTypes.CompletionItemKind.Class:
return mItemKind.Class;
case lsTypes.CompletionItemKind.Interface:
return mItemKind.Interface;
case lsTypes.CompletionItemKind.Module:
return mItemKind.Module;
case lsTypes.CompletionItemKind.Property:
return mItemKind.Property;
case lsTypes.CompletionItemKind.Unit:
return mItemKind.Unit;
case lsTypes.CompletionItemKind.Value:
return mItemKind.Value;
case lsTypes.CompletionItemKind.Enum:
return mItemKind.Enum;
case lsTypes.CompletionItemKind.Keyword:
return mItemKind.Keyword;
case lsTypes.CompletionItemKind.Snippet:
return mItemKind.Snippet;
case lsTypes.CompletionItemKind.Color:
return mItemKind.Color;
case lsTypes.CompletionItemKind.File:
return mItemKind.File;
case lsTypes.CompletionItemKind.Reference:
return mItemKind.Reference;
}
return mItemKind.Property;
}
function fromCompletionItemKind(kind: languages.CompletionItemKind): lsTypes.CompletionItemKind {
let mItemKind = languages.CompletionItemKind;
switch (kind) {
case mItemKind.Text:
return lsTypes.CompletionItemKind.Text;
case mItemKind.Method:
return lsTypes.CompletionItemKind.Method;
case mItemKind.Function:
return lsTypes.CompletionItemKind.Function;
case mItemKind.Constructor:
return lsTypes.CompletionItemKind.Constructor;
case mItemKind.Field:
return lsTypes.CompletionItemKind.Field;
case mItemKind.Variable:
return lsTypes.CompletionItemKind.Variable;
case mItemKind.Class:
return lsTypes.CompletionItemKind.Class;
case mItemKind.Interface:
return lsTypes.CompletionItemKind.Interface;
case mItemKind.Module:
return lsTypes.CompletionItemKind.Module;
case mItemKind.Property:
return lsTypes.CompletionItemKind.Property;
case mItemKind.Unit:
return lsTypes.CompletionItemKind.Unit;
case mItemKind.Value:
return lsTypes.CompletionItemKind.Value;
case mItemKind.Enum:
return lsTypes.CompletionItemKind.Enum;
case mItemKind.Keyword:
return lsTypes.CompletionItemKind.Keyword;
case mItemKind.Snippet:
return lsTypes.CompletionItemKind.Snippet;
case mItemKind.Color:
return lsTypes.CompletionItemKind.Color;
case mItemKind.File:
return lsTypes.CompletionItemKind.File;
case mItemKind.Reference:
return lsTypes.CompletionItemKind.Reference;
}
return lsTypes.CompletionItemKind.Property;
}
function toTextEdit(textEdit: lsTypes.TextEdit): editor.ISingleEditOperation {
if (!textEdit) {
return void 0;
}
return {
range: toRange(textEdit.range),
text: textEdit.newText
};
}
function toCommand(c: lsTypes.Command | undefined): languages.Command {
return c && c.command === 'editor.action.triggerSuggest'
? { id: c.command, title: c.title, arguments: c.arguments }
: undefined;
}
export class CompletionAdapter implements languages.CompletionItemProvider {
constructor(private _worker: WorkerAccessor) {}
public get triggerCharacters(): string[] {
return [' ', ':', '"'];
}
provideCompletionItems(
model: editor.IReadOnlyModel,
position: Position,
context: languages.CompletionContext,
token: CancellationToken
): Promise<languages.CompletionList> {
const resource = model.uri;
return this._worker(resource)
.then((worker) => {
return worker.doComplete(resource.toString(), fromPosition(position));
})
.then((info) => {
if (!info) {
return;
}
const wordInfo = model.getWordUntilPosition(position);
const wordRange = new Range(
position.lineNumber,
wordInfo.startColumn,
position.lineNumber,
wordInfo.endColumn
);
let items: languages.CompletionItem[] = info.items.map((entry) => {
let item: languages.CompletionItem = {
label: entry.label,
insertText: entry.insertText || entry.label,
sortText: entry.sortText,
filterText: entry.filterText,
documentation: entry.documentation,
detail: entry.detail,
command: toCommand(entry.command),
range: wordRange,
kind: toCompletionItemKind(entry.kind)
};
if (entry.textEdit) {
if (isInsertReplaceEdit(entry.textEdit)) {
item.range = {
insert: toRange(entry.textEdit.insert),
replace: toRange(entry.textEdit.replace)
};
} else {
item.range = toRange(entry.textEdit.range);
}
item.insertText = entry.textEdit.newText;
}
if (entry.additionalTextEdits) {
item.additionalTextEdits = entry.additionalTextEdits.map(toTextEdit);
}
if (entry.insertTextFormat === lsTypes.InsertTextFormat.Snippet) {
item.insertTextRules = languages.CompletionItemInsertTextRule.InsertAsSnippet;
}
return item;
});
return {
isIncomplete: info.isIncomplete,
suggestions: items
};
});
}
}
function isMarkupContent(thing: any): thing is lsTypes.MarkupContent {
return (
thing && typeof thing === 'object' && typeof (<lsTypes.MarkupContent>thing).kind === 'string'
);
}
function toMarkdownString(entry: lsTypes.MarkupContent | lsTypes.MarkedString): IMarkdownString {
if (typeof entry === 'string') {
return {
value: entry
};
}
if (isMarkupContent(entry)) {
if (entry.kind === 'plaintext') {
return {
value: entry.value.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&')
};
}
return {
value: entry.value
};
}
return { value: '```' + entry.language + '\n' + entry.value + '\n```\n' };
}
function toMarkedStringArray(
contents: lsTypes.MarkupContent | lsTypes.MarkedString | lsTypes.MarkedString[]
): IMarkdownString[] {
if (!contents) {
return void 0;
}
if (Array.isArray(contents)) {
return contents.map(toMarkdownString);
}
return [toMarkdownString(contents)];
}
// --- hover ------
export class HoverAdapter implements languages.HoverProvider {
constructor(private _worker: WorkerAccessor) {}
provideHover(
model: editor.IReadOnlyModel,
position: Position,
token: CancellationToken
): Promise<languages.Hover> {
let resource = model.uri;
return this._worker(resource)
.then((worker) => {
return worker.doHover(resource.toString(), fromPosition(position));
})
.then((info) => {
if (!info) {
return;
}
return <languages.Hover>{
range: toRange(info.range),
contents: toMarkedStringArray(info.contents)
};
});
}
}
// --- definition ------
function toLocation(location: lsTypes.Location): languages.Location {
return {
uri: Uri.parse(location.uri),
range: toRange(location.range)
};
}
// --- document symbols ------
function toSymbolKind(kind: lsTypes.SymbolKind): languages.SymbolKind {
let mKind = languages.SymbolKind;
switch (kind) {
case lsTypes.SymbolKind.File:
return mKind.Array;
case lsTypes.SymbolKind.Module:
return mKind.Module;
case lsTypes.SymbolKind.Namespace:
return mKind.Namespace;
case lsTypes.SymbolKind.Package:
return mKind.Package;
case lsTypes.SymbolKind.Class:
return mKind.Class;
case lsTypes.SymbolKind.Method:
return mKind.Method;
case lsTypes.SymbolKind.Property:
return mKind.Property;
case lsTypes.SymbolKind.Field:
return mKind.Field;
case lsTypes.SymbolKind.Constructor:
return mKind.Constructor;
case lsTypes.SymbolKind.Enum:
return mKind.Enum;
case lsTypes.SymbolKind.Interface:
return mKind.Interface;
case lsTypes.SymbolKind.Function:
return mKind.Function;
case lsTypes.SymbolKind.Variable:
return mKind.Variable;
case lsTypes.SymbolKind.Constant:
return mKind.Constant;
case lsTypes.SymbolKind.String:
return mKind.String;
case lsTypes.SymbolKind.Number:
return mKind.Number;
case lsTypes.SymbolKind.Boolean:
return mKind.Boolean;
case lsTypes.SymbolKind.Array:
return mKind.Array;
}
return mKind.Function;
}
export class DocumentSymbolAdapter implements languages.DocumentSymbolProvider {
constructor(private _worker: WorkerAccessor) {}
public provideDocumentSymbols(
model: editor.IReadOnlyModel,
token: CancellationToken
): Promise<languages.DocumentSymbol[]> {
const resource = model.uri;
return this._worker(resource)
.then((worker) => worker.findDocumentSymbols(resource.toString()))
.then((items) => {
if (!items) {
return;
}
return items.map((item) => ({
name: item.name,
detail: '',
containerName: item.containerName,
kind: toSymbolKind(item.kind),
range: toRange(item.location.range),
selectionRange: toRange(item.location.range),
tags: []
}));
});
}
}
function fromFormattingOptions(options: languages.FormattingOptions): lsTypes.FormattingOptions {
return {
tabSize: options.tabSize,
insertSpaces: options.insertSpaces
};
}
export class DocumentFormattingEditProvider implements languages.DocumentFormattingEditProvider {
constructor(private _worker: WorkerAccessor) {}
public provideDocumentFormattingEdits(
model: editor.IReadOnlyModel,
options: languages.FormattingOptions,
token: CancellationToken
): Promise<editor.ISingleEditOperation[]> {
const resource = model.uri;
return this._worker(resource).then((worker) => {
return worker
.format(resource.toString(), null, fromFormattingOptions(options))
.then((edits) => {
if (!edits || edits.length === 0) {
return;
}
return edits.map(toTextEdit);
});
});
}
}
export class DocumentRangeFormattingEditProvider
implements languages.DocumentRangeFormattingEditProvider
{
constructor(private _worker: WorkerAccessor) {}
public provideDocumentRangeFormattingEdits(
model: editor.IReadOnlyModel,
range: Range,
options: languages.FormattingOptions,
token: CancellationToken
): Promise<editor.ISingleEditOperation[]> {
const resource = model.uri;
return this._worker(resource).then((worker) => {
return worker
.format(resource.toString(), fromRange(range), fromFormattingOptions(options))
.then((edits) => {
if (!edits || edits.length === 0) {
return;
}
return edits.map(toTextEdit);
});
});
}
}
export class DocumentColorAdapter implements languages.DocumentColorProvider {
constructor(private _worker: WorkerAccessor) {}
public provideDocumentColors(
model: editor.IReadOnlyModel,
token: CancellationToken
): Promise<languages.IColorInformation[]> {
const resource = model.uri;
return this._worker(resource)
.then((worker) => worker.findDocumentColors(resource.toString()))
.then((infos) => {
if (!infos) {
return;
}
return infos.map((item) => ({
color: item.color,
range: toRange(item.range)
}));
});
}
public provideColorPresentations(
model: editor.IReadOnlyModel,
info: languages.IColorInformation,
token: CancellationToken
): Promise<languages.IColorPresentation[]> {
const resource = model.uri;
return this._worker(resource)
.then((worker) =>
worker.getColorPresentations(resource.toString(), info.color, fromRange(info.range))
)
.then((presentations) => {
if (!presentations) {
return;
}
return presentations.map((presentation) => {
let item: languages.IColorPresentation = {
label: presentation.label
};
if (presentation.textEdit) {
item.textEdit = toTextEdit(presentation.textEdit);
}
if (presentation.additionalTextEdits) {
item.additionalTextEdits = presentation.additionalTextEdits.map(toTextEdit);
}
return item;
});
});
}
}
export class FoldingRangeAdapter implements languages.FoldingRangeProvider {
constructor(private _worker: WorkerAccessor) {}
public provideFoldingRanges(
model: editor.IReadOnlyModel,
context: languages.FoldingContext,
token: CancellationToken
): Promise<languages.FoldingRange[]> {
const resource = model.uri;
return this._worker(resource)
.then((worker) => worker.getFoldingRanges(resource.toString(), context))
.then((ranges) => {
if (!ranges) {
return;
}
return ranges.map((range) => {
let result: languages.FoldingRange = {
start: range.startLine + 1,
end: range.endLine + 1
};
if (typeof range.kind !== 'undefined') {
result.kind = toFoldingRangeKind(<lsTypes.FoldingRangeKind>range.kind);
}
return result;
});
});
}
}
function toFoldingRangeKind(kind: lsTypes.FoldingRangeKind): languages.FoldingRangeKind {
switch (kind) {
case lsTypes.FoldingRangeKind.Comment:
return languages.FoldingRangeKind.Comment;
case lsTypes.FoldingRangeKind.Imports:
return languages.FoldingRangeKind.Imports;
case lsTypes.FoldingRangeKind.Region:
return languages.FoldingRangeKind.Region;
}
return void 0;
}
export class SelectionRangeAdapter implements languages.SelectionRangeProvider {
constructor(private _worker: WorkerAccessor) {}
public provideSelectionRanges(
model: editor.IReadOnlyModel,
positions: Position[],
token: CancellationToken
): Promise<languages.SelectionRange[][]> {
const resource = model.uri;
return this._worker(resource)
.then((worker) => worker.getSelectionRanges(resource.toString(), positions.map(fromPosition)))
.then((selectionRanges) => {
if (!selectionRanges) {
return;
}
return selectionRanges.map((selectionRange) => {
const result: languages.SelectionRange[] = [];
while (selectionRange) {
result.push({ range: toRange(selectionRange.range) });
selectionRange = selectionRange.parent;
}
return result;
});
});
}
}

View file

@ -0,0 +1,227 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as mode from './jsonMode';
import { Emitter, IEvent, languages } from '../fillers/monaco-editor-core';
// --- JSON configuration and defaults ---------
export interface DiagnosticsOptions {
/**
* If set, the validator will be enabled and perform syntax and schema based validation,
* unless `DiagnosticsOptions.schemaValidation` is set to `ignore`.
*/
readonly validate?: boolean;
/**
* If set, comments are tolerated. If set to false, syntax errors will be emitted for comments.
* `DiagnosticsOptions.allowComments` will override this setting.
*/
readonly allowComments?: boolean;
/**
* A list of known schemas and/or associations of schemas to file names.
*/
readonly schemas?: {
/**
* The URI of the schema, which is also the identifier of the schema.
*/
readonly uri: string;
/**
* A list of glob patterns that describe for which file URIs the JSON schema will be used.
* '*' and '**' wildcards are supported. Exclusion patterns start with '!'.
* For example '*.schema.json', 'package.json', '!foo*.schema.json', 'foo/**\/BADRESP.json'.
* A match succeeds when there is at least one pattern matching and last matching pattern does not start with '!'.
*/
readonly fileMatch?: string[];
/**
* The schema for the given URI.
*/
readonly schema?: any;
}[];
/**
* If set, the schema service would load schema content on-demand with 'fetch' if available
*/
readonly enableSchemaRequest?: boolean;
/**
* The severity of problems from schema validation. If set to 'ignore', schema validation will be skipped. If not set, 'warning' is used.
*/
readonly schemaValidation?: SeverityLevel;
/**
* The severity of problems that occurred when resolving and loading schemas. If set to 'ignore', schema resolving problems are not reported. If not set, 'warning' is used.
*/
readonly schemaRequest?: SeverityLevel;
/**
* The severity of reported trailing commas. If not set, trailing commas will be reported as errors.
*/
readonly trailingCommas?: SeverityLevel;
/**
* The severity of reported comments. If not set, 'DiagnosticsOptions.allowComments' defines whether comments are ignored or reported as errors.
*/
readonly comments?: SeverityLevel;
}
export declare type SeverityLevel = 'error' | 'warning' | 'ignore';
export interface ModeConfiguration {
/**
* Defines whether the built-in documentFormattingEdit provider is enabled.
*/
readonly documentFormattingEdits?: boolean;
/**
* Defines whether the built-in documentRangeFormattingEdit provider is enabled.
*/
readonly documentRangeFormattingEdits?: boolean;
/**
* Defines whether the built-in completionItemProvider is enabled.
*/
readonly completionItems?: boolean;
/**
* Defines whether the built-in hoverProvider is enabled.
*/
readonly hovers?: boolean;
/**
* Defines whether the built-in documentSymbolProvider is enabled.
*/
readonly documentSymbols?: boolean;
/**
* Defines whether the built-in tokens provider is enabled.
*/
readonly tokens?: boolean;
/**
* Defines whether the built-in color provider is enabled.
*/
readonly colors?: boolean;
/**
* Defines whether the built-in foldingRange provider is enabled.
*/
readonly foldingRanges?: boolean;
/**
* Defines whether the built-in diagnostic provider is enabled.
*/
readonly diagnostics?: boolean;
/**
* Defines whether the built-in selection range provider is enabled.
*/
readonly selectionRanges?: boolean;
}
export interface LanguageServiceDefaults {
readonly languageId: string;
readonly onDidChange: IEvent<LanguageServiceDefaults>;
readonly diagnosticsOptions: DiagnosticsOptions;
readonly modeConfiguration: ModeConfiguration;
setDiagnosticsOptions(options: DiagnosticsOptions): void;
setModeConfiguration(modeConfiguration: ModeConfiguration): void;
}
class LanguageServiceDefaultsImpl implements LanguageServiceDefaults {
private _onDidChange = new Emitter<LanguageServiceDefaults>();
private _diagnosticsOptions: DiagnosticsOptions;
private _modeConfiguration: ModeConfiguration;
private _languageId: string;
constructor(
languageId: string,
diagnosticsOptions: DiagnosticsOptions,
modeConfiguration: ModeConfiguration
) {
this._languageId = languageId;
this.setDiagnosticsOptions(diagnosticsOptions);
this.setModeConfiguration(modeConfiguration);
}
get onDidChange(): IEvent<LanguageServiceDefaults> {
return this._onDidChange.event;
}
get languageId(): string {
return this._languageId;
}
get modeConfiguration(): ModeConfiguration {
return this._modeConfiguration;
}
get diagnosticsOptions(): DiagnosticsOptions {
return this._diagnosticsOptions;
}
setDiagnosticsOptions(options: DiagnosticsOptions): void {
this._diagnosticsOptions = options || Object.create(null);
this._onDidChange.fire(this);
}
setModeConfiguration(modeConfiguration: ModeConfiguration): void {
this._modeConfiguration = modeConfiguration || Object.create(null);
this._onDidChange.fire(this);
}
}
const diagnosticDefault: Required<DiagnosticsOptions> = {
validate: true,
allowComments: true,
schemas: [],
enableSchemaRequest: false,
schemaRequest: 'warning',
schemaValidation: 'warning',
comments: 'error',
trailingCommas: 'error'
};
const modeConfigurationDefault: Required<ModeConfiguration> = {
documentFormattingEdits: true,
documentRangeFormattingEdits: true,
completionItems: true,
hovers: true,
documentSymbols: true,
tokens: true,
colors: true,
foldingRanges: true,
diagnostics: true,
selectionRanges: true
};
export const jsonDefaults: LanguageServiceDefaults = new LanguageServiceDefaultsImpl(
'json',
diagnosticDefault,
modeConfigurationDefault
);
// export to the global based API
(<any>languages).json = { jsonDefaults };
// --- Registration to monaco editor ---
declare var AMD: any;
declare var require: any;
function getMode(): Promise<typeof mode> {
if (AMD) {
return new Promise((resolve, reject) => {
require(['vs/language/json/jsonMode'], resolve, reject);
});
} else {
return import('./jsonMode');
}
}
languages.register({
id: 'json',
extensions: ['.json', '.bowerrc', '.jshintrc', '.jscsrc', '.eslintrc', '.babelrc', '.har'],
aliases: ['JSON', 'json'],
mimetypes: ['application/json']
});
languages.onLanguage('json', () => {
getMode().then((mode) => mode.setupMode(jsonDefaults));
});

275
src/json/tokenization.ts Normal file
View file

@ -0,0 +1,275 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as json from 'jsonc-parser';
import { languages } from '../fillers/monaco-editor-core';
export function createTokenizationSupport(supportComments: boolean): languages.TokensProvider {
return {
getInitialState: () => new JSONState(null, null, false, null),
tokenize: (line, state, offsetDelta?, stopAtOffset?) =>
tokenize(supportComments, line, <JSONState>state, offsetDelta, stopAtOffset)
};
}
export const TOKEN_DELIM_OBJECT = 'delimiter.bracket.json';
export const TOKEN_DELIM_ARRAY = 'delimiter.array.json';
export const TOKEN_DELIM_COLON = 'delimiter.colon.json';
export const TOKEN_DELIM_COMMA = 'delimiter.comma.json';
export const TOKEN_VALUE_BOOLEAN = 'keyword.json';
export const TOKEN_VALUE_NULL = 'keyword.json';
export const TOKEN_VALUE_STRING = 'string.value.json';
export const TOKEN_VALUE_NUMBER = 'number.json';
export const TOKEN_PROPERTY_NAME = 'string.key.json';
export const TOKEN_COMMENT_BLOCK = 'comment.block.json';
export const TOKEN_COMMENT_LINE = 'comment.line.json';
const enum JSONParent {
Object = 0,
Array = 1
}
class ParentsStack {
constructor(public readonly parent: ParentsStack | null, public readonly type: JSONParent) {}
public static pop(parents: ParentsStack | null): ParentsStack | null {
if (parents) {
return parents.parent;
}
return null;
}
public static push(parents: ParentsStack | null, type: JSONParent): ParentsStack {
return new ParentsStack(parents, type);
}
public static equals(a: ParentsStack | null, b: ParentsStack | null): boolean {
if (!a && !b) {
return true;
}
if (!a || !b) {
return false;
}
while (a && b) {
if (a === b) {
return true;
}
if (a.type !== b.type) {
return false;
}
a = a.parent;
b = b.parent;
}
return true;
}
}
class JSONState implements languages.IState {
private _state: languages.IState;
public scanError: ScanError;
public lastWasColon: boolean;
public parents: ParentsStack | null;
constructor(
state: languages.IState,
scanError: ScanError,
lastWasColon: boolean,
parents: ParentsStack | null
) {
this._state = state;
this.scanError = scanError;
this.lastWasColon = lastWasColon;
this.parents = parents;
}
public clone(): JSONState {
return new JSONState(this._state, this.scanError, this.lastWasColon, this.parents);
}
public equals(other: languages.IState): boolean {
if (other === this) {
return true;
}
if (!other || !(other instanceof JSONState)) {
return false;
}
return (
this.scanError === other.scanError &&
this.lastWasColon === other.lastWasColon &&
ParentsStack.equals(this.parents, other.parents)
);
}
public getStateData(): languages.IState {
return this._state;
}
public setStateData(state: languages.IState): void {
this._state = state;
}
}
const enum ScanError {
None = 0,
UnexpectedEndOfComment = 1,
UnexpectedEndOfString = 2,
UnexpectedEndOfNumber = 3,
InvalidUnicode = 4,
InvalidEscapeCharacter = 5,
InvalidCharacter = 6
}
const enum SyntaxKind {
OpenBraceToken = 1,
CloseBraceToken = 2,
OpenBracketToken = 3,
CloseBracketToken = 4,
CommaToken = 5,
ColonToken = 6,
NullKeyword = 7,
TrueKeyword = 8,
FalseKeyword = 9,
StringLiteral = 10,
NumericLiteral = 11,
LineCommentTrivia = 12,
BlockCommentTrivia = 13,
LineBreakTrivia = 14,
Trivia = 15,
Unknown = 16,
EOF = 17
}
function tokenize(
comments: boolean,
line: string,
state: JSONState,
offsetDelta: number = 0,
stopAtOffset?: number
): languages.ILineTokens {
// handle multiline strings and block comments
let numberOfInsertedCharacters = 0;
let adjustOffset = false;
switch (state.scanError) {
case ScanError.UnexpectedEndOfString:
line = '"' + line;
numberOfInsertedCharacters = 1;
break;
case ScanError.UnexpectedEndOfComment:
line = '/*' + line;
numberOfInsertedCharacters = 2;
break;
}
const scanner = json.createScanner(line);
let lastWasColon = state.lastWasColon;
let parents = state.parents;
const ret: languages.ILineTokens = {
tokens: <languages.IToken[]>[],
endState: state.clone()
};
while (true) {
let offset = offsetDelta + scanner.getPosition();
let type = '';
const kind = <SyntaxKind>(<any>scanner.scan());
if (kind === SyntaxKind.EOF) {
break;
}
// Check that the scanner has advanced
if (offset === offsetDelta + scanner.getPosition()) {
throw new Error(
'Scanner did not advance, next 3 characters are: ' + line.substr(scanner.getPosition(), 3)
);
}
// In case we inserted /* or " character, we need to
// adjust the offset of all tokens (except the first)
if (adjustOffset) {
offset -= numberOfInsertedCharacters;
}
adjustOffset = numberOfInsertedCharacters > 0;
// brackets and type
switch (kind) {
case SyntaxKind.OpenBraceToken:
parents = ParentsStack.push(parents, JSONParent.Object);
type = TOKEN_DELIM_OBJECT;
lastWasColon = false;
break;
case SyntaxKind.CloseBraceToken:
parents = ParentsStack.pop(parents);
type = TOKEN_DELIM_OBJECT;
lastWasColon = false;
break;
case SyntaxKind.OpenBracketToken:
parents = ParentsStack.push(parents, JSONParent.Array);
type = TOKEN_DELIM_ARRAY;
lastWasColon = false;
break;
case SyntaxKind.CloseBracketToken:
parents = ParentsStack.pop(parents);
type = TOKEN_DELIM_ARRAY;
lastWasColon = false;
break;
case SyntaxKind.ColonToken:
type = TOKEN_DELIM_COLON;
lastWasColon = true;
break;
case SyntaxKind.CommaToken:
type = TOKEN_DELIM_COMMA;
lastWasColon = false;
break;
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
type = TOKEN_VALUE_BOOLEAN;
lastWasColon = false;
break;
case SyntaxKind.NullKeyword:
type = TOKEN_VALUE_NULL;
lastWasColon = false;
break;
case SyntaxKind.StringLiteral:
const currentParent = parents ? parents.type : JSONParent.Object;
const inArray = currentParent === JSONParent.Array;
type = lastWasColon || inArray ? TOKEN_VALUE_STRING : TOKEN_PROPERTY_NAME;
lastWasColon = false;
break;
case SyntaxKind.NumericLiteral:
type = TOKEN_VALUE_NUMBER;
lastWasColon = false;
break;
}
// comments, iff enabled
if (comments) {
switch (kind) {
case SyntaxKind.LineCommentTrivia:
type = TOKEN_COMMENT_LINE;
break;
case SyntaxKind.BlockCommentTrivia:
type = TOKEN_COMMENT_BLOCK;
break;
}
}
ret.endState = new JSONState(
state.getStateData(),
<ScanError>(<any>scanner.getTokenError()),
lastWasColon,
parents
);
ret.tokens.push({
startIndex: offset,
scopes: type
});
}
return ret;
}

88
src/json/workerManager.ts Normal file
View file

@ -0,0 +1,88 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { LanguageServiceDefaults } from './monaco.contribution';
import type { JSONWorker } from './jsonWorker';
import { IDisposable, Uri, editor } from '../fillers/monaco-editor-core';
const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min
export class WorkerManager {
private _defaults: LanguageServiceDefaults;
private _idleCheckInterval: number;
private _lastUsedTime: number;
private _configChangeListener: IDisposable;
private _worker: editor.MonacoWebWorker<JSONWorker>;
private _client: Promise<JSONWorker>;
constructor(defaults: LanguageServiceDefaults) {
this._defaults = defaults;
this._worker = null;
this._idleCheckInterval = window.setInterval(() => this._checkIfIdle(), 30 * 1000);
this._lastUsedTime = 0;
this._configChangeListener = this._defaults.onDidChange(() => this._stopWorker());
}
private _stopWorker(): void {
if (this._worker) {
this._worker.dispose();
this._worker = null;
}
this._client = null;
}
dispose(): void {
clearInterval(this._idleCheckInterval);
this._configChangeListener.dispose();
this._stopWorker();
}
private _checkIfIdle(): void {
if (!this._worker) {
return;
}
let timePassedSinceLastUsed = Date.now() - this._lastUsedTime;
if (timePassedSinceLastUsed > STOP_WHEN_IDLE_FOR) {
this._stopWorker();
}
}
private _getClient(): Promise<JSONWorker> {
this._lastUsedTime = Date.now();
if (!this._client) {
this._worker = editor.createWebWorker<JSONWorker>({
// module that exports the create() method and returns a `JSONWorker` instance
moduleId: 'vs/language/json/jsonWorker',
label: this._defaults.languageId,
// passed in to the create() method
createData: {
languageSettings: this._defaults.diagnosticsOptions,
languageId: this._defaults.languageId,
enableSchemaRequest: this._defaults.diagnosticsOptions.enableSchemaRequest
}
});
this._client = <Promise<JSONWorker>>(<any>this._worker.getProxy());
}
return this._client;
}
getLanguageServiceWorker(...resources: Uri[]): Promise<JSONWorker> {
let _client: JSONWorker;
return this._getClient()
.then((client) => {
_client = client;
})
.then((_) => {
return this._worker.withSyncedResources(resources);
})
.then((_) => _client);
}
}