Adopt strict checking (fixes microsoft/monaco-editor#1715)

pull/2748/head
Alex Dima 5 years ago
parent 483a447093
commit e4ab9e4360
No known key found for this signature in database
GPG Key ID: 6E58D7B045760DA0

6
package-lock.json generated

@ -11,9 +11,9 @@
"dev": true "dev": true
}, },
"monaco-editor-core": { "monaco-editor-core": {
"version": "0.18.1", "version": "0.19.0",
"resolved": "https://registry.npmjs.org/monaco-editor-core/-/monaco-editor-core-0.18.1.tgz", "resolved": "https://registry.npmjs.org/monaco-editor-core/-/monaco-editor-core-0.19.0.tgz",
"integrity": "sha512-euzXzmwjZFG0oAPGjICMwINcZBzQDyfGDYlAR5YNMBJZO9Bmkqq1xpTTze/qQ0KKbVmawFXiwgUbg7WVgebP9Q==", "integrity": "sha512-wD60zpYDhsuJbzzLQigAteK2cA5fkuaDn+4c7NLwm/526OX5eL6MMvLhfvRgrDvLO00SYhFf6vz1y1C8M1hTpQ==",
"dev": true "dev": true
}, },
"monaco-languages": { "monaco-languages": {

@ -20,7 +20,7 @@
"url": "https://github.com/Microsoft/monaco-typescript/issues" "url": "https://github.com/Microsoft/monaco-typescript/issues"
}, },
"devDependencies": { "devDependencies": {
"monaco-editor-core": "^0.18.1", "monaco-editor-core": "^0.19.0",
"monaco-languages": "^1.8.0", "monaco-languages": "^1.8.0",
"monaco-plugin-helpers": "^1.0.2", "monaco-plugin-helpers": "^1.0.2",
"requirejs": "^2.3.6", "requirejs": "^2.3.6",

@ -11,7 +11,6 @@ import { TypeScriptWorker } from './tsWorker';
import Uri = monaco.Uri; import Uri = monaco.Uri;
import Position = monaco.Position; import Position = monaco.Position;
import Range = monaco.Range; import Range = monaco.Range;
import Thenable = monaco.Thenable;
import CancellationToken = monaco.CancellationToken; import CancellationToken = monaco.CancellationToken;
import IDisposable = monaco.IDisposable; import IDisposable = monaco.IDisposable;
@ -48,7 +47,7 @@ export function flattenDiagnosticMessageText(diag: string | ts.DiagnosticMessage
return result; return result;
} }
function displayPartsToString(displayParts: ts.SymbolDisplayPart[]): string { function displayPartsToString(displayParts: ts.SymbolDisplayPart[] | undefined): string {
if (displayParts) { if (displayParts) {
return displayParts.map((displayPart) => displayPart.text).join(""); return displayParts.map((displayPart) => displayPart.text).join("");
} }
@ -62,19 +61,17 @@ export abstract class Adapter {
constructor(protected _worker: (first: Uri, ...more: Uri[]) => Promise<TypeScriptWorker>) { constructor(protected _worker: (first: Uri, ...more: Uri[]) => Promise<TypeScriptWorker>) {
} }
protected _positionToOffset(uri: Uri, position: monaco.IPosition): number { // protected _positionToOffset(model: monaco.editor.ITextModel, position: monaco.IPosition): number {
let model = monaco.editor.getModel(uri); // return model.getOffsetAt(position);
return model.getOffsetAt(position); // }
}
protected _offsetToPosition(uri: Uri, offset: number): monaco.IPosition { // protected _offsetToPosition(model: monaco.editor.ITextModel, offset: number): monaco.IPosition {
let model = monaco.editor.getModel(uri); // return model.getPositionAt(offset);
return model.getPositionAt(offset); // }
}
protected _textSpanToRange(uri: Uri, span: ts.TextSpan): monaco.IRange { protected _textSpanToRange(model: monaco.editor.ITextModel, span: ts.TextSpan): monaco.IRange {
let p1 = this._offsetToPosition(uri, span.start); let p1 = model.getPositionAt(span.start);
let p2 = this._offsetToPosition(uri, span.start + span.length); let p2 = model.getPositionAt(span.start + span.length);
let { lineNumber: startLineNumber, column: startColumn } = p1; let { lineNumber: startLineNumber, column: startColumn } = p1;
let { lineNumber: endLineNumber, column: endColumn } = p2; let { lineNumber: endLineNumber, column: endColumn } = p2;
return { startLineNumber, startColumn, endLineNumber, endColumn }; return { startLineNumber, startColumn, endLineNumber, endColumn };
@ -108,7 +105,7 @@ export class DiagnosticsAdapter extends Adapter {
let handle: number; let handle: number;
const changeSubscription = model.onDidChangeContent(() => { const changeSubscription = model.onDidChangeContent(() => {
clearTimeout(handle); clearTimeout(handle);
handle = setTimeout(() => this._doValidate(model.uri), 500); handle = setTimeout(() => this._doValidate(model), 500);
}); });
this._listener[model.uri.toString()] = { this._listener[model.uri.toString()] = {
@ -118,7 +115,7 @@ export class DiagnosticsAdapter extends Adapter {
} }
}; };
this._doValidate(model.uri); this._doValidate(model);
}; };
const onModelRemoved = (model: monaco.editor.IModel): void => { const onModelRemoved = (model: monaco.editor.IModel): void => {
@ -163,43 +160,46 @@ export class DiagnosticsAdapter extends Adapter {
this._disposables = []; this._disposables = [];
} }
private _doValidate(resource: Uri): void { private async _doValidate(model: monaco.editor.ITextModel): Promise<void> {
this._worker(resource).then(worker => { const worker = await this._worker(model.uri);
if (!monaco.editor.getModel(resource)) {
if (model.isDisposed()) {
// model was disposed in the meantime // model was disposed in the meantime
return null; return;
} }
const promises: Promise<ts.Diagnostic[]>[] = []; const promises: Promise<ts.Diagnostic[]>[] = [];
const { noSyntaxValidation, noSemanticValidation, noSuggestionDiagnostics } = this._defaults.getDiagnosticsOptions(); const { noSyntaxValidation, noSemanticValidation, noSuggestionDiagnostics } = this._defaults.getDiagnosticsOptions();
if (!noSyntaxValidation) { if (!noSyntaxValidation) {
promises.push(worker.getSyntacticDiagnostics(resource.toString())); promises.push(worker.getSyntacticDiagnostics(model.uri.toString()));
} }
if (!noSemanticValidation) { if (!noSemanticValidation) {
promises.push(worker.getSemanticDiagnostics(resource.toString())); promises.push(worker.getSemanticDiagnostics(model.uri.toString()));
} }
if (!noSuggestionDiagnostics) { if (!noSuggestionDiagnostics) {
promises.push(worker.getSuggestionDiagnostics(resource.toString())); promises.push(worker.getSuggestionDiagnostics(model.uri.toString()));
} }
return Promise.all(promises);
}).then(diagnostics => { const diagnostics = await Promise.all(promises);
if (!diagnostics || !monaco.editor.getModel(resource)) {
if (!diagnostics || model.isDisposed()) {
// model was disposed in the meantime // model was disposed in the meantime
return null; return;
} }
const markers = diagnostics const markers = diagnostics
.reduce((p, c) => c.concat(p), []) .reduce((p, c) => c.concat(p), [])
.filter(d => (this._defaults.getDiagnosticsOptions().diagnosticCodesToIgnore || []).indexOf(d.code) === -1) .filter(d => (this._defaults.getDiagnosticsOptions().diagnosticCodesToIgnore || []).indexOf(d.code) === -1)
.map(d => this._convertDiagnostics(resource, d)); .map(d => this._convertDiagnostics(model, d));
monaco.editor.setModelMarkers(monaco.editor.getModel(resource), this._selector, markers); monaco.editor.setModelMarkers(model, this._selector, markers);
}).then(undefined, err => {
console.error(err);
});
} }
private _convertDiagnostics(resource: Uri, diag: ts.Diagnostic): monaco.editor.IMarkerData { private _convertDiagnostics(model: monaco.editor.ITextModel, diag: ts.Diagnostic): monaco.editor.IMarkerData {
const { lineNumber: startLineNumber, column: startColumn } = this._offsetToPosition(resource, diag.start); const diagStart = diag.start || 0;
const { lineNumber: endLineNumber, column: endColumn } = this._offsetToPosition(resource, diag.start + diag.length); const diagLength = diag.length || 1;
const { lineNumber: startLineNumber, column: startColumn } = model.getPositionAt(diagStart);
const { lineNumber: endLineNumber, column: endColumn } = model.getPositionAt(diagStart + diagLength);
return { return {
severity: this._tsDiagnosticCategoryToMarkerSeverity(diag.category), severity: this._tsDiagnosticCategoryToMarkerSeverity(diag.category),
@ -210,28 +210,41 @@ export class DiagnosticsAdapter extends Adapter {
message: flattenDiagnosticMessageText(diag.messageText, '\n'), message: flattenDiagnosticMessageText(diag.messageText, '\n'),
code: diag.code.toString(), code: diag.code.toString(),
tags: diag.reportsUnnecessary ? [monaco.MarkerTag.Unnecessary] : [], tags: diag.reportsUnnecessary ? [monaco.MarkerTag.Unnecessary] : [],
relatedInformation: this._convertRelatedInformation(resource, diag.relatedInformation), relatedInformation: this._convertRelatedInformation(model, diag.relatedInformation),
}; };
} }
private _convertRelatedInformation(resource: Uri, relatedInformation?: ts.DiagnosticRelatedInformation[]): monaco.editor.IRelatedInformation[] { private _convertRelatedInformation(model: monaco.editor.ITextModel, relatedInformation?: ts.DiagnosticRelatedInformation[]): monaco.editor.IRelatedInformation[] | undefined {
if (relatedInformation === undefined) if (!relatedInformation) {
return undefined; return;
}
const result: monaco.editor.IRelatedInformation[] = [];
relatedInformation.forEach((info) => {
let relatedResource: monaco.editor.ITextModel | null = model;
if (info.file) {
const relatedResourceUri = monaco.Uri.parse(info.file.fileName);
relatedResource = monaco.editor.getModel(relatedResourceUri);
}
return relatedInformation.map(info => { if (!relatedResource) {
const relatedResource = info.file === undefined ? resource : monaco.Uri.parse(info.file.fileName); return;
const { lineNumber: startLineNumber, column: startColumn } = this._offsetToPosition(relatedResource, info.start); }
const { lineNumber: endLineNumber, column: endColumn } = this._offsetToPosition(relatedResource, info.start + info.length); const infoStart = info.start || 0;
const infoLength = info.length || 1;
const { lineNumber: startLineNumber, column: startColumn } = relatedResource.getPositionAt(infoStart);
const { lineNumber: endLineNumber, column: endColumn } = relatedResource.getPositionAt(infoStart + infoLength);
return { result.push({
resource: relatedResource, resource: relatedResource.uri,
startLineNumber, startLineNumber,
startColumn, startColumn,
endLineNumber, endLineNumber,
endColumn, endColumn,
message: flattenDiagnosticMessageText(info.messageText, '\n') message: flattenDiagnosticMessageText(info.messageText, '\n')
};
}); });
});
return result;
} }
private _tsDiagnosticCategoryToMarkerSeverity(category: ts.DiagnosticCategory): monaco.MarkerSeverity { private _tsDiagnosticCategoryToMarkerSeverity(category: ts.DiagnosticCategory): monaco.MarkerSeverity {
@ -241,6 +254,7 @@ export class DiagnosticsAdapter extends Adapter {
case DiagnosticCategory.Warning: return monaco.MarkerSeverity.Warning case DiagnosticCategory.Warning: return monaco.MarkerSeverity.Warning
case DiagnosticCategory.Suggestion: return monaco.MarkerSeverity.Hint case DiagnosticCategory.Suggestion: return monaco.MarkerSeverity.Hint
} }
return monaco.MarkerSeverity.Info;
} }
} }
@ -257,19 +271,20 @@ export class SuggestAdapter extends Adapter implements monaco.languages.Completi
return ['.']; return ['.'];
} }
provideCompletionItems(model: monaco.editor.IReadOnlyModel, position: Position, _context: monaco.languages.CompletionContext, token: CancellationToken): Thenable<monaco.languages.CompletionList> { public async provideCompletionItems(model: monaco.editor.ITextModel, position: Position, _context: monaco.languages.CompletionContext, token: CancellationToken): Promise<monaco.languages.CompletionList | undefined> {
const wordInfo = model.getWordUntilPosition(position); const wordInfo = model.getWordUntilPosition(position);
const wordRange = new Range(position.lineNumber, wordInfo.startColumn, position.lineNumber, wordInfo.endColumn); const wordRange = new Range(position.lineNumber, wordInfo.startColumn, position.lineNumber, wordInfo.endColumn);
const resource = model.uri; const resource = model.uri;
const offset = this._positionToOffset(resource, position); const offset = model.getOffsetAt(position);
return this._worker(resource).then(worker => { const worker = await this._worker(resource);
return worker.getCompletionsAtPosition(resource.toString(), offset); const info = await worker.getCompletionsAtPosition(resource.toString(), offset);
}).then(info => {
if (!info) { if (!info || model.isDisposed()) {
return; return;
} }
let suggestions: MyCompletionItem[] = info.entries.map(entry => {
const suggestions: MyCompletionItem[] = info.entries.map(entry => {
let range = wordRange; let range = wordRange;
if (entry.replacementSpan) { if (entry.replacementSpan) {
const p1 = model.getPositionAt(entry.replacementSpan.start); const p1 = model.getPositionAt(entry.replacementSpan.start);
@ -291,21 +306,17 @@ export class SuggestAdapter extends Adapter implements monaco.languages.Completi
return { return {
suggestions suggestions
}; };
});
} }
resolveCompletionItem(_model: monaco.editor.IReadOnlyModel, _position: Position, item: monaco.languages.CompletionItem, token: CancellationToken): Thenable<monaco.languages.CompletionItem> { public async resolveCompletionItem(model: monaco.editor.ITextModel, _position: Position, item: monaco.languages.CompletionItem, token: CancellationToken): Promise<monaco.languages.CompletionItem> {
let myItem = <MyCompletionItem>item; const myItem = <MyCompletionItem>item;
const resource = myItem.uri; const resource = myItem.uri;
const position = myItem.position; const position = myItem.position;
const offset = model.getOffsetAt(position);
return this._worker(resource).then(worker => { const worker = await this._worker(resource);
return worker.getCompletionEntryDetails(resource.toString(), const details = await worker.getCompletionEntryDetails(resource.toString(), offset, myItem.label);
this._positionToOffset(resource, position), if (!details || model.isDisposed()) {
myItem.label);
}).then(details => {
if (!details) {
return myItem; return myItem;
} }
return <MyCompletionItem>{ return <MyCompletionItem>{
@ -318,7 +329,6 @@ export class SuggestAdapter extends Adapter implements monaco.languages.Completi
value: displayPartsToString(details.documentation) value: displayPartsToString(details.documentation)
} }
}; };
});
} }
private static convertKind(kind: string): monaco.languages.CompletionItemKind { private static convertKind(kind: string): monaco.languages.CompletionItemKind {
@ -359,15 +369,17 @@ export class SignatureHelpAdapter extends Adapter implements monaco.languages.Si
public signatureHelpTriggerCharacters = ['(', ',']; public signatureHelpTriggerCharacters = ['(', ','];
provideSignatureHelp(model: monaco.editor.IReadOnlyModel, position: Position, token: CancellationToken): Thenable<monaco.languages.SignatureHelpResult> { public async provideSignatureHelp(model: monaco.editor.ITextModel, position: Position, token: CancellationToken): Promise<monaco.languages.SignatureHelpResult | undefined> {
let resource = model.uri; const resource = model.uri;
return this._worker(resource).then(worker => worker.getSignatureHelpItems(resource.toString(), this._positionToOffset(resource, position))).then(info => { const offset = model.getOffsetAt(position);
const worker = await this._worker(resource);
const info = await worker.getSignatureHelpItems(resource.toString(), offset);
if (!info) { if (!info || model.isDisposed()) {
return; return;
} }
let ret: monaco.languages.SignatureHelp = { const ret: monaco.languages.SignatureHelp = {
activeSignature: info.selectedItemIndex, activeSignature: info.selectedItemIndex,
activeParameter: info.argumentIndex, activeParameter: info.argumentIndex,
signatures: [] signatures: []
@ -375,7 +387,7 @@ export class SignatureHelpAdapter extends Adapter implements monaco.languages.Si
info.items.forEach(item => { info.items.forEach(item => {
let signature: monaco.languages.SignatureInformation = { const signature: monaco.languages.SignatureInformation = {
label: '', label: '',
parameters: [] parameters: []
}; };
@ -383,8 +395,8 @@ export class SignatureHelpAdapter extends Adapter implements monaco.languages.Si
signature.documentation = displayPartsToString(item.documentation); signature.documentation = displayPartsToString(item.documentation);
signature.label += displayPartsToString(item.prefixDisplayParts); signature.label += displayPartsToString(item.prefixDisplayParts);
item.parameters.forEach((p, i, a) => { item.parameters.forEach((p, i, a) => {
let label = displayPartsToString(p.displayParts); const label = displayPartsToString(p.displayParts);
let parameter: monaco.languages.ParameterInformation = { const parameter: monaco.languages.ParameterInformation = {
label: label, label: label,
documentation: displayPartsToString(p.documentation) documentation: displayPartsToString(p.documentation)
}; };
@ -402,7 +414,6 @@ export class SignatureHelpAdapter extends Adapter implements monaco.languages.Si
value: ret, value: ret,
dispose() { } dispose() { }
}; };
});
} }
} }
@ -410,34 +421,33 @@ export class SignatureHelpAdapter extends Adapter implements monaco.languages.Si
export class QuickInfoAdapter extends Adapter implements monaco.languages.HoverProvider { export class QuickInfoAdapter extends Adapter implements monaco.languages.HoverProvider {
provideHover(model: monaco.editor.IReadOnlyModel, position: Position, token: CancellationToken): Thenable<monaco.languages.Hover> { public async provideHover(model: monaco.editor.ITextModel, position: Position, token: CancellationToken): Promise<monaco.languages.Hover | undefined> {
let resource = model.uri; const resource = model.uri;
const offset = model.getOffsetAt(position);
const worker = await this._worker(resource);
const info = await worker.getQuickInfoAtPosition(resource.toString(), offset);
return this._worker(resource).then(worker => { if (!info || model.isDisposed()) {
return worker.getQuickInfoAtPosition(resource.toString(), this._positionToOffset(resource, position));
}).then(info => {
if (!info) {
return; return;
} }
let documentation = displayPartsToString(info.documentation);
let tags = info.tags ? info.tags.map(tag => { const documentation = displayPartsToString(info.documentation);
const tags = info.tags ? info.tags.map(tag => {
const label = `*@${tag.name}*`; const label = `*@${tag.name}*`;
if (!tag.text) { if (!tag.text) {
return label; return label;
} }
return label + (tag.text.match(/\r\n|\n/g) ? ' \n' + tag.text : ` - ${tag.text}`); return label + (tag.text.match(/\r\n|\n/g) ? ' \n' + tag.text : ` - ${tag.text}`);
}) }).join(' \n\n') : '';
.join(' \n\n') : ''; const contents = displayPartsToString(info.displayParts);
let contents = displayPartsToString(info.displayParts);
return { return {
range: this._textSpanToRange(resource, info.textSpan), range: this._textSpanToRange(model, info.textSpan),
contents: [{ contents: [{
value: '```js\n' + contents + '\n```\n' value: '```js\n' + contents + '\n```\n'
}, { }, {
value: documentation + (tags ? '\n\n' + tags : '') value: documentation + (tags ? '\n\n' + tags : '')
}] }]
}; };
});
} }
} }
@ -445,22 +455,22 @@ export class QuickInfoAdapter extends Adapter implements monaco.languages.HoverP
export class OccurrencesAdapter extends Adapter implements monaco.languages.DocumentHighlightProvider { export class OccurrencesAdapter extends Adapter implements monaco.languages.DocumentHighlightProvider {
public provideDocumentHighlights(model: monaco.editor.IReadOnlyModel, position: Position, token: CancellationToken): Thenable<monaco.languages.DocumentHighlight[]> { public async provideDocumentHighlights(model: monaco.editor.ITextModel, position: Position, token: CancellationToken): Promise<monaco.languages.DocumentHighlight[] | undefined> {
const resource = model.uri; const resource = model.uri;
const offset = model.getOffsetAt(position)
const worker = await this._worker(resource);
const entries = await worker.getOccurrencesAtPosition(resource.toString(), offset);
return this._worker(resource).then(worker => { if (!entries || model.isDisposed()) {
return worker.getOccurrencesAtPosition(resource.toString(), this._positionToOffset(resource, position));
}).then(entries => {
if (!entries) {
return; return;
} }
return entries.map(entry => { return entries.map(entry => {
return <monaco.languages.DocumentHighlight>{ return <monaco.languages.DocumentHighlight>{
range: this._textSpanToRange(resource, entry.textSpan), range: this._textSpanToRange(model, entry.textSpan),
kind: entry.isWriteAccess ? monaco.languages.DocumentHighlightKind.Write : monaco.languages.DocumentHighlightKind.Text kind: entry.isWriteAccess ? monaco.languages.DocumentHighlightKind.Write : monaco.languages.DocumentHighlightKind.Text
}; };
}); });
});
} }
} }
@ -468,27 +478,28 @@ export class OccurrencesAdapter extends Adapter implements monaco.languages.Docu
export class DefinitionAdapter extends Adapter { export class DefinitionAdapter extends Adapter {
public provideDefinition(model: monaco.editor.IReadOnlyModel, position: Position, token: CancellationToken): Thenable<monaco.languages.Definition> { public async provideDefinition(model: monaco.editor.ITextModel, position: Position, token: CancellationToken): Promise<monaco.languages.Definition | undefined> {
const resource = model.uri; const resource = model.uri;
const offset = model.getOffsetAt(position);
const worker = await this._worker(resource);
const entries = await worker.getDefinitionAtPosition(resource.toString(), offset);
return this._worker(resource).then(worker => { if (!entries || model.isDisposed()) {
return worker.getDefinitionAtPosition(resource.toString(), this._positionToOffset(resource, position));
}).then(entries => {
if (!entries) {
return; return;
} }
const result: monaco.languages.Location[] = []; const result: monaco.languages.Location[] = [];
for (let entry of entries) { for (let entry of entries) {
const uri = Uri.parse(entry.fileName); const uri = Uri.parse(entry.fileName);
if (monaco.editor.getModel(uri)) { const refModel = monaco.editor.getModel(uri);
if (refModel) {
result.push({ result.push({
uri: uri, uri: uri,
range: this._textSpanToRange(uri, entry.textSpan) range: this._textSpanToRange(refModel, entry.textSpan)
}); });
} }
} }
return result; return result;
});
} }
} }
@ -496,27 +507,28 @@ export class DefinitionAdapter extends Adapter {
export class ReferenceAdapter extends Adapter implements monaco.languages.ReferenceProvider { export class ReferenceAdapter extends Adapter implements monaco.languages.ReferenceProvider {
provideReferences(model: monaco.editor.IReadOnlyModel, position: Position, context: monaco.languages.ReferenceContext, token: CancellationToken): Thenable<monaco.languages.Location[]> { public async provideReferences(model: monaco.editor.ITextModel, position: Position, context: monaco.languages.ReferenceContext, token: CancellationToken): Promise<monaco.languages.Location[] | undefined> {
const resource = model.uri; const resource = model.uri;
const offset = model.getOffsetAt(position);
const worker = await this._worker(resource);
const entries = await worker.getReferencesAtPosition(resource.toString(), offset);
return this._worker(resource).then(worker => { if (!entries || model.isDisposed()) {
return worker.getReferencesAtPosition(resource.toString(), this._positionToOffset(resource, position));
}).then(entries => {
if (!entries) {
return; return;
} }
const result: monaco.languages.Location[] = []; const result: monaco.languages.Location[] = [];
for (let entry of entries) { for (let entry of entries) {
const uri = Uri.parse(entry.fileName); const uri = Uri.parse(entry.fileName);
if (monaco.editor.getModel(uri)) { const refModel = monaco.editor.getModel(uri);
if (refModel) {
result.push({ result.push({
uri: uri, uri: uri,
range: this._textSpanToRange(uri, entry.textSpan) range: this._textSpanToRange(refModel, entry.textSpan)
}); });
} }
} }
return result; return result;
});
} }
} }
@ -524,11 +536,12 @@ export class ReferenceAdapter extends Adapter implements monaco.languages.Refere
export class OutlineAdapter extends Adapter implements monaco.languages.DocumentSymbolProvider { export class OutlineAdapter extends Adapter implements monaco.languages.DocumentSymbolProvider {
public provideDocumentSymbols(model: monaco.editor.IReadOnlyModel, token: CancellationToken): Thenable<monaco.languages.DocumentSymbol[]> { public async provideDocumentSymbols(model: monaco.editor.ITextModel, token: CancellationToken): Promise<monaco.languages.DocumentSymbol[] | undefined> {
const resource = model.uri; const resource = model.uri;
const worker = await this._worker(resource);
const items = await worker.getNavigationBarItems(resource.toString());
return this._worker(resource).then(worker => worker.getNavigationBarItems(resource.toString())).then(items => { if (!items || model.isDisposed()) {
if (!items) {
return; return;
} }
@ -537,8 +550,8 @@ export class OutlineAdapter extends Adapter implements monaco.languages.Document
name: item.text, name: item.text,
detail: '', detail: '',
kind: <monaco.languages.SymbolKind>(outlineTypeTable[item.kind] || monaco.languages.SymbolKind.Variable), kind: <monaco.languages.SymbolKind>(outlineTypeTable[item.kind] || monaco.languages.SymbolKind.Variable),
range: this._textSpanToRange(resource, item.spans[0]), range: this._textSpanToRange(model, item.spans[0]),
selectionRange: this._textSpanToRange(resource, item.spans[0]), selectionRange: this._textSpanToRange(model, item.spans[0]),
tags: [], tags: [],
containerName: containerLabel containerName: containerLabel
}; };
@ -555,7 +568,6 @@ export class OutlineAdapter extends Adapter implements monaco.languages.Document
let result: monaco.languages.DocumentSymbol[] = []; let result: monaco.languages.DocumentSymbol[] = [];
items.forEach(item => convert(result, item)); items.forEach(item => convert(result, item));
return result; return result;
});
} }
} }
@ -629,29 +641,28 @@ export abstract class FormatHelper extends Adapter {
}; };
} }
protected _convertTextChanges(uri: Uri, change: ts.TextChange): monaco.editor.ISingleEditOperation { protected _convertTextChanges(model: monaco.editor.ITextModel, change: ts.TextChange): monaco.languages.TextEdit {
return <monaco.editor.ISingleEditOperation>{ return {
text: change.newText, text: change.newText,
range: this._textSpanToRange(uri, change.span) range: this._textSpanToRange(model, change.span)
}; };
} }
} }
export class FormatAdapter extends FormatHelper implements monaco.languages.DocumentRangeFormattingEditProvider { export class FormatAdapter extends FormatHelper implements monaco.languages.DocumentRangeFormattingEditProvider {
provideDocumentRangeFormattingEdits(model: monaco.editor.IReadOnlyModel, range: Range, options: monaco.languages.FormattingOptions, token: CancellationToken): Thenable<monaco.editor.ISingleEditOperation[]> { public async provideDocumentRangeFormattingEdits(model: monaco.editor.ITextModel, range: Range, options: monaco.languages.FormattingOptions, token: CancellationToken): Promise<monaco.languages.TextEdit[] | undefined> {
const resource = model.uri; const resource = model.uri;
const startOffset = model.getOffsetAt({ lineNumber: range.startLineNumber, column: range.startColumn });
const endOffset = model.getOffsetAt({ lineNumber: range.endLineNumber, column: range.endColumn });
const worker = await this._worker(resource);
const edits = await worker.getFormattingEditsForRange(resource.toString(), startOffset, endOffset, FormatHelper._convertOptions(options));
return this._worker(resource).then(worker => { if (!edits || model.isDisposed()) {
return worker.getFormattingEditsForRange(resource.toString(), return;
this._positionToOffset(resource, { lineNumber: range.startLineNumber, column: range.startColumn }),
this._positionToOffset(resource, { lineNumber: range.endLineNumber, column: range.endColumn }),
FormatHelper._convertOptions(options));
}).then(edits => {
if (edits) {
return edits.map(edit => this._convertTextChanges(resource, edit));
} }
});
return edits.map(edit => this._convertTextChanges(model, edit));
} }
} }
@ -661,18 +672,17 @@ export class FormatOnTypeAdapter extends FormatHelper implements monaco.language
return [';', '}', '\n']; return [';', '}', '\n'];
} }
provideOnTypeFormattingEdits(model: monaco.editor.IReadOnlyModel, position: Position, ch: string, options: monaco.languages.FormattingOptions, token: CancellationToken): Thenable<monaco.editor.ISingleEditOperation[]> { public async provideOnTypeFormattingEdits(model: monaco.editor.ITextModel, position: Position, ch: string, options: monaco.languages.FormattingOptions, token: CancellationToken): Promise<monaco.languages.TextEdit[] | undefined> {
const resource = model.uri; const resource = model.uri;
const offset = model.getOffsetAt(position);
const worker = await this._worker(resource);
const edits = await worker.getFormattingEditsAfterKeystroke(resource.toString(), offset, ch, FormatHelper._convertOptions(options));
return this._worker(resource).then(worker => { if (!edits || model.isDisposed()) {
return worker.getFormattingEditsAfterKeystroke(resource.toString(), return;
this._positionToOffset(resource, position),
ch, FormatHelper._convertOptions(options));
}).then(edits => {
if (edits) {
return edits.map(edit => this._convertTextChanges(resource, edit));
} }
});
return edits.map(edit => this._convertTextChanges(model, edit));
} }
} }
@ -680,32 +690,30 @@ export class FormatOnTypeAdapter extends FormatHelper implements monaco.language
export class CodeActionAdaptor extends FormatHelper implements monaco.languages.CodeActionProvider { export class CodeActionAdaptor extends FormatHelper implements monaco.languages.CodeActionProvider {
public provideCodeActions(model: monaco.editor.ITextModel, range: Range, context: monaco.languages.CodeActionContext, token: CancellationToken): Promise<monaco.languages.CodeActionList> { public async provideCodeActions(model: monaco.editor.ITextModel, range: Range, context: monaco.languages.CodeActionContext, token: CancellationToken): Promise<monaco.languages.CodeActionList | undefined> {
const resource = model.uri; const resource = model.uri;
const start = model.getOffsetAt({ lineNumber: range.startLineNumber, column: range.startColumn });
return this._worker(resource).then(worker => { const end = model.getOffsetAt({ lineNumber: range.endLineNumber, column: range.endColumn });
const start = this._positionToOffset(resource, { lineNumber: range.startLineNumber, column: range.startColumn });
const end = this._positionToOffset(resource, { lineNumber: range.endLineNumber, column: range.endColumn });
const formatOptions = FormatHelper._convertOptions(model.getOptions()); const formatOptions = FormatHelper._convertOptions(model.getOptions());
const errorCodes = context.markers.filter(m => m.code).map(m => m.code).map(Number); const errorCodes = context.markers.filter(m => m.code).map(m => m.code).map(Number);
const worker = await this._worker(resource);
const codeFixes = await worker.getCodeFixesAtPosition(resource.toString(), start, end, errorCodes, formatOptions);
return worker.getCodeFixesAtPosition(resource.toString(), start, end, errorCodes, formatOptions); if (!codeFixes || model.isDisposed()) {
return;
}).then(codeFixes => { }
return codeFixes.filter(fix => { const actions = codeFixes.filter(fix => {
// Removes any 'make a new file'-type code fix // Removes any 'make a new file'-type code fix
return fix.changes.filter(change => change.isNewFile).length === 0; return fix.changes.filter(change => change.isNewFile).length === 0;
}).map(fix => { }).map(fix => {
return this._tsCodeFixActionToMonacoCodeAction(model, context, fix); return this._tsCodeFixActionToMonacoCodeAction(model, context, fix);
}) });
}).then(result => {
return { return {
actions: result, actions: actions,
dispose: () => { } dispose: () => { }
}; };
});
} }
@ -713,7 +721,7 @@ export class CodeActionAdaptor extends FormatHelper implements monaco.languages.
const edits: monaco.languages.ResourceTextEdit[] = codeFix.changes.map(edit => ({ const edits: monaco.languages.ResourceTextEdit[] = codeFix.changes.map(edit => ({
resource: model.uri, resource: model.uri,
edits: edit.textChanges.map(tc => ({ edits: edit.textChanges.map(tc => ({
range: this._textSpanToRange(model.uri, tc.span), range: this._textSpanToRange(model, tc.span),
text: tc.newText text: tc.newText
})) }))
})); }));
@ -732,10 +740,10 @@ export class CodeActionAdaptor extends FormatHelper implements monaco.languages.
export class RenameAdapter extends Adapter implements monaco.languages.RenameProvider { export class RenameAdapter extends Adapter implements monaco.languages.RenameProvider {
async provideRenameEdits(model: monaco.editor.ITextModel, position: Position, newName: string, token: CancellationToken): Promise<monaco.languages.WorkspaceEdit & monaco.languages.Rejection> { public async provideRenameEdits(model: monaco.editor.ITextModel, position: Position, newName: string, token: CancellationToken): Promise<monaco.languages.WorkspaceEdit & monaco.languages.Rejection | undefined> {
const resource = model.uri; const resource = model.uri;
const fileName = resource.toString(); const fileName = resource.toString();
const offset = this._positionToOffset(resource, position); const offset = model.getOffsetAt(position);
const worker = await this._worker(resource); const worker = await this._worker(resource);
const renameInfo = await worker.getRenameInfo(fileName, offset, { allowRenameOfImportPath: false }); const renameInfo = await worker.getRenameInfo(fileName, offset, { allowRenameOfImportPath: false });
@ -750,6 +758,11 @@ export class RenameAdapter extends Adapter implements monaco.languages.RenamePro
} }
const renameLocations = await worker.findRenameLocations(fileName, offset, /*strings*/ false, /*comments*/ false, /*prefixAndSuffix*/ false); const renameLocations = await worker.findRenameLocations(fileName, offset, /*strings*/ false, /*comments*/ false, /*prefixAndSuffix*/ false);
if (!renameLocations || model.isDisposed()) {
return;
}
const fileNameToResourceTextEditMap: { [fileName: string]: monaco.languages.ResourceTextEdit } = {}; const fileNameToResourceTextEditMap: { [fileName: string]: monaco.languages.ResourceTextEdit } = {};
const edits: monaco.languages.ResourceTextEdit[] = []; const edits: monaco.languages.ResourceTextEdit[] = [];
@ -764,7 +777,7 @@ export class RenameAdapter extends Adapter implements monaco.languages.RenamePro
} }
fileNameToResourceTextEditMap[renameLocation.fileName].edits.push({ fileNameToResourceTextEditMap[renameLocation.fileName].edits.push({
range: this._textSpanToRange(resource, renameLocation.textSpan), range: this._textSpanToRange(model, renameLocation.textSpan),
text: newName text: newName
}); });
} }

@ -0,0 +1,8 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'monaco-editor-core/esm/vs/editor/editor.worker' {
export function initialize(callback: (ctx: monaco.worker.IWorkerContext, createData: any) => any): void;
}

@ -30,13 +30,14 @@ export class LanguageServiceDefaultsImpl implements monaco.languages.typescript.
private _extraLibs: IExtraLibs; private _extraLibs: IExtraLibs;
private _workerMaxIdleTime: number; private _workerMaxIdleTime: number;
private _eagerModelSync: boolean; private _eagerModelSync: boolean;
private _compilerOptions: monaco.languages.typescript.CompilerOptions; private _compilerOptions!: monaco.languages.typescript.CompilerOptions;
private _diagnosticsOptions: monaco.languages.typescript.DiagnosticsOptions; private _diagnosticsOptions!: monaco.languages.typescript.DiagnosticsOptions;
private _onDidExtraLibsChangeTimeout: number; private _onDidExtraLibsChangeTimeout: number;
constructor(compilerOptions: monaco.languages.typescript.CompilerOptions, diagnosticsOptions: monaco.languages.typescript.DiagnosticsOptions) { constructor(compilerOptions: monaco.languages.typescript.CompilerOptions, diagnosticsOptions: monaco.languages.typescript.DiagnosticsOptions) {
this._extraLibs = Object.create(null); this._extraLibs = Object.create(null);
this._workerMaxIdleTime = 2 * 60 * 1000; this._workerMaxIdleTime = 2 * 60 * 1000;
this._eagerModelSync = false;
this.setCompilerOptions(compilerOptions); this.setCompilerOptions(compilerOptions);
this.setDiagnosticsOptions(diagnosticsOptions); this.setDiagnosticsOptions(diagnosticsOptions);
this._onDidExtraLibsChangeTimeout = -1; this._onDidExtraLibsChangeTimeout = -1;
@ -54,9 +55,12 @@ export class LanguageServiceDefaultsImpl implements monaco.languages.typescript.
return this._extraLibs; return this._extraLibs;
} }
addExtraLib(content: string, filePath?: string): IDisposable { addExtraLib(content: string, _filePath?: string): IDisposable {
if (typeof filePath === 'undefined') { let filePath: string;
if (typeof _filePath === 'undefined') {
filePath = `ts:extralib-${Math.random().toString(36).substring(2, 15)}`; filePath = `ts:extralib-${Math.random().toString(36).substring(2, 15)}`;
} else {
filePath = _filePath;
} }
if (this._extraLibs[filePath] && this._extraLibs[filePath].content === content) { if (this._extraLibs[filePath] && this._extraLibs[filePath].content === content) {

@ -5,11 +5,11 @@
'use strict'; 'use strict';
import * as worker from 'monaco-editor-core/esm/vs/editor/editor.worker'; import * as worker from 'monaco-editor-core/esm/vs/editor/editor.worker';
import { TypeScriptWorker } from './tsWorker'; import { TypeScriptWorker, ICreateData } from './tsWorker';
self.onmessage = () => { self.onmessage = () => {
// ignore the first message // ignore the first message
worker.initialize((ctx, createData) => { worker.initialize((ctx: monaco.worker.IWorkerContext, createData: ICreateData) => {
return new TypeScriptWorker(ctx, createData) return new TypeScriptWorker(ctx, createData)
}); });
}; };

@ -46,7 +46,7 @@ export class TypeScriptWorker implements ts.LanguageServiceHost {
return models.concat(Object.keys(this._extraLibs)); return models.concat(Object.keys(this._extraLibs));
} }
private _getModel(fileName: string): monaco.worker.IMirrorModel { private _getModel(fileName: string): monaco.worker.IMirrorModel | null {
let models = this._ctx.getMirrorModels(); let models = this._ctx.getMirrorModels();
for (let i = 0; i < models.length; i++) { for (let i = 0; i < models.length; i++) {
if (models[i].uri.toString() === fileName) { if (models[i].uri.toString() === fileName) {
@ -66,9 +66,10 @@ export class TypeScriptWorker implements ts.LanguageServiceHost {
} else if (fileName in this._extraLibs) { } else if (fileName in this._extraLibs) {
return String(this._extraLibs[fileName].version); return String(this._extraLibs[fileName].version);
} }
return '';
} }
getScriptSnapshot(fileName: string): ts.IScriptSnapshot { getScriptSnapshot(fileName: string): ts.IScriptSnapshot | undefined {
let text: string; let text: string;
let model = this._getModel(fileName); let model = this._getModel(fileName);
if (model) { if (model) {
@ -113,7 +114,7 @@ export class TypeScriptWorker implements ts.LanguageServiceHost {
getDefaultLibFileName(options: ts.CompilerOptions): string { getDefaultLibFileName(options: ts.CompilerOptions): string {
// TODO@joh support lib.es7.d.ts // TODO@joh support lib.es7.d.ts
return options.target <= ts.ScriptTarget.ES5 ? DEFAULT_LIB.NAME : ES6_LIB.NAME; return (options.target || ts.ScriptTarget.ES5) <= ts.ScriptTarget.ES5 ? DEFAULT_LIB.NAME : ES6_LIB.NAME;
} }
isDefaultLibFileName(fileName: string): boolean { isDefaultLibFileName(fileName: string): boolean {
@ -158,31 +159,31 @@ export class TypeScriptWorker implements ts.LanguageServiceHost {
return Promise.resolve(diagnostics); return Promise.resolve(diagnostics);
} }
getCompletionsAtPosition(fileName: string, position: number): Promise<ts.CompletionInfo> { getCompletionsAtPosition(fileName: string, position: number): Promise<ts.CompletionInfo | undefined> {
return Promise.resolve(this._languageService.getCompletionsAtPosition(fileName, position, undefined)); return Promise.resolve(this._languageService.getCompletionsAtPosition(fileName, position, undefined));
} }
getCompletionEntryDetails(fileName: string, position: number, entry: string): Promise<ts.CompletionEntryDetails> { getCompletionEntryDetails(fileName: string, position: number, entry: string): Promise<ts.CompletionEntryDetails | undefined> {
return Promise.resolve(this._languageService.getCompletionEntryDetails(fileName, position, entry, undefined, undefined, undefined)); return Promise.resolve(this._languageService.getCompletionEntryDetails(fileName, position, entry, undefined, undefined, undefined));
} }
getSignatureHelpItems(fileName: string, position: number): Promise<ts.SignatureHelpItems> { getSignatureHelpItems(fileName: string, position: number): Promise<ts.SignatureHelpItems | undefined> {
return Promise.resolve(this._languageService.getSignatureHelpItems(fileName, position, undefined)); return Promise.resolve(this._languageService.getSignatureHelpItems(fileName, position, undefined));
} }
getQuickInfoAtPosition(fileName: string, position: number): Promise<ts.QuickInfo> { getQuickInfoAtPosition(fileName: string, position: number): Promise<ts.QuickInfo | undefined> {
return Promise.resolve(this._languageService.getQuickInfoAtPosition(fileName, position)); return Promise.resolve(this._languageService.getQuickInfoAtPosition(fileName, position));
} }
getOccurrencesAtPosition(fileName: string, position: number): Promise<ReadonlyArray<ts.ReferenceEntry>> { getOccurrencesAtPosition(fileName: string, position: number): Promise<ReadonlyArray<ts.ReferenceEntry> | undefined> {
return Promise.resolve(this._languageService.getOccurrencesAtPosition(fileName, position)); return Promise.resolve(this._languageService.getOccurrencesAtPosition(fileName, position));
} }
getDefinitionAtPosition(fileName: string, position: number): Promise<ReadonlyArray<ts.DefinitionInfo>> { getDefinitionAtPosition(fileName: string, position: number): Promise<ReadonlyArray<ts.DefinitionInfo> | undefined> {
return Promise.resolve(this._languageService.getDefinitionAtPosition(fileName, position)); return Promise.resolve(this._languageService.getDefinitionAtPosition(fileName, position));
} }
getReferencesAtPosition(fileName: string, position: number): Promise<ts.ReferenceEntry[]> { getReferencesAtPosition(fileName: string, position: number): Promise<ts.ReferenceEntry[] | undefined> {
return Promise.resolve(this._languageService.getReferencesAtPosition(fileName, position)); return Promise.resolve(this._languageService.getReferencesAtPosition(fileName, position));
} }
@ -202,7 +203,7 @@ export class TypeScriptWorker implements ts.LanguageServiceHost {
return Promise.resolve(this._languageService.getFormattingEditsAfterKeystroke(fileName, postion, ch, options)); return Promise.resolve(this._languageService.getFormattingEditsAfterKeystroke(fileName, postion, ch, options));
} }
findRenameLocations(fileName: string, positon: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename: boolean): Promise<readonly ts.RenameLocation[]> { findRenameLocations(fileName: string, positon: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename: boolean): Promise<readonly ts.RenameLocation[] | undefined> {
return Promise.resolve(this._languageService.findRenameLocations(fileName, positon, findInStrings, findInComments, providePrefixAndSuffixTextForRename)); return Promise.resolve(this._languageService.findRenameLocations(fileName, positon, findInStrings, findInComments, providePrefixAndSuffixTextForRename));
} }

@ -11,7 +11,8 @@
"es2015.collection", "es2015.collection",
"es2015.iterable", "es2015.iterable",
"es2015.promise" "es2015.promise"
] ],
"strict": true
}, },
"include": [ "include": [
"**/*.ts" "**/*.ts"

@ -11,7 +11,8 @@
"es2015.collection", "es2015.collection",
"es2015.iterable", "es2015.iterable",
"es2015.promise" "es2015.promise"
] ],
"strict": true,
}, },
"include": [ "include": [
"**/*.ts" "**/*.ts"

@ -20,13 +20,14 @@ export class WorkerManager {
private _updateExtraLibsToken: number; private _updateExtraLibsToken: number;
private _extraLibsChangeListener: IDisposable; private _extraLibsChangeListener: IDisposable;
private _worker: monaco.editor.MonacoWebWorker<TypeScriptWorker>; private _worker: monaco.editor.MonacoWebWorker<TypeScriptWorker> | null;
private _client: Promise<TypeScriptWorker>; private _client: Promise<TypeScriptWorker> | null;
constructor(modeId: string, defaults: LanguageServiceDefaultsImpl) { constructor(modeId: string, defaults: LanguageServiceDefaultsImpl) {
this._modeId = modeId; this._modeId = modeId;
this._defaults = defaults; this._defaults = defaults;
this._worker = null; this._worker = null;
this._client = null;
this._idleCheckInterval = setInterval(() => this._checkIfIdle(), 30 * 1000); this._idleCheckInterval = setInterval(() => this._checkIfIdle(), 30 * 1000);
this._lastUsedTime = 0; this._lastUsedTime = 0;
this._configChangeListener = this._defaults.onDidChange(() => this._stopWorker()); this._configChangeListener = this._defaults.onDidChange(() => this._stopWorker());
@ -95,11 +96,14 @@ export class WorkerManager {
if (this._defaults.getEagerModelSync()) { if (this._defaults.getEagerModelSync()) {
p = p.then(worker => { p = p.then(worker => {
if (this._worker) {
return this._worker.withSyncedResources(monaco.editor.getModels() return this._worker.withSyncedResources(monaco.editor.getModels()
.filter(model => model.getModeId() === this._modeId) .filter(model => model.getModeId() === this._modeId)
.map(model => model.uri) .map(model => model.uri)
); );
}) }
return worker;
});
} }
this._client = p; this._client = p;
@ -113,7 +117,9 @@ export class WorkerManager {
return this._getClient().then((client) => { return this._getClient().then((client) => {
_client = client _client = client
}).then(_ => { }).then(_ => {
if (this._worker) {
return this._worker.withSyncedResources(resources) return this._worker.withSyncedResources(resources)
}
}).then(_ => _client); }).then(_ => _client);
} }
} }

Loading…
Cancel
Save