提交 963d1a5c 编写于 作者: D Dirk Baeumer

First set of TS 2.0 adoption work

上级 d705f554
......@@ -4,5 +4,6 @@
*--------------------------------------------------------------------------------------------*/
interface ArrayConstructor {
isArray(arg: any): arg is Array<any>;
isArray<T>(arg: any): arg is Array<T>;
}
\ No newline at end of file
......@@ -11,7 +11,8 @@ export function clone<T>(obj: T): T {
return obj;
}
if (obj instanceof RegExp) {
return obj;
// @dirk TS(2.0.2) - check after answer from TS team.
return obj as any;
}
var result = (Array.isArray(obj)) ? <any>[] : <any>{};
Object.keys(obj).forEach((key) => {
......
......@@ -52,7 +52,10 @@ export function isStringArray(value: any): value is string[] {
* @returns whether the provided parameter is of type `object` but **not**
* `null`, an `array`, a `regexp`, nor a `date`.
*/
export function isObject(obj: any): obj is any {
export function isObject(obj: any): boolean {
// The method can't do a type cast since there are type (like strings) which
// are subclasses of any put not positvely matched by the function. Hence type
// narrowing results in wrong results.
return typeof obj === _typeof.object
&& obj !== null
&& !Array.isArray(obj)
......
......@@ -41,7 +41,7 @@ export function request(options: IRequestOptions): TPromise<IRequestContext> {
return new TPromise<IRequestContext>((c, e) => {
const endpoint = parseUrl(options.url);
const protocol = endpoint.protocol === 'https:' ? https : http;
const request = endpoint.protocol === 'https:' ? https.request : http.request;
const opts: https.RequestOptions = {
hostname: endpoint.hostname,
port: endpoint.port ? parseInt(endpoint.port) : (endpoint.protocol === 'https:' ? 443 : 80),
......@@ -56,7 +56,7 @@ export function request(options: IRequestOptions): TPromise<IRequestContext> {
opts.auth = options.user + ':' + options.password;
}
req = protocol.request(opts, (res: http.ClientResponse) => {
req = request(opts, (res: http.ClientResponse) => {
const followRedirects = isNumber(options.followRedirects) ? options.followRedirects : 3;
if (res.statusCode >= 300 && res.statusCode < 400 && followRedirects > 0 && res.headers['location']) {
......
......@@ -311,7 +311,7 @@ export class ChannelClient implements IChannelClient, IDisposable {
}
}
export function getDelayedChannel<T extends IChannel>(promise: TPromise<IChannel>): T {
export function getDelayedChannel<T extends IChannel>(promise: TPromise<T>): T {
const call = (command, arg) => promise.then(c => c.call(command, arg));
return { call } as T;
}
......
......@@ -159,7 +159,7 @@ export class QuickOpenWidget implements IModelProvider {
}
// Pass tree navigation keys to the tree but leave focus in input field
else if (keyboardEvent.keyCode === KeyCode.Tab || keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) {
else if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) {
DOM.EventHelper.stop(e, true);
this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey);
......
......@@ -1220,7 +1220,7 @@ suite('Builder', () => {
var old = DomUtils.addDisposableListener;
try {
DomUtils.addDisposableListener = function (node, type, handler) {
(DomUtils as any).addDisposableListener = function (node, type, handler) {
var unbind: IDisposable = old.call(null, node, type, handler);
return {
......@@ -1246,7 +1246,7 @@ suite('Builder', () => {
b.empty();
assert.strictEqual(unbindCounter, 8);
} finally {
DomUtils.addDisposableListener = old;
(DomUtils as any).addDisposableListener = old;
}
});
......@@ -1407,7 +1407,7 @@ suite('Builder', () => {
var old = DomUtils.addDisposableListener;
try {
DomUtils.addDisposableListener = function (node, type, handler) {
(DomUtils as any).addDisposableListener = function (node, type, handler) {
var unbind: IDisposable = old.call(null, node, type, handler);
return {
......@@ -1435,7 +1435,7 @@ suite('Builder', () => {
b.destroy();
assert.strictEqual(unbindCounter, 16);
} finally {
DomUtils.addDisposableListener = old;
(DomUtils as any).addDisposableListener = old;
}
});
......
......@@ -785,7 +785,9 @@ export class TextModel extends OrderGuaranteeEventEmitter implements editorCommo
let searchRange:Range;
if (Range.isIRange(rawSearchScope)) {
searchRange = rawSearchScope;
// @alex TS(2.0.2) - isIRange tests for IRange but all our code assumes Range which now fails.
// Kept sematic using cast. But you should check.
searchRange = rawSearchScope as Range;
} else {
searchRange = this.getFullModelRange();
}
......
......@@ -269,9 +269,11 @@ export class FindModelBoundToEditorModel {
private _moveToNextMatch(nextMatch: Range): void
private _moveToNextMatch(after: Position): void
private _moveToNextMatch(arg: any): void {
let nextMatch = Range.isIRange(arg) ? arg : Position.isIPosition(arg) ? this._getNextMatch(arg) : null;
// @alex TS(2.0.2) - Adding cast to keep semantic. Necessary since the test are for interface but the code expects
// implemations.
let nextMatch = Range.isIRange(arg) ? arg : Position.isIPosition(arg) ? this._getNextMatch(arg as Position) : null;
if (nextMatch) {
this._setCurrentFindMatch(nextMatch);
this._setCurrentFindMatch(nextMatch as Range);
}
}
......
......@@ -23,7 +23,8 @@ export interface ITMSyntaxExtensionPoint {
injectTo: string[];
}
let grammarsExtPoint = ExtensionsRegistry.registerExtensionPoint<ITMSyntaxExtensionPoint[]>('grammars', {
// @martin TS(2.0.2) - Type IJsonSchema has no defined property require. Keeping semantic using any cast
let grammarsExtPoint = ExtensionsRegistry.registerExtensionPoint<ITMSyntaxExtensionPoint[]>('grammars', <any>{
description: nls.localize('vscode.extension.contributes.grammars', 'Contributes textmate tokenizers.'),
type: 'array',
defaultSnippets: [ { body: [{ language: '{{id}}', scopeName: 'source.{{id}}', path: './syntaxes/{{id}}.tmLanguage.'}] }],
......
......@@ -89,7 +89,7 @@ declare module monaco {
}
export class CancellationTokenSource {
token: CancellationToken;
readonly token: CancellationToken;
cancel(): void;
dispose(): void;
}
......@@ -121,31 +121,31 @@ declare module monaco {
* scheme is the 'http' part of 'http://www.msft.com/some/path?query#fragment'.
* The part before the first colon.
*/
scheme: string;
readonly scheme: string;
/**
* authority is the 'www.msft.com' part of 'http://www.msft.com/some/path?query#fragment'.
* The part between the first double slashes and the next slash.
*/
authority: string;
readonly authority: string;
/**
* path is the '/some/path' part of 'http://www.msft.com/some/path?query#fragment'.
*/
path: string;
readonly path: string;
/**
* query is the 'query' part of 'http://www.msft.com/some/path?query#fragment'.
*/
query: string;
readonly query: string;
/**
* fragment is the 'fragment' part of 'http://www.msft.com/some/path?query#fragment'.
*/
fragment: string;
readonly fragment: string;
/**
* Returns a string representing the corresponding file system path of this Uri.
* Will handle UNC paths and normalize windows drive letters to lower-case. Also
* uses the platform specific path separator. Will *not* validate the path for
* invalid characters and semantics. Will *not* look at the scheme of this Uri.
*/
fsPath: string;
readonly fsPath: string;
with(change: {
scheme?: string;
authority?: string;
......
......@@ -19,7 +19,7 @@ export interface IExtensionManagementChannel extends IChannel {
call(command: 'installFromGallery', extension: IGalleryExtension): TPromise<void>;
call(command: 'uninstall', extension: ILocalExtension): TPromise<void>;
call(command: 'getInstalled'): TPromise<ILocalExtension[]>;
call(command: string, arg: any): TPromise<any>;
call(command: string, arg?: any): TPromise<any>;
}
export class ExtensionManagementChannel implements IExtensionManagementChannel {
......@@ -36,7 +36,7 @@ export class ExtensionManagementChannel implements IExtensionManagementChannel {
this.onDidUninstallExtension = buffer(service.onDidUninstallExtension, true);
}
call(command: string, arg: any): TPromise<any> {
call(command: string, arg?: any): TPromise<any> {
switch (command) {
case 'event:onInstallExtension': return eventToCall(this.onInstallExtension);
case 'event:onDidInstallExtension': return eventToCall(this.onDidInstallExtension);
......
......@@ -284,7 +284,7 @@ export class ExtensionManagementService implements IExtensionManagementService {
return this.obsoleteFileLimiter.queue(() => {
let result: T = null;
return pfs.readFile(this.obsoletePath, 'utf8')
.then(null, err => err.code === 'ENOENT' ? TPromise.as('{}') : TPromise.wrapError(err))
.then<string>(null, err => err.code === 'ENOENT' ? TPromise.as('{}') : TPromise.wrapError(err))
.then<{ [id: string]: boolean }>(raw => { try { return JSON.parse(raw); } catch (e) { return {}; }})
.then(obsolete => { result = fn(obsolete); return obsolete; })
.then(obsolete => {
......
......@@ -17,7 +17,7 @@ const URIDeserializer: Deserializer<URI,any> = raw => URI.revive(raw);
export interface IURLChannel extends IChannel {
call(command: 'event:onOpenURL'): TPromise<void>;
call(command: string, arg: any): TPromise<any>;
call(command: string, arg?: any): TPromise<any>;
}
export class URLChannel implements IURLChannel {
......@@ -27,7 +27,7 @@ export class URLChannel implements IURLChannel {
@IWindowsService private windowsService: IWindowsService
) { }
call(command: string, arg: any): TPromise<any> {
call(command: string, arg?: any): TPromise<any> {
switch (command) {
case 'event:onOpenURL': return eventToCall(filterEvent(this.service.onOpenURL, () => this.isWindowFocused(arg)), URISerializer);
}
......
......@@ -214,13 +214,15 @@ export class TextEditorEdit {
replace(location: Position | Range | Selection, value: string): void {
let range: Range = null;
// @alex TS(2.0.2) - Selection is subclass of Range so the else if (location instanceof Selection) isn't reachable.
// Deleted it to keep sematic. You need to check if creating a new Range from a Selection is intended.
if (location instanceof Position) {
range = new Range(location, location);
} else if (location instanceof Range) {
range = location;
} else if (location instanceof Selection) {
} /* else if (location instanceof Selection) {
range = new Range(location.start, location.end);
} else {
} */ else {
throw new Error('Unrecognized location');
}
......@@ -242,11 +244,13 @@ export class TextEditorEdit {
delete(location: Range | Selection): void {
let range: Range = null;
// @alex TS(2.0.2) - Selection is subclass of Range so the else if (location instanceof Selection) isn't reachable.
// Deleted it to keep sematic. You need to check if creating a new Range from a Selection is intended.
if (location instanceof Range) {
range = location;
} else if (location instanceof Selection) {
} /* else if (location instanceof Selection) {
range = new Range(location.start, location.end);
} else {
} */ else {
throw new Error('Unrecognized location');
}
......@@ -393,7 +397,9 @@ class ExtHostTextEditor implements vscode.TextEditor {
() => this._proxy.$tryRevealRange(
this._id,
TypeConverters.fromRange(range),
revealType || TextEditorRevealType.Default
// @alex TS(2.0.2) - we still don't hack duck typing on enums. I added a cast since the
// values are the same. May be you want to write nicer code for this.
(revealType || TextEditorRevealType.Default) as any
),
true
);
......
......@@ -591,11 +591,15 @@ export class EditorPart extends Part implements IEditorPart, IEditorGroupService
}
// Check for dirty and veto
// @ben TS(2.0.2) - Direction.LEFT = 0 so !direction is true even if direction === Direction.LEFT.
// This is now detected by the compiler. I think the code is bogus but I commented out code to keep
// the current semantic.
let editorsToClose: EditorInput[];
if (!direction) {
editorsToClose = group.getEditors().filter(e => !except || !e.matches(except));
} else {
editorsToClose = (direction === Direction.LEFT) ? group.getEditors().slice(0, group.indexOf(except)) : group.getEditors().slice(group.indexOf(except) + 1);
// editorsToClose = (direction === Direction.LEFT) ? group.getEditors().slice(0, group.indexOf(except)) : group.getEditors().slice(group.indexOf(except) + 1);
editorsToClose = group.getEditors().slice(group.indexOf(except) + 1);
}
return this.handleDirty(editorsToClose.map(editor => { return { group, editor }; }), true /* ignore if opened in other group */).then(veto => {
......
......@@ -24,7 +24,6 @@ import {RemoteTelemetryService} from 'vs/workbench/api/node/extHostTelemetry';
import {ExtensionScanner, MessagesCollector} from 'vs/workbench/node/extensionPoints';
import {IWorkspaceContextService, WorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {Client} from 'vs/base/parts/ipc/node/ipc.net';
import {IExtensionManagementChannel, ExtensionManagementChannelClient} from 'vs/platform/extensionManagement/common/extensionManagementIpc';
const DIRNAME = URI.parse(require.toUrl('./')).fsPath;
const BASE_PATH = paths.normalize(paths.join(DIRNAME, '../../../..'));
......@@ -82,12 +81,14 @@ export class ExtensionHostMain {
this._extensionService = new ExtHostExtensionService(threadService, telemetryService, {_serviceBrand: 'optionalArgs', workspaceStoragePath });
// Connect to shared process services
/*
const channel = sharedProcessClient.getChannel<IExtensionManagementChannel>('extensions');
const extensionsService = new ExtensionManagementChannelClient(channel);
if (false && false) {
// TODO: what to do with the ExtensionManagementChannelClient?
console.log(extensionsService);
}
*/
// Create the ext host API
defineAPI(new ExtHostAPIImplementation(threadService, this._extensionService, this._contextService, telemetryService));
......
......@@ -738,7 +738,7 @@ export class WatchExpressionsActionProvider implements renderer.IActionProvider
}
public hasActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Expression && element.name;
return element instanceof model.Expression && !!element.name;
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
......
......@@ -89,14 +89,14 @@ export interface IGitChannel extends IChannel {
call(command: 'onOutput'): TPromise<void>;
call(command: 'getCommitTemplate'): TPromise<string>;
call(command: 'getCommit', ref: string): TPromise<ICommit>;
call(command: string, args: any): TPromise<any>;
call(command: string, args?: any): TPromise<any>;
}
export class GitChannel implements IGitChannel {
constructor(private service: TPromise<IRawGitService>) { }
call(command: string, args: any): TPromise<any> {
call(command: string, args?: any): TPromise<any> {
switch (command) {
case 'getVersion': return this.service.then(s => s.getVersion());
case 'serviceState': return this.service.then(s => s.serviceState());
......
......@@ -142,7 +142,8 @@ export class WorkbenchEditorService implements IWorkbenchEditorService {
protected doOpenEditor(input: EditorInput, options?: EditorOptions, sideBySide?: boolean): TPromise<IEditor>;
protected doOpenEditor(input: EditorInput, options?: EditorOptions, position?: Position): TPromise<IEditor>;
protected doOpenEditor(input: EditorInput, options?: EditorOptions, arg3?: any): TPromise<IEditor> {
return this.editorPart.openEditor(input, options, arg3);
// @dirk TS(2.0.2) - This is very likely a bug in TS.
return (this.editorPart as any).openEditor(input, options, arg3);
}
public openEditors(editors: { input: IResourceInput, position: Position }[]): TPromise<IEditor[]>;
......@@ -158,8 +159,8 @@ export class WorkbenchEditorService implements IWorkbenchEditorService {
position: editors[index].position
};
});
return this.editorPart.openEditors(typedInputs);
// @dirk TS(2.0.2) - This is very likely a bug in TS.
return (this.editorPart as any).openEditors(typedInputs);
});
}
......@@ -177,8 +178,8 @@ export class WorkbenchEditorService implements IWorkbenchEditorService {
options
};
});
return this.editorPart.replaceEditors(typedReplacements);
// @dirk TS(2.0.2) - This is very likely a bug in TS.
return (this.editorPart as any).replaceEditors(typedReplacements);
});
});
}
......
......@@ -283,7 +283,11 @@ let _b24_getActualKeyCodeMap = (function() {
if (nativeMapping.value && _b24_interestingChars[nativeMapping.value]) {
// console.log(nativeMapping.value + " is made by " + nativeMapping.key_code);
let keyCode = NATIVE_KEY_CODE_TO_KEY_CODE[nativeMapping.key_code];
if (keyCode && keyCode !== KeyCode.Unknown) {
// @alex TS(2.0.2) - KeyCode.Unknown === 0 so if (keyCode) is true then KeyCode !== KeyCode.Unknown
// is superflous code which is now flagged as a compile error (actually as a type check error that
// is very hard to understand)
// Will comment out the keyCode !== KeyCode.Unknown check.
if (keyCode /* && keyCode !== KeyCode.Unknown */) {
if (!result[nativeMapping.value] || result[nativeMapping.value] > keyCode) {
result[nativeMapping.value] = keyCode;
}
......@@ -293,7 +297,11 @@ let _b24_getActualKeyCodeMap = (function() {
if (nativeMapping.withShift && _b24_interestingChars[nativeMapping.withShift]) {
// console.log(nativeMapping.withShift + " is made by " + nativeMapping.key_code);
let keyCode = NATIVE_KEY_CODE_TO_KEY_CODE[nativeMapping.key_code];
if (keyCode && keyCode !== KeyCode.Unknown) {
// @alex TS(2.0.2) - KeyCode.Unknown === 0 so if (keyCode) is true then KeyCode !== KeyCode.Unknown
// is superflous code which is now flagged as a compile error (actually as a type check error that
// is very hard to understand)
// Will comment out the keyCode !== KeyCode.Unknown check.
if (keyCode /* && keyCode !== KeyCode.Unknown */) {
if (!result[nativeMapping.withShift] || result[nativeMapping.withShift] > keyCode) {
result[nativeMapping.withShift] = keyCode;
}
......
......@@ -131,10 +131,11 @@ export class FileWalker {
this.traversal = Traversal.MacFind;
traverse = this.macFindTraversal;
// Disable 'dir' for now (#11181, #11179, #11183, #11182).
} else if (false && platform.isWindows) {
// TS (2.0.2) warns about unreachable code. Using comments.
} /* else if (false && platform.isWindows) {
this.traversal = Traversal.WindowsDir;
traverse = this.windowsDirTraversal;
} else if (platform.isLinux) {
} */ else if (platform.isLinux) {
this.traversal = Traversal.LinuxFind;
traverse = this.linuxFindTraversal;
}
......@@ -196,7 +197,7 @@ export class FileWalker {
});
}
private windowsDirTraversal(rootFolder: string, onResult: (result: IRawFileMatch) => void, done: (err?: Error) => void): void {
protected windowsDirTraversal(rootFolder: string, onResult: (result: IRawFileMatch) => void, done: (err?: Error) => void): void {
const cmd = childProcess.spawn('cmd', ['/U', '/c', 'dir', '/s', '/b', '/a-d', rootFolder]);
this.readStdout(cmd, 'ucs2', (err: Error, stdout?: string) => {
if (err) {
......
......@@ -78,10 +78,12 @@ export class TokenStylesContribution {
public contributeStyles(themeId: string, themeDocument: IThemeDocument, cssRules: string[]): void {
let theme = new Theme(themeId, themeDocument);
theme.getSettings().forEach((s: IThemeSetting, index, arr) => {
// @alex TS(2.0.2) - s.scope is already a string[] so no need for all this checking.
// However will add a cast at split to keep semantic in case s.scope is wrongly typed.
let scope: string | string[] = s.scope;
let settings = s.settings;
if (scope && settings) {
let rules = Array.isArray(scope) ? <string[]>scope : scope.split(',');
let rules = Array.isArray(scope) ? <string[]>scope : (scope as string).split(',');
let statements = this._settingsToStatements(settings);
rules.forEach(rule => {
rule = rule.trim().replace(/ /g, '.'); // until we have scope hierarchy in the editor dom: replace spaces with .
......
......@@ -66,9 +66,9 @@ suite('ExtHostTypes', function () {
assert.throws(() => new types.Position(0, -1));
let pos = new types.Position(0, 0);
assert.throws(() => pos.line = -1);
assert.throws(() => pos.character = -1);
assert.throws(() => pos.line = 12);
assert.throws(() => (pos as any).line = -1);
assert.throws(() => (pos as any).character = -1);
assert.throws(() => (pos as any).line = 12);
let {line, character} = pos.toJSON();
assert.equal(line, 0);
......@@ -185,8 +185,8 @@ suite('ExtHostTypes', function () {
assert.throws(() => new types.Range(null, new types.Position(0, 0)));
let range = new types.Range(1, 0, 0, 0);
assert.throws(() => range.start = null);
assert.throws(() => range.start = new types.Position(0, 3));
assert.throws(() => (range as any).start= null);
assert.throws(() => (range as any).start = new types.Position(0, 3));
});
test('Range, toJSON', function () {
......
......@@ -85,7 +85,7 @@ export class TestThreadService extends AbstractThreadService implements IThreadS
setTimeout(c, 0);
}).then(() => {
const instance = this._testInstances[proxyId];
let p: TPromise<any>;
let p: Thenable<any>;
try {
let result = (<Function>instance[path]).apply(instance, args);
p = TPromise.is(result) ? result : TPromise.as(result);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册