Merge branch 'master' into requireAsFunctionInExternalModule

This commit is contained in:
Sheetal Nandi
2016-10-17 16:13:51 -07:00
636 changed files with 66214 additions and 17529 deletions
+2
View File
@@ -41,7 +41,9 @@ tests/cases/**/*.js.map
scripts/debug.bat
scripts/run.bat
scripts/word2md.js
scripts/buildProtocol.js
scripts/ior.js
scripts/buildProtocol.js
scripts/*.js.map
scripts/typings/
coverage/
-2
View File
@@ -183,5 +183,3 @@ jake baseline-accept
```
to establish the new baselines as the desired behavior. This will change the files in `tests\baselines\reference`, which should be included as part of your commit. It's important to carefully validate changes in the baselines.
**Note** that `baseline-accept` should only be run after a full test run! Accepting baselines after running a subset of tests will delete baseline files for the tests that didn't run.
+3 -3
View File
@@ -725,16 +725,16 @@ declare module "convert-source-map" {
}
gulp.task("browserify", "Runs browserify on run.js to produce a file suitable for running tests in the browser", [servicesFile], (done) => {
const testProject = tsc.createProject("src/harness/tsconfig.json", getCompilerSettings({ outFile: "built/local/bundle.js" }, /*useBuiltCompiler*/ true));
const testProject = tsc.createProject("src/harness/tsconfig.json", getCompilerSettings({ outFile: "../../built/local/bundle.js" }, /*useBuiltCompiler*/ true));
return testProject.src()
.pipe(newer("built/local/bundle.js"))
.pipe(sourcemaps.init())
.pipe(testProject)
.pipe(testProject())
.pipe(through2.obj((file, enc, next) => {
const originalMap = file.sourceMap;
const prebundledContent = file.contents.toString();
// Make paths absolute to help sorcery deal with all the terrible paths being thrown around
originalMap.sources = originalMap.sources.map(s => path.resolve("src", s));
originalMap.sources = originalMap.sources.map(s => path.resolve(s));
// intoStream (below) makes browserify think the input file is named this, so this is what it puts in the sourcemap
originalMap.file = "built/local/_stream_0.js";
+50 -13
View File
@@ -70,13 +70,14 @@ var compilerSources = [
"visitor.ts",
"transformers/destructuring.ts",
"transformers/ts.ts",
"transformers/module/es6.ts",
"transformers/module/es2015.ts",
"transformers/module/system.ts",
"transformers/module/module.ts",
"transformers/jsx.ts",
"transformers/es7.ts",
"transformers/es2017.ts",
"transformers/es2016.ts",
"transformers/es2015.ts",
"transformers/generators.ts",
"transformers/es6.ts",
"transformer.ts",
"sourcemap.ts",
"comments.ts",
@@ -104,13 +105,14 @@ var servicesSources = [
"visitor.ts",
"transformers/destructuring.ts",
"transformers/ts.ts",
"transformers/module/es6.ts",
"transformers/module/es2015.ts",
"transformers/module/system.ts",
"transformers/module/module.ts",
"transformers/jsx.ts",
"transformers/es7.ts",
"transformers/es2017.ts",
"transformers/es2016.ts",
"transformers/es2015.ts",
"transformers/generators.ts",
"transformers/es6.ts",
"transformer.ts",
"sourcemap.ts",
"comments.ts",
@@ -174,7 +176,7 @@ var serverCoreSources = [
"lsHost.ts",
"project.ts",
"editorServices.ts",
"protocol.d.ts",
"protocol.ts",
"session.ts",
"server.ts"
].map(function (f) {
@@ -198,14 +200,13 @@ var typingsInstallerSources = [
var serverSources = serverCoreSources.concat(servicesSources);
var languageServiceLibrarySources = [
"protocol.d.ts",
"protocol.ts",
"utilities.ts",
"scriptVersionCache.ts",
"scriptInfo.ts",
"lsHost.ts",
"project.ts",
"editorServices.ts",
"protocol.d.ts",
"session.ts",
].map(function (f) {
@@ -259,7 +260,7 @@ var harnessSources = harnessCoreSources.concat([
].map(function (f) {
return path.join(unittestsDirectory, f);
})).concat([
"protocol.d.ts",
"protocol.ts",
"utilities.ts",
"scriptVersionCache.ts",
"scriptInfo.ts",
@@ -267,7 +268,6 @@ var harnessSources = harnessCoreSources.concat([
"project.ts",
"typingsCache.ts",
"editorServices.ts",
"protocol.d.ts",
"session.ts",
].map(function (f) {
return path.join(serverDirectory, f);
@@ -355,6 +355,7 @@ function concatenateFiles(destinationFile, sourceFiles) {
if (!fs.existsSync(sourceFiles[i])) {
fail(sourceFiles[i] + " does not exist!");
}
fs.appendFileSync(temp, "\n\n");
fs.appendFileSync(temp, fs.readFileSync(sourceFiles[i]));
}
// Move the file to the final destination
@@ -518,6 +519,40 @@ compileFile(processDiagnosticMessagesJs,
[],
/*useBuiltCompiler*/ false);
var buildProtocolTs = path.join(scriptsDirectory, "buildProtocol.ts");
var buildProtocolJs = path.join(scriptsDirectory, "buildProtocol.js");
var buildProtocolDts = path.join(builtLocalDirectory, "protocol.d.ts");
var typescriptServicesDts = path.join(builtLocalDirectory, "typescriptServices.d.ts");
file(buildProtocolTs);
compileFile(buildProtocolJs,
[buildProtocolTs],
[buildProtocolTs],
[],
/*useBuiltCompiler*/ false,
{noOutFile: true});
file(buildProtocolDts, [buildProtocolTs, buildProtocolJs, typescriptServicesDts], function() {
var protocolTs = path.join(serverDirectory, "protocol.ts");
var cmd = host + " " + buildProtocolJs + " "+ protocolTs + " " + typescriptServicesDts + " " + buildProtocolDts;
console.log(cmd);
var ex = jake.createExec([cmd]);
// Add listeners for output and error
ex.addListener("stdout", function (output) {
process.stdout.write(output);
});
ex.addListener("stderr", function (error) {
process.stderr.write(error);
});
ex.addListener("cmdEnd", function () {
complete();
});
ex.run();
}, { async: true })
// The generated diagnostics map; built for the compiler and for the 'generate-diagnostics' task
file(diagnosticInfoMapTs, [processDiagnosticMessagesJs, diagnosticMessagesJson], function () {
var cmd = host + " " + processDiagnosticMessagesJs + " " + diagnosticMessagesJson;
@@ -655,6 +690,8 @@ compileFile(
inlineSourceMap: true
});
file(typescriptServicesDts, [servicesFile]);
var cancellationTokenFile = path.join(builtLocalDirectory, "cancellationToken.js");
compileFile(cancellationTokenFile, cancellationTokenSources, [builtLocalDirectory].concat(cancellationTokenSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, { outDir: builtLocalDirectory, noOutFile: true });
@@ -689,7 +726,7 @@ task("build-fold-end", [], function () {
// Local target to build the compiler and services
desc("Builds the full compiler and services");
task("local", ["build-fold-start", "generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile, builtGeneratedDiagnosticMessagesJSON, "lssl", "build-fold-end"]);
task("local", ["build-fold-start", "generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile, buildProtocolDts, builtGeneratedDiagnosticMessagesJSON, "lssl", "build-fold-end"]);
// Local target to build only tsc.js
desc("Builds only the compiler");
@@ -745,7 +782,7 @@ task("generate-spec", [specMd]);
// Makes a new LKG. This target does not build anything, but errors if not all the outputs are present in the built/local directory
desc("Makes a new LKG out of the built js files");
task("LKG", ["clean", "release", "local"].concat(libraryTargets), function () {
var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile, cancellationTokenFile, typingsInstallerFile].concat(libraryTargets);
var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile, cancellationTokenFile, typingsInstallerFile, buildProtocolDts].concat(libraryTargets);
var missingFiles = expectedFiles.filter(function (f) {
return !fs.existsSync(f);
});
+1 -1
View File
@@ -2,7 +2,7 @@
<!-- QUESTIONS: This is not a general support forum! Ask Qs at http://stackoverflow.com/questions/tagged/typescript -->
<!-- SUGGESTIONS: See https://github.com/Microsoft/TypeScript-wiki/blob/master/Writing-Good-Design-Proposals.md -->
**TypeScript Version:** 1.8.0 / nightly (2.0.0-dev.201xxxxx)
**TypeScript Version:** 2.0.3 / nightly (2.1.0-dev.201xxxxx)
**Code**
+217 -189
View File
@@ -260,6 +260,9 @@ interface Function {
*/
bind(this: Function, thisArg: any, ...argArray: any[]): any;
/** Returns a string representation of a function. */
toString(): string;
prototype: any;
readonly length: number;
@@ -1216,6 +1219,30 @@ interface Array<T> {
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@@ -11660,11 +11687,12 @@ declare var HashChangeEvent: {
interface History {
readonly length: number;
readonly state: any;
back(distance?: any): void;
forward(distance?: any): void;
go(delta?: any): void;
pushState(statedata: any, title?: string, url?: string): void;
replaceState(statedata: any, title?: string, url?: string): void;
scrollRestoration: ScrollRestoration;
back(): void;
forward(): void;
go(delta?: number): void;
pushState(data: any, title: string, url?: string | null): void;
replaceState(data: any, title: string, url?: string | null): void;
}
declare var History: {
@@ -17236,7 +17264,6 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
[index: number]: Window;
}
declare var Window: {
@@ -17267,7 +17294,7 @@ declare var XMLDocument: {
}
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
onreadystatechange: (this: this, ev: ProgressEvent) => any;
onreadystatechange: (this: this, ev: Event) => any;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
@@ -17294,13 +17321,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -17641,183 +17668,183 @@ interface NavigatorUserMedia {
}
interface NodeSelector {
querySelector(selectors: "a"): HTMLAnchorElement;
querySelector(selectors: "abbr"): HTMLElement;
querySelector(selectors: "acronym"): HTMLElement;
querySelector(selectors: "address"): HTMLElement;
querySelector(selectors: "applet"): HTMLAppletElement;
querySelector(selectors: "area"): HTMLAreaElement;
querySelector(selectors: "article"): HTMLElement;
querySelector(selectors: "aside"): HTMLElement;
querySelector(selectors: "audio"): HTMLAudioElement;
querySelector(selectors: "b"): HTMLElement;
querySelector(selectors: "base"): HTMLBaseElement;
querySelector(selectors: "basefont"): HTMLBaseFontElement;
querySelector(selectors: "bdo"): HTMLElement;
querySelector(selectors: "big"): HTMLElement;
querySelector(selectors: "blockquote"): HTMLQuoteElement;
querySelector(selectors: "body"): HTMLBodyElement;
querySelector(selectors: "br"): HTMLBRElement;
querySelector(selectors: "button"): HTMLButtonElement;
querySelector(selectors: "canvas"): HTMLCanvasElement;
querySelector(selectors: "caption"): HTMLTableCaptionElement;
querySelector(selectors: "center"): HTMLElement;
querySelector(selectors: "circle"): SVGCircleElement;
querySelector(selectors: "cite"): HTMLElement;
querySelector(selectors: "clippath"): SVGClipPathElement;
querySelector(selectors: "code"): HTMLElement;
querySelector(selectors: "col"): HTMLTableColElement;
querySelector(selectors: "colgroup"): HTMLTableColElement;
querySelector(selectors: "datalist"): HTMLDataListElement;
querySelector(selectors: "dd"): HTMLElement;
querySelector(selectors: "defs"): SVGDefsElement;
querySelector(selectors: "del"): HTMLModElement;
querySelector(selectors: "desc"): SVGDescElement;
querySelector(selectors: "dfn"): HTMLElement;
querySelector(selectors: "dir"): HTMLDirectoryElement;
querySelector(selectors: "div"): HTMLDivElement;
querySelector(selectors: "dl"): HTMLDListElement;
querySelector(selectors: "dt"): HTMLElement;
querySelector(selectors: "ellipse"): SVGEllipseElement;
querySelector(selectors: "em"): HTMLElement;
querySelector(selectors: "embed"): HTMLEmbedElement;
querySelector(selectors: "feblend"): SVGFEBlendElement;
querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement;
querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement;
querySelector(selectors: "fecomposite"): SVGFECompositeElement;
querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement;
querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement;
querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement;
querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement;
querySelector(selectors: "feflood"): SVGFEFloodElement;
querySelector(selectors: "fefunca"): SVGFEFuncAElement;
querySelector(selectors: "fefuncb"): SVGFEFuncBElement;
querySelector(selectors: "fefuncg"): SVGFEFuncGElement;
querySelector(selectors: "fefuncr"): SVGFEFuncRElement;
querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement;
querySelector(selectors: "feimage"): SVGFEImageElement;
querySelector(selectors: "femerge"): SVGFEMergeElement;
querySelector(selectors: "femergenode"): SVGFEMergeNodeElement;
querySelector(selectors: "femorphology"): SVGFEMorphologyElement;
querySelector(selectors: "feoffset"): SVGFEOffsetElement;
querySelector(selectors: "fepointlight"): SVGFEPointLightElement;
querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement;
querySelector(selectors: "fespotlight"): SVGFESpotLightElement;
querySelector(selectors: "fetile"): SVGFETileElement;
querySelector(selectors: "feturbulence"): SVGFETurbulenceElement;
querySelector(selectors: "fieldset"): HTMLFieldSetElement;
querySelector(selectors: "figcaption"): HTMLElement;
querySelector(selectors: "figure"): HTMLElement;
querySelector(selectors: "filter"): SVGFilterElement;
querySelector(selectors: "font"): HTMLFontElement;
querySelector(selectors: "footer"): HTMLElement;
querySelector(selectors: "foreignobject"): SVGForeignObjectElement;
querySelector(selectors: "form"): HTMLFormElement;
querySelector(selectors: "frame"): HTMLFrameElement;
querySelector(selectors: "frameset"): HTMLFrameSetElement;
querySelector(selectors: "g"): SVGGElement;
querySelector(selectors: "h1"): HTMLHeadingElement;
querySelector(selectors: "h2"): HTMLHeadingElement;
querySelector(selectors: "h3"): HTMLHeadingElement;
querySelector(selectors: "h4"): HTMLHeadingElement;
querySelector(selectors: "h5"): HTMLHeadingElement;
querySelector(selectors: "h6"): HTMLHeadingElement;
querySelector(selectors: "head"): HTMLHeadElement;
querySelector(selectors: "header"): HTMLElement;
querySelector(selectors: "hgroup"): HTMLElement;
querySelector(selectors: "hr"): HTMLHRElement;
querySelector(selectors: "html"): HTMLHtmlElement;
querySelector(selectors: "i"): HTMLElement;
querySelector(selectors: "iframe"): HTMLIFrameElement;
querySelector(selectors: "image"): SVGImageElement;
querySelector(selectors: "img"): HTMLImageElement;
querySelector(selectors: "input"): HTMLInputElement;
querySelector(selectors: "ins"): HTMLModElement;
querySelector(selectors: "isindex"): HTMLUnknownElement;
querySelector(selectors: "kbd"): HTMLElement;
querySelector(selectors: "keygen"): HTMLElement;
querySelector(selectors: "label"): HTMLLabelElement;
querySelector(selectors: "legend"): HTMLLegendElement;
querySelector(selectors: "li"): HTMLLIElement;
querySelector(selectors: "line"): SVGLineElement;
querySelector(selectors: "lineargradient"): SVGLinearGradientElement;
querySelector(selectors: "link"): HTMLLinkElement;
querySelector(selectors: "listing"): HTMLPreElement;
querySelector(selectors: "map"): HTMLMapElement;
querySelector(selectors: "mark"): HTMLElement;
querySelector(selectors: "marker"): SVGMarkerElement;
querySelector(selectors: "marquee"): HTMLMarqueeElement;
querySelector(selectors: "mask"): SVGMaskElement;
querySelector(selectors: "menu"): HTMLMenuElement;
querySelector(selectors: "meta"): HTMLMetaElement;
querySelector(selectors: "metadata"): SVGMetadataElement;
querySelector(selectors: "meter"): HTMLMeterElement;
querySelector(selectors: "nav"): HTMLElement;
querySelector(selectors: "nextid"): HTMLUnknownElement;
querySelector(selectors: "nobr"): HTMLElement;
querySelector(selectors: "noframes"): HTMLElement;
querySelector(selectors: "noscript"): HTMLElement;
querySelector(selectors: "object"): HTMLObjectElement;
querySelector(selectors: "ol"): HTMLOListElement;
querySelector(selectors: "optgroup"): HTMLOptGroupElement;
querySelector(selectors: "option"): HTMLOptionElement;
querySelector(selectors: "p"): HTMLParagraphElement;
querySelector(selectors: "param"): HTMLParamElement;
querySelector(selectors: "path"): SVGPathElement;
querySelector(selectors: "pattern"): SVGPatternElement;
querySelector(selectors: "picture"): HTMLPictureElement;
querySelector(selectors: "plaintext"): HTMLElement;
querySelector(selectors: "polygon"): SVGPolygonElement;
querySelector(selectors: "polyline"): SVGPolylineElement;
querySelector(selectors: "pre"): HTMLPreElement;
querySelector(selectors: "progress"): HTMLProgressElement;
querySelector(selectors: "q"): HTMLQuoteElement;
querySelector(selectors: "radialgradient"): SVGRadialGradientElement;
querySelector(selectors: "rect"): SVGRectElement;
querySelector(selectors: "rt"): HTMLElement;
querySelector(selectors: "ruby"): HTMLElement;
querySelector(selectors: "s"): HTMLElement;
querySelector(selectors: "samp"): HTMLElement;
querySelector(selectors: "script"): HTMLScriptElement;
querySelector(selectors: "section"): HTMLElement;
querySelector(selectors: "select"): HTMLSelectElement;
querySelector(selectors: "small"): HTMLElement;
querySelector(selectors: "source"): HTMLSourceElement;
querySelector(selectors: "span"): HTMLSpanElement;
querySelector(selectors: "stop"): SVGStopElement;
querySelector(selectors: "strike"): HTMLElement;
querySelector(selectors: "strong"): HTMLElement;
querySelector(selectors: "style"): HTMLStyleElement;
querySelector(selectors: "sub"): HTMLElement;
querySelector(selectors: "sup"): HTMLElement;
querySelector(selectors: "svg"): SVGSVGElement;
querySelector(selectors: "switch"): SVGSwitchElement;
querySelector(selectors: "symbol"): SVGSymbolElement;
querySelector(selectors: "table"): HTMLTableElement;
querySelector(selectors: "tbody"): HTMLTableSectionElement;
querySelector(selectors: "td"): HTMLTableDataCellElement;
querySelector(selectors: "template"): HTMLTemplateElement;
querySelector(selectors: "text"): SVGTextElement;
querySelector(selectors: "textpath"): SVGTextPathElement;
querySelector(selectors: "textarea"): HTMLTextAreaElement;
querySelector(selectors: "tfoot"): HTMLTableSectionElement;
querySelector(selectors: "th"): HTMLTableHeaderCellElement;
querySelector(selectors: "thead"): HTMLTableSectionElement;
querySelector(selectors: "title"): HTMLTitleElement;
querySelector(selectors: "tr"): HTMLTableRowElement;
querySelector(selectors: "track"): HTMLTrackElement;
querySelector(selectors: "tspan"): SVGTSpanElement;
querySelector(selectors: "tt"): HTMLElement;
querySelector(selectors: "u"): HTMLElement;
querySelector(selectors: "ul"): HTMLUListElement;
querySelector(selectors: "use"): SVGUseElement;
querySelector(selectors: "var"): HTMLElement;
querySelector(selectors: "video"): HTMLVideoElement;
querySelector(selectors: "view"): SVGViewElement;
querySelector(selectors: "wbr"): HTMLElement;
querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement;
querySelector(selectors: "xmp"): HTMLPreElement;
querySelector(selectors: string): Element;
querySelector(selectors: "a"): HTMLAnchorElement | null;
querySelector(selectors: "abbr"): HTMLElement | null;
querySelector(selectors: "acronym"): HTMLElement | null;
querySelector(selectors: "address"): HTMLElement | null;
querySelector(selectors: "applet"): HTMLAppletElement | null;
querySelector(selectors: "area"): HTMLAreaElement | null;
querySelector(selectors: "article"): HTMLElement | null;
querySelector(selectors: "aside"): HTMLElement | null;
querySelector(selectors: "audio"): HTMLAudioElement | null;
querySelector(selectors: "b"): HTMLElement | null;
querySelector(selectors: "base"): HTMLBaseElement | null;
querySelector(selectors: "basefont"): HTMLBaseFontElement | null;
querySelector(selectors: "bdo"): HTMLElement | null;
querySelector(selectors: "big"): HTMLElement | null;
querySelector(selectors: "blockquote"): HTMLQuoteElement | null;
querySelector(selectors: "body"): HTMLBodyElement | null;
querySelector(selectors: "br"): HTMLBRElement | null;
querySelector(selectors: "button"): HTMLButtonElement | null;
querySelector(selectors: "canvas"): HTMLCanvasElement | null;
querySelector(selectors: "caption"): HTMLTableCaptionElement | null;
querySelector(selectors: "center"): HTMLElement | null;
querySelector(selectors: "circle"): SVGCircleElement | null;
querySelector(selectors: "cite"): HTMLElement | null;
querySelector(selectors: "clippath"): SVGClipPathElement | null;
querySelector(selectors: "code"): HTMLElement | null;
querySelector(selectors: "col"): HTMLTableColElement | null;
querySelector(selectors: "colgroup"): HTMLTableColElement | null;
querySelector(selectors: "datalist"): HTMLDataListElement | null;
querySelector(selectors: "dd"): HTMLElement | null;
querySelector(selectors: "defs"): SVGDefsElement | null;
querySelector(selectors: "del"): HTMLModElement | null;
querySelector(selectors: "desc"): SVGDescElement | null;
querySelector(selectors: "dfn"): HTMLElement | null;
querySelector(selectors: "dir"): HTMLDirectoryElement | null;
querySelector(selectors: "div"): HTMLDivElement | null;
querySelector(selectors: "dl"): HTMLDListElement | null;
querySelector(selectors: "dt"): HTMLElement | null;
querySelector(selectors: "ellipse"): SVGEllipseElement | null;
querySelector(selectors: "em"): HTMLElement | null;
querySelector(selectors: "embed"): HTMLEmbedElement | null;
querySelector(selectors: "feblend"): SVGFEBlendElement | null;
querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null;
querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null;
querySelector(selectors: "fecomposite"): SVGFECompositeElement | null;
querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null;
querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null;
querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null;
querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null;
querySelector(selectors: "feflood"): SVGFEFloodElement | null;
querySelector(selectors: "fefunca"): SVGFEFuncAElement | null;
querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null;
querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null;
querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null;
querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null;
querySelector(selectors: "feimage"): SVGFEImageElement | null;
querySelector(selectors: "femerge"): SVGFEMergeElement | null;
querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null;
querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null;
querySelector(selectors: "feoffset"): SVGFEOffsetElement | null;
querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null;
querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null;
querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null;
querySelector(selectors: "fetile"): SVGFETileElement | null;
querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null;
querySelector(selectors: "fieldset"): HTMLFieldSetElement | null;
querySelector(selectors: "figcaption"): HTMLElement | null;
querySelector(selectors: "figure"): HTMLElement | null;
querySelector(selectors: "filter"): SVGFilterElement | null;
querySelector(selectors: "font"): HTMLFontElement | null;
querySelector(selectors: "footer"): HTMLElement | null;
querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null;
querySelector(selectors: "form"): HTMLFormElement | null;
querySelector(selectors: "frame"): HTMLFrameElement | null;
querySelector(selectors: "frameset"): HTMLFrameSetElement | null;
querySelector(selectors: "g"): SVGGElement | null;
querySelector(selectors: "h1"): HTMLHeadingElement | null;
querySelector(selectors: "h2"): HTMLHeadingElement | null;
querySelector(selectors: "h3"): HTMLHeadingElement | null;
querySelector(selectors: "h4"): HTMLHeadingElement | null;
querySelector(selectors: "h5"): HTMLHeadingElement | null;
querySelector(selectors: "h6"): HTMLHeadingElement | null;
querySelector(selectors: "head"): HTMLHeadElement | null;
querySelector(selectors: "header"): HTMLElement | null;
querySelector(selectors: "hgroup"): HTMLElement | null;
querySelector(selectors: "hr"): HTMLHRElement | null;
querySelector(selectors: "html"): HTMLHtmlElement | null;
querySelector(selectors: "i"): HTMLElement | null;
querySelector(selectors: "iframe"): HTMLIFrameElement | null;
querySelector(selectors: "image"): SVGImageElement | null;
querySelector(selectors: "img"): HTMLImageElement | null;
querySelector(selectors: "input"): HTMLInputElement | null;
querySelector(selectors: "ins"): HTMLModElement | null;
querySelector(selectors: "isindex"): HTMLUnknownElement | null;
querySelector(selectors: "kbd"): HTMLElement | null;
querySelector(selectors: "keygen"): HTMLElement | null;
querySelector(selectors: "label"): HTMLLabelElement | null;
querySelector(selectors: "legend"): HTMLLegendElement | null;
querySelector(selectors: "li"): HTMLLIElement | null;
querySelector(selectors: "line"): SVGLineElement | null;
querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null;
querySelector(selectors: "link"): HTMLLinkElement | null;
querySelector(selectors: "listing"): HTMLPreElement | null;
querySelector(selectors: "map"): HTMLMapElement | null;
querySelector(selectors: "mark"): HTMLElement | null;
querySelector(selectors: "marker"): SVGMarkerElement | null;
querySelector(selectors: "marquee"): HTMLMarqueeElement | null;
querySelector(selectors: "mask"): SVGMaskElement | null;
querySelector(selectors: "menu"): HTMLMenuElement | null;
querySelector(selectors: "meta"): HTMLMetaElement | null;
querySelector(selectors: "metadata"): SVGMetadataElement | null;
querySelector(selectors: "meter"): HTMLMeterElement | null;
querySelector(selectors: "nav"): HTMLElement | null;
querySelector(selectors: "nextid"): HTMLUnknownElement | null;
querySelector(selectors: "nobr"): HTMLElement | null;
querySelector(selectors: "noframes"): HTMLElement | null;
querySelector(selectors: "noscript"): HTMLElement | null;
querySelector(selectors: "object"): HTMLObjectElement | null;
querySelector(selectors: "ol"): HTMLOListElement | null;
querySelector(selectors: "optgroup"): HTMLOptGroupElement | null;
querySelector(selectors: "option"): HTMLOptionElement | null;
querySelector(selectors: "p"): HTMLParagraphElement | null;
querySelector(selectors: "param"): HTMLParamElement | null;
querySelector(selectors: "path"): SVGPathElement | null;
querySelector(selectors: "pattern"): SVGPatternElement | null;
querySelector(selectors: "picture"): HTMLPictureElement | null;
querySelector(selectors: "plaintext"): HTMLElement | null;
querySelector(selectors: "polygon"): SVGPolygonElement | null;
querySelector(selectors: "polyline"): SVGPolylineElement | null;
querySelector(selectors: "pre"): HTMLPreElement | null;
querySelector(selectors: "progress"): HTMLProgressElement | null;
querySelector(selectors: "q"): HTMLQuoteElement | null;
querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null;
querySelector(selectors: "rect"): SVGRectElement | null;
querySelector(selectors: "rt"): HTMLElement | null;
querySelector(selectors: "ruby"): HTMLElement | null;
querySelector(selectors: "s"): HTMLElement | null;
querySelector(selectors: "samp"): HTMLElement | null;
querySelector(selectors: "script"): HTMLScriptElement | null;
querySelector(selectors: "section"): HTMLElement | null;
querySelector(selectors: "select"): HTMLSelectElement | null;
querySelector(selectors: "small"): HTMLElement | null;
querySelector(selectors: "source"): HTMLSourceElement | null;
querySelector(selectors: "span"): HTMLSpanElement | null;
querySelector(selectors: "stop"): SVGStopElement | null;
querySelector(selectors: "strike"): HTMLElement | null;
querySelector(selectors: "strong"): HTMLElement | null;
querySelector(selectors: "style"): HTMLStyleElement | null;
querySelector(selectors: "sub"): HTMLElement | null;
querySelector(selectors: "sup"): HTMLElement | null;
querySelector(selectors: "svg"): SVGSVGElement | null;
querySelector(selectors: "switch"): SVGSwitchElement | null;
querySelector(selectors: "symbol"): SVGSymbolElement | null;
querySelector(selectors: "table"): HTMLTableElement | null;
querySelector(selectors: "tbody"): HTMLTableSectionElement | null;
querySelector(selectors: "td"): HTMLTableDataCellElement | null;
querySelector(selectors: "template"): HTMLTemplateElement | null;
querySelector(selectors: "text"): SVGTextElement | null;
querySelector(selectors: "textpath"): SVGTextPathElement | null;
querySelector(selectors: "textarea"): HTMLTextAreaElement | null;
querySelector(selectors: "tfoot"): HTMLTableSectionElement | null;
querySelector(selectors: "th"): HTMLTableHeaderCellElement | null;
querySelector(selectors: "thead"): HTMLTableSectionElement | null;
querySelector(selectors: "title"): HTMLTitleElement | null;
querySelector(selectors: "tr"): HTMLTableRowElement | null;
querySelector(selectors: "track"): HTMLTrackElement | null;
querySelector(selectors: "tspan"): SVGTSpanElement | null;
querySelector(selectors: "tt"): HTMLElement | null;
querySelector(selectors: "u"): HTMLElement | null;
querySelector(selectors: "ul"): HTMLUListElement | null;
querySelector(selectors: "use"): SVGUseElement | null;
querySelector(selectors: "var"): HTMLElement | null;
querySelector(selectors: "video"): HTMLVideoElement | null;
querySelector(selectors: "view"): SVGViewElement | null;
querySelector(selectors: "wbr"): HTMLElement | null;
querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null;
querySelector(selectors: "xmp"): HTMLPreElement | null;
querySelector(selectors: string): Element | null;
querySelectorAll(selectors: "a"): NodeListOf<HTMLAnchorElement>;
querySelectorAll(selectors: "abbr"): NodeListOf<HTMLElement>;
querySelectorAll(selectors: "acronym"): NodeListOf<HTMLElement>;
@@ -18747,6 +18774,7 @@ type ScrollLogicalPosition = "start" | "center" | "end" | "nearest";
type IDBValidKey = number | string | Date | IDBArrayKey;
type BufferSource = ArrayBuffer | ArrayBufferView;
type MouseWheelEvent = WheelEvent;
type ScrollRestoration = "auto" | "manual";
/////////////////////////////
/// WorkerGlobalScope APIs
/////////////////////////////
+191 -190
View File
@@ -7552,11 +7552,12 @@ declare var HashChangeEvent: {
interface History {
readonly length: number;
readonly state: any;
back(distance?: any): void;
forward(distance?: any): void;
go(delta?: any): void;
pushState(statedata: any, title?: string, url?: string): void;
replaceState(statedata: any, title?: string, url?: string): void;
scrollRestoration: ScrollRestoration;
back(): void;
forward(): void;
go(delta?: number): void;
pushState(data: any, title: string, url?: string | null): void;
replaceState(data: any, title: string, url?: string | null): void;
}
declare var History: {
@@ -13128,7 +13129,6 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
[index: number]: Window;
}
declare var Window: {
@@ -13159,7 +13159,7 @@ declare var XMLDocument: {
}
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
onreadystatechange: (this: this, ev: ProgressEvent) => any;
onreadystatechange: (this: this, ev: Event) => any;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
@@ -13186,13 +13186,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -13533,183 +13533,183 @@ interface NavigatorUserMedia {
}
interface NodeSelector {
querySelector(selectors: "a"): HTMLAnchorElement;
querySelector(selectors: "abbr"): HTMLElement;
querySelector(selectors: "acronym"): HTMLElement;
querySelector(selectors: "address"): HTMLElement;
querySelector(selectors: "applet"): HTMLAppletElement;
querySelector(selectors: "area"): HTMLAreaElement;
querySelector(selectors: "article"): HTMLElement;
querySelector(selectors: "aside"): HTMLElement;
querySelector(selectors: "audio"): HTMLAudioElement;
querySelector(selectors: "b"): HTMLElement;
querySelector(selectors: "base"): HTMLBaseElement;
querySelector(selectors: "basefont"): HTMLBaseFontElement;
querySelector(selectors: "bdo"): HTMLElement;
querySelector(selectors: "big"): HTMLElement;
querySelector(selectors: "blockquote"): HTMLQuoteElement;
querySelector(selectors: "body"): HTMLBodyElement;
querySelector(selectors: "br"): HTMLBRElement;
querySelector(selectors: "button"): HTMLButtonElement;
querySelector(selectors: "canvas"): HTMLCanvasElement;
querySelector(selectors: "caption"): HTMLTableCaptionElement;
querySelector(selectors: "center"): HTMLElement;
querySelector(selectors: "circle"): SVGCircleElement;
querySelector(selectors: "cite"): HTMLElement;
querySelector(selectors: "clippath"): SVGClipPathElement;
querySelector(selectors: "code"): HTMLElement;
querySelector(selectors: "col"): HTMLTableColElement;
querySelector(selectors: "colgroup"): HTMLTableColElement;
querySelector(selectors: "datalist"): HTMLDataListElement;
querySelector(selectors: "dd"): HTMLElement;
querySelector(selectors: "defs"): SVGDefsElement;
querySelector(selectors: "del"): HTMLModElement;
querySelector(selectors: "desc"): SVGDescElement;
querySelector(selectors: "dfn"): HTMLElement;
querySelector(selectors: "dir"): HTMLDirectoryElement;
querySelector(selectors: "div"): HTMLDivElement;
querySelector(selectors: "dl"): HTMLDListElement;
querySelector(selectors: "dt"): HTMLElement;
querySelector(selectors: "ellipse"): SVGEllipseElement;
querySelector(selectors: "em"): HTMLElement;
querySelector(selectors: "embed"): HTMLEmbedElement;
querySelector(selectors: "feblend"): SVGFEBlendElement;
querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement;
querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement;
querySelector(selectors: "fecomposite"): SVGFECompositeElement;
querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement;
querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement;
querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement;
querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement;
querySelector(selectors: "feflood"): SVGFEFloodElement;
querySelector(selectors: "fefunca"): SVGFEFuncAElement;
querySelector(selectors: "fefuncb"): SVGFEFuncBElement;
querySelector(selectors: "fefuncg"): SVGFEFuncGElement;
querySelector(selectors: "fefuncr"): SVGFEFuncRElement;
querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement;
querySelector(selectors: "feimage"): SVGFEImageElement;
querySelector(selectors: "femerge"): SVGFEMergeElement;
querySelector(selectors: "femergenode"): SVGFEMergeNodeElement;
querySelector(selectors: "femorphology"): SVGFEMorphologyElement;
querySelector(selectors: "feoffset"): SVGFEOffsetElement;
querySelector(selectors: "fepointlight"): SVGFEPointLightElement;
querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement;
querySelector(selectors: "fespotlight"): SVGFESpotLightElement;
querySelector(selectors: "fetile"): SVGFETileElement;
querySelector(selectors: "feturbulence"): SVGFETurbulenceElement;
querySelector(selectors: "fieldset"): HTMLFieldSetElement;
querySelector(selectors: "figcaption"): HTMLElement;
querySelector(selectors: "figure"): HTMLElement;
querySelector(selectors: "filter"): SVGFilterElement;
querySelector(selectors: "font"): HTMLFontElement;
querySelector(selectors: "footer"): HTMLElement;
querySelector(selectors: "foreignobject"): SVGForeignObjectElement;
querySelector(selectors: "form"): HTMLFormElement;
querySelector(selectors: "frame"): HTMLFrameElement;
querySelector(selectors: "frameset"): HTMLFrameSetElement;
querySelector(selectors: "g"): SVGGElement;
querySelector(selectors: "h1"): HTMLHeadingElement;
querySelector(selectors: "h2"): HTMLHeadingElement;
querySelector(selectors: "h3"): HTMLHeadingElement;
querySelector(selectors: "h4"): HTMLHeadingElement;
querySelector(selectors: "h5"): HTMLHeadingElement;
querySelector(selectors: "h6"): HTMLHeadingElement;
querySelector(selectors: "head"): HTMLHeadElement;
querySelector(selectors: "header"): HTMLElement;
querySelector(selectors: "hgroup"): HTMLElement;
querySelector(selectors: "hr"): HTMLHRElement;
querySelector(selectors: "html"): HTMLHtmlElement;
querySelector(selectors: "i"): HTMLElement;
querySelector(selectors: "iframe"): HTMLIFrameElement;
querySelector(selectors: "image"): SVGImageElement;
querySelector(selectors: "img"): HTMLImageElement;
querySelector(selectors: "input"): HTMLInputElement;
querySelector(selectors: "ins"): HTMLModElement;
querySelector(selectors: "isindex"): HTMLUnknownElement;
querySelector(selectors: "kbd"): HTMLElement;
querySelector(selectors: "keygen"): HTMLElement;
querySelector(selectors: "label"): HTMLLabelElement;
querySelector(selectors: "legend"): HTMLLegendElement;
querySelector(selectors: "li"): HTMLLIElement;
querySelector(selectors: "line"): SVGLineElement;
querySelector(selectors: "lineargradient"): SVGLinearGradientElement;
querySelector(selectors: "link"): HTMLLinkElement;
querySelector(selectors: "listing"): HTMLPreElement;
querySelector(selectors: "map"): HTMLMapElement;
querySelector(selectors: "mark"): HTMLElement;
querySelector(selectors: "marker"): SVGMarkerElement;
querySelector(selectors: "marquee"): HTMLMarqueeElement;
querySelector(selectors: "mask"): SVGMaskElement;
querySelector(selectors: "menu"): HTMLMenuElement;
querySelector(selectors: "meta"): HTMLMetaElement;
querySelector(selectors: "metadata"): SVGMetadataElement;
querySelector(selectors: "meter"): HTMLMeterElement;
querySelector(selectors: "nav"): HTMLElement;
querySelector(selectors: "nextid"): HTMLUnknownElement;
querySelector(selectors: "nobr"): HTMLElement;
querySelector(selectors: "noframes"): HTMLElement;
querySelector(selectors: "noscript"): HTMLElement;
querySelector(selectors: "object"): HTMLObjectElement;
querySelector(selectors: "ol"): HTMLOListElement;
querySelector(selectors: "optgroup"): HTMLOptGroupElement;
querySelector(selectors: "option"): HTMLOptionElement;
querySelector(selectors: "p"): HTMLParagraphElement;
querySelector(selectors: "param"): HTMLParamElement;
querySelector(selectors: "path"): SVGPathElement;
querySelector(selectors: "pattern"): SVGPatternElement;
querySelector(selectors: "picture"): HTMLPictureElement;
querySelector(selectors: "plaintext"): HTMLElement;
querySelector(selectors: "polygon"): SVGPolygonElement;
querySelector(selectors: "polyline"): SVGPolylineElement;
querySelector(selectors: "pre"): HTMLPreElement;
querySelector(selectors: "progress"): HTMLProgressElement;
querySelector(selectors: "q"): HTMLQuoteElement;
querySelector(selectors: "radialgradient"): SVGRadialGradientElement;
querySelector(selectors: "rect"): SVGRectElement;
querySelector(selectors: "rt"): HTMLElement;
querySelector(selectors: "ruby"): HTMLElement;
querySelector(selectors: "s"): HTMLElement;
querySelector(selectors: "samp"): HTMLElement;
querySelector(selectors: "script"): HTMLScriptElement;
querySelector(selectors: "section"): HTMLElement;
querySelector(selectors: "select"): HTMLSelectElement;
querySelector(selectors: "small"): HTMLElement;
querySelector(selectors: "source"): HTMLSourceElement;
querySelector(selectors: "span"): HTMLSpanElement;
querySelector(selectors: "stop"): SVGStopElement;
querySelector(selectors: "strike"): HTMLElement;
querySelector(selectors: "strong"): HTMLElement;
querySelector(selectors: "style"): HTMLStyleElement;
querySelector(selectors: "sub"): HTMLElement;
querySelector(selectors: "sup"): HTMLElement;
querySelector(selectors: "svg"): SVGSVGElement;
querySelector(selectors: "switch"): SVGSwitchElement;
querySelector(selectors: "symbol"): SVGSymbolElement;
querySelector(selectors: "table"): HTMLTableElement;
querySelector(selectors: "tbody"): HTMLTableSectionElement;
querySelector(selectors: "td"): HTMLTableDataCellElement;
querySelector(selectors: "template"): HTMLTemplateElement;
querySelector(selectors: "text"): SVGTextElement;
querySelector(selectors: "textpath"): SVGTextPathElement;
querySelector(selectors: "textarea"): HTMLTextAreaElement;
querySelector(selectors: "tfoot"): HTMLTableSectionElement;
querySelector(selectors: "th"): HTMLTableHeaderCellElement;
querySelector(selectors: "thead"): HTMLTableSectionElement;
querySelector(selectors: "title"): HTMLTitleElement;
querySelector(selectors: "tr"): HTMLTableRowElement;
querySelector(selectors: "track"): HTMLTrackElement;
querySelector(selectors: "tspan"): SVGTSpanElement;
querySelector(selectors: "tt"): HTMLElement;
querySelector(selectors: "u"): HTMLElement;
querySelector(selectors: "ul"): HTMLUListElement;
querySelector(selectors: "use"): SVGUseElement;
querySelector(selectors: "var"): HTMLElement;
querySelector(selectors: "video"): HTMLVideoElement;
querySelector(selectors: "view"): SVGViewElement;
querySelector(selectors: "wbr"): HTMLElement;
querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement;
querySelector(selectors: "xmp"): HTMLPreElement;
querySelector(selectors: string): Element;
querySelector(selectors: "a"): HTMLAnchorElement | null;
querySelector(selectors: "abbr"): HTMLElement | null;
querySelector(selectors: "acronym"): HTMLElement | null;
querySelector(selectors: "address"): HTMLElement | null;
querySelector(selectors: "applet"): HTMLAppletElement | null;
querySelector(selectors: "area"): HTMLAreaElement | null;
querySelector(selectors: "article"): HTMLElement | null;
querySelector(selectors: "aside"): HTMLElement | null;
querySelector(selectors: "audio"): HTMLAudioElement | null;
querySelector(selectors: "b"): HTMLElement | null;
querySelector(selectors: "base"): HTMLBaseElement | null;
querySelector(selectors: "basefont"): HTMLBaseFontElement | null;
querySelector(selectors: "bdo"): HTMLElement | null;
querySelector(selectors: "big"): HTMLElement | null;
querySelector(selectors: "blockquote"): HTMLQuoteElement | null;
querySelector(selectors: "body"): HTMLBodyElement | null;
querySelector(selectors: "br"): HTMLBRElement | null;
querySelector(selectors: "button"): HTMLButtonElement | null;
querySelector(selectors: "canvas"): HTMLCanvasElement | null;
querySelector(selectors: "caption"): HTMLTableCaptionElement | null;
querySelector(selectors: "center"): HTMLElement | null;
querySelector(selectors: "circle"): SVGCircleElement | null;
querySelector(selectors: "cite"): HTMLElement | null;
querySelector(selectors: "clippath"): SVGClipPathElement | null;
querySelector(selectors: "code"): HTMLElement | null;
querySelector(selectors: "col"): HTMLTableColElement | null;
querySelector(selectors: "colgroup"): HTMLTableColElement | null;
querySelector(selectors: "datalist"): HTMLDataListElement | null;
querySelector(selectors: "dd"): HTMLElement | null;
querySelector(selectors: "defs"): SVGDefsElement | null;
querySelector(selectors: "del"): HTMLModElement | null;
querySelector(selectors: "desc"): SVGDescElement | null;
querySelector(selectors: "dfn"): HTMLElement | null;
querySelector(selectors: "dir"): HTMLDirectoryElement | null;
querySelector(selectors: "div"): HTMLDivElement | null;
querySelector(selectors: "dl"): HTMLDListElement | null;
querySelector(selectors: "dt"): HTMLElement | null;
querySelector(selectors: "ellipse"): SVGEllipseElement | null;
querySelector(selectors: "em"): HTMLElement | null;
querySelector(selectors: "embed"): HTMLEmbedElement | null;
querySelector(selectors: "feblend"): SVGFEBlendElement | null;
querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null;
querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null;
querySelector(selectors: "fecomposite"): SVGFECompositeElement | null;
querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null;
querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null;
querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null;
querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null;
querySelector(selectors: "feflood"): SVGFEFloodElement | null;
querySelector(selectors: "fefunca"): SVGFEFuncAElement | null;
querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null;
querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null;
querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null;
querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null;
querySelector(selectors: "feimage"): SVGFEImageElement | null;
querySelector(selectors: "femerge"): SVGFEMergeElement | null;
querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null;
querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null;
querySelector(selectors: "feoffset"): SVGFEOffsetElement | null;
querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null;
querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null;
querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null;
querySelector(selectors: "fetile"): SVGFETileElement | null;
querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null;
querySelector(selectors: "fieldset"): HTMLFieldSetElement | null;
querySelector(selectors: "figcaption"): HTMLElement | null;
querySelector(selectors: "figure"): HTMLElement | null;
querySelector(selectors: "filter"): SVGFilterElement | null;
querySelector(selectors: "font"): HTMLFontElement | null;
querySelector(selectors: "footer"): HTMLElement | null;
querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null;
querySelector(selectors: "form"): HTMLFormElement | null;
querySelector(selectors: "frame"): HTMLFrameElement | null;
querySelector(selectors: "frameset"): HTMLFrameSetElement | null;
querySelector(selectors: "g"): SVGGElement | null;
querySelector(selectors: "h1"): HTMLHeadingElement | null;
querySelector(selectors: "h2"): HTMLHeadingElement | null;
querySelector(selectors: "h3"): HTMLHeadingElement | null;
querySelector(selectors: "h4"): HTMLHeadingElement | null;
querySelector(selectors: "h5"): HTMLHeadingElement | null;
querySelector(selectors: "h6"): HTMLHeadingElement | null;
querySelector(selectors: "head"): HTMLHeadElement | null;
querySelector(selectors: "header"): HTMLElement | null;
querySelector(selectors: "hgroup"): HTMLElement | null;
querySelector(selectors: "hr"): HTMLHRElement | null;
querySelector(selectors: "html"): HTMLHtmlElement | null;
querySelector(selectors: "i"): HTMLElement | null;
querySelector(selectors: "iframe"): HTMLIFrameElement | null;
querySelector(selectors: "image"): SVGImageElement | null;
querySelector(selectors: "img"): HTMLImageElement | null;
querySelector(selectors: "input"): HTMLInputElement | null;
querySelector(selectors: "ins"): HTMLModElement | null;
querySelector(selectors: "isindex"): HTMLUnknownElement | null;
querySelector(selectors: "kbd"): HTMLElement | null;
querySelector(selectors: "keygen"): HTMLElement | null;
querySelector(selectors: "label"): HTMLLabelElement | null;
querySelector(selectors: "legend"): HTMLLegendElement | null;
querySelector(selectors: "li"): HTMLLIElement | null;
querySelector(selectors: "line"): SVGLineElement | null;
querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null;
querySelector(selectors: "link"): HTMLLinkElement | null;
querySelector(selectors: "listing"): HTMLPreElement | null;
querySelector(selectors: "map"): HTMLMapElement | null;
querySelector(selectors: "mark"): HTMLElement | null;
querySelector(selectors: "marker"): SVGMarkerElement | null;
querySelector(selectors: "marquee"): HTMLMarqueeElement | null;
querySelector(selectors: "mask"): SVGMaskElement | null;
querySelector(selectors: "menu"): HTMLMenuElement | null;
querySelector(selectors: "meta"): HTMLMetaElement | null;
querySelector(selectors: "metadata"): SVGMetadataElement | null;
querySelector(selectors: "meter"): HTMLMeterElement | null;
querySelector(selectors: "nav"): HTMLElement | null;
querySelector(selectors: "nextid"): HTMLUnknownElement | null;
querySelector(selectors: "nobr"): HTMLElement | null;
querySelector(selectors: "noframes"): HTMLElement | null;
querySelector(selectors: "noscript"): HTMLElement | null;
querySelector(selectors: "object"): HTMLObjectElement | null;
querySelector(selectors: "ol"): HTMLOListElement | null;
querySelector(selectors: "optgroup"): HTMLOptGroupElement | null;
querySelector(selectors: "option"): HTMLOptionElement | null;
querySelector(selectors: "p"): HTMLParagraphElement | null;
querySelector(selectors: "param"): HTMLParamElement | null;
querySelector(selectors: "path"): SVGPathElement | null;
querySelector(selectors: "pattern"): SVGPatternElement | null;
querySelector(selectors: "picture"): HTMLPictureElement | null;
querySelector(selectors: "plaintext"): HTMLElement | null;
querySelector(selectors: "polygon"): SVGPolygonElement | null;
querySelector(selectors: "polyline"): SVGPolylineElement | null;
querySelector(selectors: "pre"): HTMLPreElement | null;
querySelector(selectors: "progress"): HTMLProgressElement | null;
querySelector(selectors: "q"): HTMLQuoteElement | null;
querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null;
querySelector(selectors: "rect"): SVGRectElement | null;
querySelector(selectors: "rt"): HTMLElement | null;
querySelector(selectors: "ruby"): HTMLElement | null;
querySelector(selectors: "s"): HTMLElement | null;
querySelector(selectors: "samp"): HTMLElement | null;
querySelector(selectors: "script"): HTMLScriptElement | null;
querySelector(selectors: "section"): HTMLElement | null;
querySelector(selectors: "select"): HTMLSelectElement | null;
querySelector(selectors: "small"): HTMLElement | null;
querySelector(selectors: "source"): HTMLSourceElement | null;
querySelector(selectors: "span"): HTMLSpanElement | null;
querySelector(selectors: "stop"): SVGStopElement | null;
querySelector(selectors: "strike"): HTMLElement | null;
querySelector(selectors: "strong"): HTMLElement | null;
querySelector(selectors: "style"): HTMLStyleElement | null;
querySelector(selectors: "sub"): HTMLElement | null;
querySelector(selectors: "sup"): HTMLElement | null;
querySelector(selectors: "svg"): SVGSVGElement | null;
querySelector(selectors: "switch"): SVGSwitchElement | null;
querySelector(selectors: "symbol"): SVGSymbolElement | null;
querySelector(selectors: "table"): HTMLTableElement | null;
querySelector(selectors: "tbody"): HTMLTableSectionElement | null;
querySelector(selectors: "td"): HTMLTableDataCellElement | null;
querySelector(selectors: "template"): HTMLTemplateElement | null;
querySelector(selectors: "text"): SVGTextElement | null;
querySelector(selectors: "textpath"): SVGTextPathElement | null;
querySelector(selectors: "textarea"): HTMLTextAreaElement | null;
querySelector(selectors: "tfoot"): HTMLTableSectionElement | null;
querySelector(selectors: "th"): HTMLTableHeaderCellElement | null;
querySelector(selectors: "thead"): HTMLTableSectionElement | null;
querySelector(selectors: "title"): HTMLTitleElement | null;
querySelector(selectors: "tr"): HTMLTableRowElement | null;
querySelector(selectors: "track"): HTMLTrackElement | null;
querySelector(selectors: "tspan"): SVGTSpanElement | null;
querySelector(selectors: "tt"): HTMLElement | null;
querySelector(selectors: "u"): HTMLElement | null;
querySelector(selectors: "ul"): HTMLUListElement | null;
querySelector(selectors: "use"): SVGUseElement | null;
querySelector(selectors: "var"): HTMLElement | null;
querySelector(selectors: "video"): HTMLVideoElement | null;
querySelector(selectors: "view"): SVGViewElement | null;
querySelector(selectors: "wbr"): HTMLElement | null;
querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null;
querySelector(selectors: "xmp"): HTMLPreElement | null;
querySelector(selectors: string): Element | null;
querySelectorAll(selectors: "a"): NodeListOf<HTMLAnchorElement>;
querySelectorAll(selectors: "abbr"): NodeListOf<HTMLElement>;
querySelectorAll(selectors: "acronym"): NodeListOf<HTMLElement>;
@@ -14638,4 +14638,5 @@ type ScrollBehavior = "auto" | "instant" | "smooth";
type ScrollLogicalPosition = "start" | "center" | "end" | "nearest";
type IDBValidKey = number | string | Date | IDBArrayKey;
type BufferSource = ArrayBuffer | ArrayBufferView;
type MouseWheelEvent = WheelEvent;
type MouseWheelEvent = WheelEvent;
type ScrollRestoration = "auto" | "manual";
+1 -1
View File
@@ -217,7 +217,7 @@ interface NumberConstructor {
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
+27
View File
@@ -260,6 +260,9 @@ interface Function {
*/
bind(this: Function, thisArg: any, ...argArray: any[]): any;
/** Returns a string representation of a function. */
toString(): string;
prototype: any;
readonly length: number;
@@ -1216,6 +1219,30 @@ interface Array<T> {
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
+218 -190
View File
@@ -260,6 +260,9 @@ interface Function {
*/
bind(this: Function, thisArg: any, ...argArray: any[]): any;
/** Returns a string representation of a function. */
toString(): string;
prototype: any;
readonly length: number;
@@ -1216,6 +1219,30 @@ interface Array<T> {
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@@ -4325,7 +4352,7 @@ interface NumberConstructor {
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
@@ -13361,11 +13388,12 @@ declare var HashChangeEvent: {
interface History {
readonly length: number;
readonly state: any;
back(distance?: any): void;
forward(distance?: any): void;
go(delta?: any): void;
pushState(statedata: any, title?: string, url?: string): void;
replaceState(statedata: any, title?: string, url?: string): void;
scrollRestoration: ScrollRestoration;
back(): void;
forward(): void;
go(delta?: number): void;
pushState(data: any, title: string, url?: string | null): void;
replaceState(data: any, title: string, url?: string | null): void;
}
declare var History: {
@@ -18937,7 +18965,6 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
[index: number]: Window;
}
declare var Window: {
@@ -18968,7 +18995,7 @@ declare var XMLDocument: {
}
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
onreadystatechange: (this: this, ev: ProgressEvent) => any;
onreadystatechange: (this: this, ev: Event) => any;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
@@ -18995,13 +19022,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -19342,183 +19369,183 @@ interface NavigatorUserMedia {
}
interface NodeSelector {
querySelector(selectors: "a"): HTMLAnchorElement;
querySelector(selectors: "abbr"): HTMLElement;
querySelector(selectors: "acronym"): HTMLElement;
querySelector(selectors: "address"): HTMLElement;
querySelector(selectors: "applet"): HTMLAppletElement;
querySelector(selectors: "area"): HTMLAreaElement;
querySelector(selectors: "article"): HTMLElement;
querySelector(selectors: "aside"): HTMLElement;
querySelector(selectors: "audio"): HTMLAudioElement;
querySelector(selectors: "b"): HTMLElement;
querySelector(selectors: "base"): HTMLBaseElement;
querySelector(selectors: "basefont"): HTMLBaseFontElement;
querySelector(selectors: "bdo"): HTMLElement;
querySelector(selectors: "big"): HTMLElement;
querySelector(selectors: "blockquote"): HTMLQuoteElement;
querySelector(selectors: "body"): HTMLBodyElement;
querySelector(selectors: "br"): HTMLBRElement;
querySelector(selectors: "button"): HTMLButtonElement;
querySelector(selectors: "canvas"): HTMLCanvasElement;
querySelector(selectors: "caption"): HTMLTableCaptionElement;
querySelector(selectors: "center"): HTMLElement;
querySelector(selectors: "circle"): SVGCircleElement;
querySelector(selectors: "cite"): HTMLElement;
querySelector(selectors: "clippath"): SVGClipPathElement;
querySelector(selectors: "code"): HTMLElement;
querySelector(selectors: "col"): HTMLTableColElement;
querySelector(selectors: "colgroup"): HTMLTableColElement;
querySelector(selectors: "datalist"): HTMLDataListElement;
querySelector(selectors: "dd"): HTMLElement;
querySelector(selectors: "defs"): SVGDefsElement;
querySelector(selectors: "del"): HTMLModElement;
querySelector(selectors: "desc"): SVGDescElement;
querySelector(selectors: "dfn"): HTMLElement;
querySelector(selectors: "dir"): HTMLDirectoryElement;
querySelector(selectors: "div"): HTMLDivElement;
querySelector(selectors: "dl"): HTMLDListElement;
querySelector(selectors: "dt"): HTMLElement;
querySelector(selectors: "ellipse"): SVGEllipseElement;
querySelector(selectors: "em"): HTMLElement;
querySelector(selectors: "embed"): HTMLEmbedElement;
querySelector(selectors: "feblend"): SVGFEBlendElement;
querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement;
querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement;
querySelector(selectors: "fecomposite"): SVGFECompositeElement;
querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement;
querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement;
querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement;
querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement;
querySelector(selectors: "feflood"): SVGFEFloodElement;
querySelector(selectors: "fefunca"): SVGFEFuncAElement;
querySelector(selectors: "fefuncb"): SVGFEFuncBElement;
querySelector(selectors: "fefuncg"): SVGFEFuncGElement;
querySelector(selectors: "fefuncr"): SVGFEFuncRElement;
querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement;
querySelector(selectors: "feimage"): SVGFEImageElement;
querySelector(selectors: "femerge"): SVGFEMergeElement;
querySelector(selectors: "femergenode"): SVGFEMergeNodeElement;
querySelector(selectors: "femorphology"): SVGFEMorphologyElement;
querySelector(selectors: "feoffset"): SVGFEOffsetElement;
querySelector(selectors: "fepointlight"): SVGFEPointLightElement;
querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement;
querySelector(selectors: "fespotlight"): SVGFESpotLightElement;
querySelector(selectors: "fetile"): SVGFETileElement;
querySelector(selectors: "feturbulence"): SVGFETurbulenceElement;
querySelector(selectors: "fieldset"): HTMLFieldSetElement;
querySelector(selectors: "figcaption"): HTMLElement;
querySelector(selectors: "figure"): HTMLElement;
querySelector(selectors: "filter"): SVGFilterElement;
querySelector(selectors: "font"): HTMLFontElement;
querySelector(selectors: "footer"): HTMLElement;
querySelector(selectors: "foreignobject"): SVGForeignObjectElement;
querySelector(selectors: "form"): HTMLFormElement;
querySelector(selectors: "frame"): HTMLFrameElement;
querySelector(selectors: "frameset"): HTMLFrameSetElement;
querySelector(selectors: "g"): SVGGElement;
querySelector(selectors: "h1"): HTMLHeadingElement;
querySelector(selectors: "h2"): HTMLHeadingElement;
querySelector(selectors: "h3"): HTMLHeadingElement;
querySelector(selectors: "h4"): HTMLHeadingElement;
querySelector(selectors: "h5"): HTMLHeadingElement;
querySelector(selectors: "h6"): HTMLHeadingElement;
querySelector(selectors: "head"): HTMLHeadElement;
querySelector(selectors: "header"): HTMLElement;
querySelector(selectors: "hgroup"): HTMLElement;
querySelector(selectors: "hr"): HTMLHRElement;
querySelector(selectors: "html"): HTMLHtmlElement;
querySelector(selectors: "i"): HTMLElement;
querySelector(selectors: "iframe"): HTMLIFrameElement;
querySelector(selectors: "image"): SVGImageElement;
querySelector(selectors: "img"): HTMLImageElement;
querySelector(selectors: "input"): HTMLInputElement;
querySelector(selectors: "ins"): HTMLModElement;
querySelector(selectors: "isindex"): HTMLUnknownElement;
querySelector(selectors: "kbd"): HTMLElement;
querySelector(selectors: "keygen"): HTMLElement;
querySelector(selectors: "label"): HTMLLabelElement;
querySelector(selectors: "legend"): HTMLLegendElement;
querySelector(selectors: "li"): HTMLLIElement;
querySelector(selectors: "line"): SVGLineElement;
querySelector(selectors: "lineargradient"): SVGLinearGradientElement;
querySelector(selectors: "link"): HTMLLinkElement;
querySelector(selectors: "listing"): HTMLPreElement;
querySelector(selectors: "map"): HTMLMapElement;
querySelector(selectors: "mark"): HTMLElement;
querySelector(selectors: "marker"): SVGMarkerElement;
querySelector(selectors: "marquee"): HTMLMarqueeElement;
querySelector(selectors: "mask"): SVGMaskElement;
querySelector(selectors: "menu"): HTMLMenuElement;
querySelector(selectors: "meta"): HTMLMetaElement;
querySelector(selectors: "metadata"): SVGMetadataElement;
querySelector(selectors: "meter"): HTMLMeterElement;
querySelector(selectors: "nav"): HTMLElement;
querySelector(selectors: "nextid"): HTMLUnknownElement;
querySelector(selectors: "nobr"): HTMLElement;
querySelector(selectors: "noframes"): HTMLElement;
querySelector(selectors: "noscript"): HTMLElement;
querySelector(selectors: "object"): HTMLObjectElement;
querySelector(selectors: "ol"): HTMLOListElement;
querySelector(selectors: "optgroup"): HTMLOptGroupElement;
querySelector(selectors: "option"): HTMLOptionElement;
querySelector(selectors: "p"): HTMLParagraphElement;
querySelector(selectors: "param"): HTMLParamElement;
querySelector(selectors: "path"): SVGPathElement;
querySelector(selectors: "pattern"): SVGPatternElement;
querySelector(selectors: "picture"): HTMLPictureElement;
querySelector(selectors: "plaintext"): HTMLElement;
querySelector(selectors: "polygon"): SVGPolygonElement;
querySelector(selectors: "polyline"): SVGPolylineElement;
querySelector(selectors: "pre"): HTMLPreElement;
querySelector(selectors: "progress"): HTMLProgressElement;
querySelector(selectors: "q"): HTMLQuoteElement;
querySelector(selectors: "radialgradient"): SVGRadialGradientElement;
querySelector(selectors: "rect"): SVGRectElement;
querySelector(selectors: "rt"): HTMLElement;
querySelector(selectors: "ruby"): HTMLElement;
querySelector(selectors: "s"): HTMLElement;
querySelector(selectors: "samp"): HTMLElement;
querySelector(selectors: "script"): HTMLScriptElement;
querySelector(selectors: "section"): HTMLElement;
querySelector(selectors: "select"): HTMLSelectElement;
querySelector(selectors: "small"): HTMLElement;
querySelector(selectors: "source"): HTMLSourceElement;
querySelector(selectors: "span"): HTMLSpanElement;
querySelector(selectors: "stop"): SVGStopElement;
querySelector(selectors: "strike"): HTMLElement;
querySelector(selectors: "strong"): HTMLElement;
querySelector(selectors: "style"): HTMLStyleElement;
querySelector(selectors: "sub"): HTMLElement;
querySelector(selectors: "sup"): HTMLElement;
querySelector(selectors: "svg"): SVGSVGElement;
querySelector(selectors: "switch"): SVGSwitchElement;
querySelector(selectors: "symbol"): SVGSymbolElement;
querySelector(selectors: "table"): HTMLTableElement;
querySelector(selectors: "tbody"): HTMLTableSectionElement;
querySelector(selectors: "td"): HTMLTableDataCellElement;
querySelector(selectors: "template"): HTMLTemplateElement;
querySelector(selectors: "text"): SVGTextElement;
querySelector(selectors: "textpath"): SVGTextPathElement;
querySelector(selectors: "textarea"): HTMLTextAreaElement;
querySelector(selectors: "tfoot"): HTMLTableSectionElement;
querySelector(selectors: "th"): HTMLTableHeaderCellElement;
querySelector(selectors: "thead"): HTMLTableSectionElement;
querySelector(selectors: "title"): HTMLTitleElement;
querySelector(selectors: "tr"): HTMLTableRowElement;
querySelector(selectors: "track"): HTMLTrackElement;
querySelector(selectors: "tspan"): SVGTSpanElement;
querySelector(selectors: "tt"): HTMLElement;
querySelector(selectors: "u"): HTMLElement;
querySelector(selectors: "ul"): HTMLUListElement;
querySelector(selectors: "use"): SVGUseElement;
querySelector(selectors: "var"): HTMLElement;
querySelector(selectors: "video"): HTMLVideoElement;
querySelector(selectors: "view"): SVGViewElement;
querySelector(selectors: "wbr"): HTMLElement;
querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement;
querySelector(selectors: "xmp"): HTMLPreElement;
querySelector(selectors: string): Element;
querySelector(selectors: "a"): HTMLAnchorElement | null;
querySelector(selectors: "abbr"): HTMLElement | null;
querySelector(selectors: "acronym"): HTMLElement | null;
querySelector(selectors: "address"): HTMLElement | null;
querySelector(selectors: "applet"): HTMLAppletElement | null;
querySelector(selectors: "area"): HTMLAreaElement | null;
querySelector(selectors: "article"): HTMLElement | null;
querySelector(selectors: "aside"): HTMLElement | null;
querySelector(selectors: "audio"): HTMLAudioElement | null;
querySelector(selectors: "b"): HTMLElement | null;
querySelector(selectors: "base"): HTMLBaseElement | null;
querySelector(selectors: "basefont"): HTMLBaseFontElement | null;
querySelector(selectors: "bdo"): HTMLElement | null;
querySelector(selectors: "big"): HTMLElement | null;
querySelector(selectors: "blockquote"): HTMLQuoteElement | null;
querySelector(selectors: "body"): HTMLBodyElement | null;
querySelector(selectors: "br"): HTMLBRElement | null;
querySelector(selectors: "button"): HTMLButtonElement | null;
querySelector(selectors: "canvas"): HTMLCanvasElement | null;
querySelector(selectors: "caption"): HTMLTableCaptionElement | null;
querySelector(selectors: "center"): HTMLElement | null;
querySelector(selectors: "circle"): SVGCircleElement | null;
querySelector(selectors: "cite"): HTMLElement | null;
querySelector(selectors: "clippath"): SVGClipPathElement | null;
querySelector(selectors: "code"): HTMLElement | null;
querySelector(selectors: "col"): HTMLTableColElement | null;
querySelector(selectors: "colgroup"): HTMLTableColElement | null;
querySelector(selectors: "datalist"): HTMLDataListElement | null;
querySelector(selectors: "dd"): HTMLElement | null;
querySelector(selectors: "defs"): SVGDefsElement | null;
querySelector(selectors: "del"): HTMLModElement | null;
querySelector(selectors: "desc"): SVGDescElement | null;
querySelector(selectors: "dfn"): HTMLElement | null;
querySelector(selectors: "dir"): HTMLDirectoryElement | null;
querySelector(selectors: "div"): HTMLDivElement | null;
querySelector(selectors: "dl"): HTMLDListElement | null;
querySelector(selectors: "dt"): HTMLElement | null;
querySelector(selectors: "ellipse"): SVGEllipseElement | null;
querySelector(selectors: "em"): HTMLElement | null;
querySelector(selectors: "embed"): HTMLEmbedElement | null;
querySelector(selectors: "feblend"): SVGFEBlendElement | null;
querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null;
querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null;
querySelector(selectors: "fecomposite"): SVGFECompositeElement | null;
querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null;
querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null;
querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null;
querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null;
querySelector(selectors: "feflood"): SVGFEFloodElement | null;
querySelector(selectors: "fefunca"): SVGFEFuncAElement | null;
querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null;
querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null;
querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null;
querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null;
querySelector(selectors: "feimage"): SVGFEImageElement | null;
querySelector(selectors: "femerge"): SVGFEMergeElement | null;
querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null;
querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null;
querySelector(selectors: "feoffset"): SVGFEOffsetElement | null;
querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null;
querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null;
querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null;
querySelector(selectors: "fetile"): SVGFETileElement | null;
querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null;
querySelector(selectors: "fieldset"): HTMLFieldSetElement | null;
querySelector(selectors: "figcaption"): HTMLElement | null;
querySelector(selectors: "figure"): HTMLElement | null;
querySelector(selectors: "filter"): SVGFilterElement | null;
querySelector(selectors: "font"): HTMLFontElement | null;
querySelector(selectors: "footer"): HTMLElement | null;
querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null;
querySelector(selectors: "form"): HTMLFormElement | null;
querySelector(selectors: "frame"): HTMLFrameElement | null;
querySelector(selectors: "frameset"): HTMLFrameSetElement | null;
querySelector(selectors: "g"): SVGGElement | null;
querySelector(selectors: "h1"): HTMLHeadingElement | null;
querySelector(selectors: "h2"): HTMLHeadingElement | null;
querySelector(selectors: "h3"): HTMLHeadingElement | null;
querySelector(selectors: "h4"): HTMLHeadingElement | null;
querySelector(selectors: "h5"): HTMLHeadingElement | null;
querySelector(selectors: "h6"): HTMLHeadingElement | null;
querySelector(selectors: "head"): HTMLHeadElement | null;
querySelector(selectors: "header"): HTMLElement | null;
querySelector(selectors: "hgroup"): HTMLElement | null;
querySelector(selectors: "hr"): HTMLHRElement | null;
querySelector(selectors: "html"): HTMLHtmlElement | null;
querySelector(selectors: "i"): HTMLElement | null;
querySelector(selectors: "iframe"): HTMLIFrameElement | null;
querySelector(selectors: "image"): SVGImageElement | null;
querySelector(selectors: "img"): HTMLImageElement | null;
querySelector(selectors: "input"): HTMLInputElement | null;
querySelector(selectors: "ins"): HTMLModElement | null;
querySelector(selectors: "isindex"): HTMLUnknownElement | null;
querySelector(selectors: "kbd"): HTMLElement | null;
querySelector(selectors: "keygen"): HTMLElement | null;
querySelector(selectors: "label"): HTMLLabelElement | null;
querySelector(selectors: "legend"): HTMLLegendElement | null;
querySelector(selectors: "li"): HTMLLIElement | null;
querySelector(selectors: "line"): SVGLineElement | null;
querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null;
querySelector(selectors: "link"): HTMLLinkElement | null;
querySelector(selectors: "listing"): HTMLPreElement | null;
querySelector(selectors: "map"): HTMLMapElement | null;
querySelector(selectors: "mark"): HTMLElement | null;
querySelector(selectors: "marker"): SVGMarkerElement | null;
querySelector(selectors: "marquee"): HTMLMarqueeElement | null;
querySelector(selectors: "mask"): SVGMaskElement | null;
querySelector(selectors: "menu"): HTMLMenuElement | null;
querySelector(selectors: "meta"): HTMLMetaElement | null;
querySelector(selectors: "metadata"): SVGMetadataElement | null;
querySelector(selectors: "meter"): HTMLMeterElement | null;
querySelector(selectors: "nav"): HTMLElement | null;
querySelector(selectors: "nextid"): HTMLUnknownElement | null;
querySelector(selectors: "nobr"): HTMLElement | null;
querySelector(selectors: "noframes"): HTMLElement | null;
querySelector(selectors: "noscript"): HTMLElement | null;
querySelector(selectors: "object"): HTMLObjectElement | null;
querySelector(selectors: "ol"): HTMLOListElement | null;
querySelector(selectors: "optgroup"): HTMLOptGroupElement | null;
querySelector(selectors: "option"): HTMLOptionElement | null;
querySelector(selectors: "p"): HTMLParagraphElement | null;
querySelector(selectors: "param"): HTMLParamElement | null;
querySelector(selectors: "path"): SVGPathElement | null;
querySelector(selectors: "pattern"): SVGPatternElement | null;
querySelector(selectors: "picture"): HTMLPictureElement | null;
querySelector(selectors: "plaintext"): HTMLElement | null;
querySelector(selectors: "polygon"): SVGPolygonElement | null;
querySelector(selectors: "polyline"): SVGPolylineElement | null;
querySelector(selectors: "pre"): HTMLPreElement | null;
querySelector(selectors: "progress"): HTMLProgressElement | null;
querySelector(selectors: "q"): HTMLQuoteElement | null;
querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null;
querySelector(selectors: "rect"): SVGRectElement | null;
querySelector(selectors: "rt"): HTMLElement | null;
querySelector(selectors: "ruby"): HTMLElement | null;
querySelector(selectors: "s"): HTMLElement | null;
querySelector(selectors: "samp"): HTMLElement | null;
querySelector(selectors: "script"): HTMLScriptElement | null;
querySelector(selectors: "section"): HTMLElement | null;
querySelector(selectors: "select"): HTMLSelectElement | null;
querySelector(selectors: "small"): HTMLElement | null;
querySelector(selectors: "source"): HTMLSourceElement | null;
querySelector(selectors: "span"): HTMLSpanElement | null;
querySelector(selectors: "stop"): SVGStopElement | null;
querySelector(selectors: "strike"): HTMLElement | null;
querySelector(selectors: "strong"): HTMLElement | null;
querySelector(selectors: "style"): HTMLStyleElement | null;
querySelector(selectors: "sub"): HTMLElement | null;
querySelector(selectors: "sup"): HTMLElement | null;
querySelector(selectors: "svg"): SVGSVGElement | null;
querySelector(selectors: "switch"): SVGSwitchElement | null;
querySelector(selectors: "symbol"): SVGSymbolElement | null;
querySelector(selectors: "table"): HTMLTableElement | null;
querySelector(selectors: "tbody"): HTMLTableSectionElement | null;
querySelector(selectors: "td"): HTMLTableDataCellElement | null;
querySelector(selectors: "template"): HTMLTemplateElement | null;
querySelector(selectors: "text"): SVGTextElement | null;
querySelector(selectors: "textpath"): SVGTextPathElement | null;
querySelector(selectors: "textarea"): HTMLTextAreaElement | null;
querySelector(selectors: "tfoot"): HTMLTableSectionElement | null;
querySelector(selectors: "th"): HTMLTableHeaderCellElement | null;
querySelector(selectors: "thead"): HTMLTableSectionElement | null;
querySelector(selectors: "title"): HTMLTitleElement | null;
querySelector(selectors: "tr"): HTMLTableRowElement | null;
querySelector(selectors: "track"): HTMLTrackElement | null;
querySelector(selectors: "tspan"): SVGTSpanElement | null;
querySelector(selectors: "tt"): HTMLElement | null;
querySelector(selectors: "u"): HTMLElement | null;
querySelector(selectors: "ul"): HTMLUListElement | null;
querySelector(selectors: "use"): SVGUseElement | null;
querySelector(selectors: "var"): HTMLElement | null;
querySelector(selectors: "video"): HTMLVideoElement | null;
querySelector(selectors: "view"): SVGViewElement | null;
querySelector(selectors: "wbr"): HTMLElement | null;
querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null;
querySelector(selectors: "xmp"): HTMLPreElement | null;
querySelector(selectors: string): Element | null;
querySelectorAll(selectors: "a"): NodeListOf<HTMLAnchorElement>;
querySelectorAll(selectors: "abbr"): NodeListOf<HTMLElement>;
querySelectorAll(selectors: "acronym"): NodeListOf<HTMLElement>;
@@ -20448,6 +20475,7 @@ type ScrollLogicalPosition = "start" | "center" | "end" | "nearest";
type IDBValidKey = number | string | Date | IDBArrayKey;
type BufferSource = ArrayBuffer | ArrayBufferView;
type MouseWheelEvent = WheelEvent;
type ScrollRestoration = "auto" | "manual";
/////////////////////////////
/// WorkerGlobalScope APIs
/////////////////////////////
+6 -6
View File
@@ -744,7 +744,7 @@ declare var Worker: {
}
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
onreadystatechange: (this: this, ev: ProgressEvent) => any;
onreadystatechange: (this: this, ev: Event) => any;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
@@ -770,13 +770,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
+1848
View File
File diff suppressed because it is too large Load Diff
+1935 -1642
View File
File diff suppressed because it is too large Load Diff
+6230 -3896
View File
File diff suppressed because it is too large Load Diff
+1851 -505
View File
File diff suppressed because one or more lines are too long
+6082 -3879
View File
File diff suppressed because it is too large Load Diff
+381 -99
View File
File diff suppressed because it is too large Load Diff
+2806 -2123
View File
File diff suppressed because it is too large Load Diff
+381 -99
View File
File diff suppressed because it is too large Load Diff
+2806 -2123
View File
File diff suppressed because it is too large Load Diff
+257 -120
View File
@@ -72,7 +72,6 @@ var ts;
(function (ts) {
ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); };
})(ts || (ts = {}));
var ts;
(function (ts) {
var performance;
(function (performance) {
@@ -790,6 +789,56 @@ var ts;
};
}
ts.memoize = memoize;
function chain(a, b, c, d, e) {
if (e) {
var args_2 = [];
for (var i = 0; i < arguments.length; i++) {
args_2[i] = arguments[i];
}
return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); };
}
else if (d) {
return function (t) { return compose(a(t), b(t), c(t), d(t)); };
}
else if (c) {
return function (t) { return compose(a(t), b(t), c(t)); };
}
else if (b) {
return function (t) { return compose(a(t), b(t)); };
}
else if (a) {
return function (t) { return compose(a(t)); };
}
else {
return function (t) { return function (u) { return u; }; };
}
}
ts.chain = chain;
function compose(a, b, c, d, e) {
if (e) {
var args_3 = [];
for (var i = 0; i < arguments.length; i++) {
args_3[i] = arguments[i];
}
return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); };
}
else if (d) {
return function (t) { return d(c(b(a(t)))); };
}
else if (c) {
return function (t) { return c(b(a(t))); };
}
else if (b) {
return function (t) { return b(a(t)); };
}
else if (a) {
return function (t) { return a(t); };
}
else {
return function (t) { return t; };
}
}
ts.compose = compose;
function formatStringFromArgs(text, args, baseIndex) {
baseIndex = baseIndex || 0;
return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; });
@@ -1537,7 +1586,6 @@ var ts;
this.transformFlags = 0;
this.parent = undefined;
this.original = undefined;
this.transformId = 0;
}
ts.objectAllocator = {
getNodeConstructor: function () { return Node; },
@@ -1550,9 +1598,9 @@ var ts;
};
var Debug;
(function (Debug) {
var currentAssertionLevel;
Debug.currentAssertionLevel = 0;
function shouldAssert(level) {
return getCurrentAssertionLevel() >= level;
return Debug.currentAssertionLevel >= level;
}
Debug.shouldAssert = shouldAssert;
function assert(expression, message, verboseDebugInfo) {
@@ -1570,30 +1618,7 @@ var ts;
Debug.assert(false, message);
}
Debug.fail = fail;
function getCurrentAssertionLevel() {
if (currentAssertionLevel !== undefined) {
return currentAssertionLevel;
}
if (ts.sys === undefined) {
return 0;
}
var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV"));
currentAssertionLevel = developmentMode
? 1
: 0;
return currentAssertionLevel;
}
})(Debug = ts.Debug || (ts.Debug = {}));
function getEnvironmentVariable(name, host) {
if (host && host.getEnvironmentVariable) {
return host.getEnvironmentVariable(name);
}
if (ts.sys && ts.sys.getEnvironmentVariable) {
return ts.sys.getEnvironmentVariable(name);
}
return "";
}
ts.getEnvironmentVariable = getEnvironmentVariable;
function orderedRemoveItemAt(array, index) {
for (var i = index; i < array.length - 1; i++) {
array[i] = array[i + 1];
@@ -1624,6 +1649,60 @@ var ts;
: (function (fileName) { return fileName.toLowerCase(); });
}
ts.createGetCanonicalFileName = createGetCanonicalFileName;
function matchPatternOrExact(patternStrings, candidate) {
var patterns = [];
for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
var patternString = patternStrings_1[_i];
var pattern = tryParsePattern(patternString);
if (pattern) {
patterns.push(pattern);
}
else if (patternString === candidate) {
return patternString;
}
}
return findBestPatternMatch(patterns, function (_) { return _; }, candidate);
}
ts.matchPatternOrExact = matchPatternOrExact;
function patternText(_a) {
var prefix = _a.prefix, suffix = _a.suffix;
return prefix + "*" + suffix;
}
ts.patternText = patternText;
function matchedText(pattern, candidate) {
Debug.assert(isPatternMatch(pattern, candidate));
return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
}
ts.matchedText = matchedText;
function findBestPatternMatch(values, getPattern, candidate) {
var matchedValue = undefined;
var longestMatchPrefixLength = -1;
for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
var v = values_1[_i];
var pattern = getPattern(v);
if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
longestMatchPrefixLength = pattern.prefix.length;
matchedValue = v;
}
}
return matchedValue;
}
ts.findBestPatternMatch = findBestPatternMatch;
function isPatternMatch(_a, candidate) {
var prefix = _a.prefix, suffix = _a.suffix;
return candidate.length >= prefix.length + suffix.length &&
startsWith(candidate, prefix) &&
endsWith(candidate, suffix);
}
function tryParsePattern(pattern) {
Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
var indexOfStar = pattern.indexOf("*");
return indexOfStar === -1 ? undefined : {
prefix: pattern.substr(0, indexOfStar),
suffix: pattern.substr(indexOfStar + 1)
};
}
ts.tryParsePattern = tryParsePattern;
function positionIsSynthesized(pos) {
return !(pos >= 0);
}
@@ -1821,8 +1900,14 @@ var ts;
function isNode4OrLater() {
return parseInt(process.version.charAt(1)) >= 4;
}
function isFileSystemCaseSensitive() {
if (platform === "win32" || platform === "win64") {
return false;
}
return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase());
}
var platform = _os.platform();
var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin";
var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
function readFile(fileName, encoding) {
if (!fileExists(fileName)) {
return undefined;
@@ -1947,6 +2032,9 @@ var ts;
},
watchDirectory: function (directoryName, callback, recursive) {
var options;
if (!directoryExists(directoryName)) {
return;
}
if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) {
options = { persistent: true, recursive: !!recursive };
}
@@ -2090,6 +2178,11 @@ var ts;
}
return sys;
})();
if (ts.sys && ts.sys.getEnvironmentVariable) {
ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
? 1
: 0;
}
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -2414,7 +2507,7 @@ var ts;
The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." },
Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." },
Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" },
All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." },
The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." },
Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." },
Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." },
Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." },
@@ -2575,7 +2668,7 @@ var ts;
this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." },
The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." },
The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." },
Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" },
_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." },
All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." },
Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." },
Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" },
@@ -2809,6 +2902,7 @@ var ts;
Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." },
Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." },
Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." },
Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." },
@@ -2833,6 +2927,7 @@ var ts;
Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." },
Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." },
Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." },
Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." },
You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." },
You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." },
import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." },
@@ -2862,7 +2957,14 @@ var ts;
super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." },
Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." },
Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" },
The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }
The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." },
Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." },
Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." },
Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" },
Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" },
Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" },
Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" },
Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" }
};
})(ts || (ts = {}));
var ts;
@@ -3772,7 +3874,7 @@ var ts;
return token = 69;
}
function scanBinaryOrOctalDigits(base) {
ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8");
ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8");
var value = 0;
var numberOfDigits = 0;
while (true) {
@@ -4844,6 +4946,11 @@ var ts;
name: "importHelpers",
type: "boolean",
description: ts.Diagnostics.Import_emit_helpers_from_tslib
},
{
name: "alwaysStrict",
type: "boolean",
description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
}
];
ts.typingOptionDeclarations = [
@@ -5294,7 +5401,7 @@ var ts;
ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true }
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true }
: {};
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
return options;
@@ -5704,7 +5811,7 @@ var ts;
else if (host.getCurrentDirectory) {
currentDirectory = host.getCurrentDirectory();
}
return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host);
}
ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
function getDefaultTypeRoots(currentDirectory, host) {
@@ -5958,11 +6065,11 @@ var ts;
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
}
matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
}
if (matchedPattern) {
var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName);
var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern);
var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName);
var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern);
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
}
@@ -5988,57 +6095,6 @@ var ts;
return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
}
}
function matchPatternOrExact(patternStrings, candidate) {
var patterns = [];
for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
var patternString = patternStrings_1[_i];
var pattern = tryParsePattern(patternString);
if (pattern) {
patterns.push(pattern);
}
else if (patternString === candidate) {
return patternString;
}
}
return findBestPatternMatch(patterns, function (_) { return _; }, candidate);
}
function patternText(_a) {
var prefix = _a.prefix, suffix = _a.suffix;
return prefix + "*" + suffix;
}
function matchedText(pattern, candidate) {
ts.Debug.assert(isPatternMatch(pattern, candidate));
return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
}
function findBestPatternMatch(values, getPattern, candidate) {
var matchedValue = undefined;
var longestMatchPrefixLength = -1;
for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
var v = values_1[_i];
var pattern = getPattern(v);
if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
longestMatchPrefixLength = pattern.prefix.length;
matchedValue = v;
}
}
return matchedValue;
}
ts.findBestPatternMatch = findBestPatternMatch;
function isPatternMatch(_a, candidate) {
var prefix = _a.prefix, suffix = _a.suffix;
return candidate.length >= prefix.length + suffix.length &&
ts.startsWith(candidate, prefix) &&
ts.endsWith(candidate, suffix);
}
function tryParsePattern(pattern) {
ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern));
var indexOfStar = pattern.indexOf("*");
return indexOfStar === -1 ? undefined : {
prefix: pattern.substr(0, indexOfStar),
suffix: pattern.substr(indexOfStar + 1)
};
}
ts.tryParsePattern = tryParsePattern;
function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
var containingDirectory = ts.getDirectoryPath(containingFile);
var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
@@ -6169,20 +6225,28 @@ var ts;
}
}
function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) {
return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, false);
}
ts.loadModuleFromNodeModules = loadModuleFromNodeModules;
function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) {
return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, false, true);
}
function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) {
directory = ts.normalizeSlashes(directory);
while (true) {
var baseName = ts.getBaseFileName(directory);
if (baseName !== "node_modules") {
var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
return packageResult;
}
else {
var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
if (typesResult || packageResult) {
return typesResult || packageResult;
var packageResult = void 0;
if (!typesOnly) {
packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
return packageResult;
}
}
var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
if (typesResult || packageResult) {
return typesResult || packageResult;
}
}
var parentPath = ts.getDirectoryPath(directory);
if (parentPath === directory || checkOneLevel) {
@@ -6192,7 +6256,6 @@ var ts;
}
return undefined;
}
ts.loadModuleFromNodeModules = loadModuleFromNodeModules;
function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx };
@@ -6205,18 +6268,8 @@ var ts;
}
var referencedSourceFile;
if (moduleHasNonRelativeName(moduleName)) {
while (true) {
var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state);
if (referencedSourceFile) {
break;
}
var parentPath = ts.getDirectoryPath(containingDirectory);
if (parentPath === containingDirectory) {
break;
}
containingDirectory = parentPath;
}
referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) ||
loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state);
}
else {
var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
@@ -6227,6 +6280,20 @@ var ts;
: { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
}
ts.classicNameResolver = classicNameResolver;
function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) {
while (true) {
var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state);
if (referencedSourceFile) {
return referencedSourceFile;
}
var parentPath = ts.getDirectoryPath(containingDirectory);
if (parentPath === containingDirectory) {
return undefined;
}
containingDirectory = parentPath;
}
}
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -6242,6 +6309,36 @@ var ts;
var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
return result.resolvedModule && result.resolvedModule.resolvedFileName;
}
(function (PackageNameValidationResult) {
PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok";
PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported";
PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 2] = "NameTooLong";
PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
})(typingsInstaller.PackageNameValidationResult || (typingsInstaller.PackageNameValidationResult = {}));
var PackageNameValidationResult = typingsInstaller.PackageNameValidationResult;
typingsInstaller.MaxPackageNameLength = 214;
function validatePackageName(packageName) {
ts.Debug.assert(!!packageName, "Package name is not specified");
if (packageName.length > typingsInstaller.MaxPackageNameLength) {
return PackageNameValidationResult.NameTooLong;
}
if (packageName.charCodeAt(0) === 46) {
return PackageNameValidationResult.NameStartsWithDot;
}
if (packageName.charCodeAt(0) === 95) {
return PackageNameValidationResult.NameStartsWithUnderscore;
}
if (/^@[^/]+\/[^/]+$/.test(packageName)) {
return PackageNameValidationResult.ScopedPackagesNotSupported;
}
if (encodeURIComponent(packageName) !== packageName) {
return PackageNameValidationResult.NameContainsNonURISafeCharacters;
}
return PackageNameValidationResult.Ok;
}
typingsInstaller.validatePackageName = validatePackageName;
typingsInstaller.NpmViewRequest = "npm view";
typingsInstaller.NpmInstallRequest = "npm install";
var TypingsInstaller = (function () {
@@ -6364,15 +6461,54 @@ var ts;
}
this.knownCachesSet[cacheLocation] = true;
};
TypingsInstaller.prototype.filterTypings = function (typingsToInstall) {
if (typingsToInstall.length === 0) {
return typingsToInstall;
}
var result = [];
for (var _i = 0, typingsToInstall_1 = typingsToInstall; _i < typingsToInstall_1.length; _i++) {
var typing = typingsToInstall_1[_i];
if (this.missingTypingsSet[typing]) {
continue;
}
var validationResult = validatePackageName(typing);
if (validationResult === PackageNameValidationResult.Ok) {
result.push(typing);
}
else {
this.missingTypingsSet[typing] = true;
if (this.log.isEnabled()) {
switch (validationResult) {
case PackageNameValidationResult.NameTooLong:
this.log.writeLine("Package name '" + typing + "' should be less than " + typingsInstaller.MaxPackageNameLength + " characters");
break;
case PackageNameValidationResult.NameStartsWithDot:
this.log.writeLine("Package name '" + typing + "' cannot start with '.'");
break;
case PackageNameValidationResult.NameStartsWithUnderscore:
this.log.writeLine("Package name '" + typing + "' cannot start with '_'");
break;
case PackageNameValidationResult.ScopedPackagesNotSupported:
this.log.writeLine("Package '" + typing + "' is scoped and currently is not supported");
break;
case PackageNameValidationResult.NameContainsNonURISafeCharacters:
this.log.writeLine("Package name '" + typing + "' contains non URI safe characters");
break;
}
}
}
}
return result;
};
TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) {
var _this = this;
if (this.log.isEnabled()) {
this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall));
}
typingsToInstall = ts.filter(typingsToInstall, function (x) { return !_this.missingTypingsSet[x]; });
typingsToInstall = this.filterTypings(typingsToInstall);
if (typingsToInstall.length === 0) {
if (this.log.isEnabled()) {
this.log.writeLine("All typings are known to be missing - no need to go any further");
this.log.writeLine("All typings are known to be missing or invalid - no need to go any further");
}
return;
}
@@ -6412,8 +6548,8 @@ var ts;
if (_this.log.isEnabled()) {
_this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles));
}
for (var _a = 0, typingsToInstall_1 = typingsToInstall; _a < typingsToInstall_1.length; _a++) {
var toInstall = typingsToInstall_1[_a];
for (var _a = 0, typingsToInstall_2 = typingsToInstall; _a < typingsToInstall_2.length; _a++) {
var toInstall = typingsToInstall_2[_a];
if (!installedPackages[toInstall]) {
if (_this.log.isEnabled()) {
_this.log.writeLine("New missing typing package '" + toInstall + "'");
@@ -6429,8 +6565,8 @@ var ts;
this.installRunCount++;
var execInstallCmdCount = 0;
var filteredTypings = [];
for (var _i = 0, typingsToInstall_2 = typingsToInstall; _i < typingsToInstall_2.length; _i++) {
var typing = typingsToInstall_2[_i];
for (var _i = 0, typingsToInstall_3 = typingsToInstall; _i < typingsToInstall_3.length; _i++) {
var typing = typingsToInstall_3[_i];
execNpmViewTyping(this, typing);
}
function execNpmViewTyping(self, typing) {
@@ -6553,13 +6689,14 @@ var ts;
var NodeTypingsInstaller = (function (_super) {
__extends(NodeTypingsInstaller, _super);
function NodeTypingsInstaller(globalTypingsCacheLocation, throttleLimit, log) {
_super.call(this, globalTypingsCacheLocation, getNPMLocation(process.argv[0]), ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log);
this.installTypingHost = ts.sys;
if (this.log.isEnabled()) {
this.log.writeLine("Process id: " + process.pid);
var _this = _super.call(this, globalTypingsCacheLocation, getNPMLocation(process.argv[0]), ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this;
_this.installTypingHost = ts.sys;
if (_this.log.isEnabled()) {
_this.log.writeLine("Process id: " + process.pid);
}
var exec = require("child_process").exec;
this.exec = exec;
_this.exec = exec;
return _this;
}
NodeTypingsInstaller.prototype.init = function () {
var _this = this;
+150
View File
@@ -0,0 +1,150 @@
/// <reference types="node"/>
import * as ts from "../lib/typescript";
import * as path from "path";
function endsWith(s: string, suffix: string) {
return s.lastIndexOf(suffix, s.length - suffix.length) !== -1;
}
class DeclarationsWalker {
private visitedTypes: ts.Type[] = [];
private text = "";
private constructor(private typeChecker: ts.TypeChecker, private protocolFile: ts.SourceFile) {
}
static getExtraDeclarations(typeChecker: ts.TypeChecker, protocolFile: ts.SourceFile): string {
let text = "declare namespace ts.server.protocol {\n";
var walker = new DeclarationsWalker(typeChecker, protocolFile);
walker.visitTypeNodes(protocolFile);
return walker.text
? `declare namespace ts.server.protocol {\n${walker.text}}`
: "";
}
private processType(type: ts.Type): void {
if (this.visitedTypes.indexOf(type) >= 0) {
return;
}
this.visitedTypes.push(type);
let s = type.aliasSymbol || type.getSymbol();
if (!s) {
return;
}
if (s.name === "Array") {
// we should process type argument instead
return this.processType((<any>type).typeArguments[0]);
}
else {
for (const decl of s.getDeclarations()) {
const sourceFile = decl.getSourceFile();
if (sourceFile === this.protocolFile || path.basename(sourceFile.fileName) === "lib.d.ts") {
return;
}
// splice declaration in final d.ts file
let text = decl.getFullText();
if (decl.kind === ts.SyntaxKind.EnumDeclaration && !(decl.flags & ts.NodeFlags.Const)) {
// patch enum declaration to make them constan
const declStart = decl.getStart() - decl.getFullStart();
const prefix = text.substring(0, declStart);
const suffix = text.substring(declStart + "enum".length, decl.getEnd() - decl.getFullStart());
text = prefix + "const enum" + suffix;
}
this.text += `${text}\n`;
// recursively pull all dependencies into result dts file
this.visitTypeNodes(decl);
}
}
}
private visitTypeNodes(node: ts.Node) {
if (node.parent) {
switch (node.parent.kind) {
case ts.SyntaxKind.VariableDeclaration:
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.MethodSignature:
case ts.SyntaxKind.PropertyDeclaration:
case ts.SyntaxKind.PropertySignature:
case ts.SyntaxKind.Parameter:
case ts.SyntaxKind.IndexSignature:
if (((<ts.VariableDeclaration | ts.MethodDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration | ts.PropertySignature | ts.MethodSignature | ts.IndexSignatureDeclaration>node.parent).type) === node) {
const type = this.typeChecker.getTypeAtLocation(node);
if (type && !(type.flags & ts.TypeFlags.TypeParameter)) {
this.processType(type);
}
}
break;
}
}
ts.forEachChild(node, n => this.visitTypeNodes(n));
}
}
function generateProtocolFile(protocolTs: string, typeScriptServicesDts: string): string {
const options = { target: ts.ScriptTarget.ES5, declaration: true, noResolve: true, types: <string[]>[], stripInternal: true };
/**
* 1st pass - generate a program from protocol.ts and typescriptservices.d.ts and emit core version of protocol.d.ts with all internal members stripped
* @return text of protocol.d.t.s
*/
function getInitialDtsFileForProtocol() {
const program = ts.createProgram([protocolTs, typeScriptServicesDts], options);
let protocolDts: string;
program.emit(program.getSourceFile(protocolTs), (file, content) => {
if (endsWith(file, ".d.ts")) {
protocolDts = content;
}
});
if (protocolDts === undefined) {
throw new Error(`Declaration file for protocol.ts is not generated`)
}
return protocolDts;
}
const protocolFileName = "protocol.d.ts";
/**
* Second pass - generate a program from protocol.d.ts and typescriptservices.d.ts, then augment core protocol.d.ts with extra types from typescriptservices.d.ts
*/
function getProgramWithProtocolText(protocolDts: string, includeTypeScriptServices: boolean) {
const host = ts.createCompilerHost(options);
const originalGetSourceFile = host.getSourceFile;
host.getSourceFile = (fileName) => {
if (fileName === protocolFileName) {
return ts.createSourceFile(fileName, protocolDts, options.target);
}
return originalGetSourceFile.apply(host, [fileName]);
}
const rootFiles = includeTypeScriptServices ? [protocolFileName, typeScriptServicesDts] : [protocolFileName];
return ts.createProgram(rootFiles, options, host);
}
let protocolDts = getInitialDtsFileForProtocol();
const program = getProgramWithProtocolText(protocolDts, /*includeTypeScriptServices*/ true);
const protocolFile = program.getSourceFile("protocol.d.ts");
const extraDeclarations = DeclarationsWalker.getExtraDeclarations(program.getTypeChecker(), protocolFile);
if (extraDeclarations) {
protocolDts += extraDeclarations;
}
// do sanity check and try to compile generated text as standalone program
const sanityCheckProgram = getProgramWithProtocolText(protocolDts, /*includeTypeScriptServices*/ false);
const diagnostics = [...program.getSyntacticDiagnostics(), ...program.getSemanticDiagnostics(), ...program.getGlobalDiagnostics()];
if (diagnostics.length) {
const flattenedDiagnostics = diagnostics.map(d => ts.flattenDiagnosticMessageText(d.messageText, "\n")).join("\n");
throw new Error(`Unexpected errors during sanity check: ${flattenedDiagnostics}`);
}
return protocolDts;
}
if (process.argv.length < 5) {
console.log(`Expected 3 arguments: path to 'protocol.ts', path to 'typescriptservices.d.ts' and path to output file`);
process.exit(1);
}
const protocolTs = process.argv[2];
const typeScriptServicesDts = process.argv[3];
const outputFile = process.argv[4];
const generatedProtocolDts = generateProtocolFile(protocolTs, typeScriptServicesDts);
ts.sys.writeFile(outputFile, generatedProtocolDts);
+1 -1
View File
@@ -86,7 +86,7 @@ function buildInfoFileOutput(messageTable: InputDiagnosticMessageTable, nameMap:
'/// <reference path="types.ts" />\r\n' +
'/* @internal */\r\n' +
'namespace ts {\r\n' +
' export var Diagnostics = {\r\n';
' export const Diagnostics = {\r\n';
var names = Utilities.getObjectKeys(messageTable);
for (var i = 0; i < names.length; i++) {
var name = names[i];
+1 -1
View File
@@ -126,7 +126,7 @@ class PreferConstWalker extends Lint.RuleWalker {
visitModuleDeclaration(node: ts.ModuleDeclaration) {
if (node.body.kind === ts.SyntaxKind.ModuleBlock) {
// For some reason module blocks are left out of the visit block traversal
this.visitBlock(node.body as ts.ModuleBlock);
this.visitBlock(node.body as any as ts.Block);
}
super.visitModuleDeclaration(node);
}
+7 -2
View File
@@ -18,8 +18,13 @@ class TypeOperatorSpacingWalker extends Lint.RuleWalker {
for (let i = 1; i < types.length; i++) {
const currentType = types[i];
if (expectedStart !== currentType.pos || currentType.getLeadingTriviaWidth() !== 1) {
const failure = this.createFailure(currentType.pos, currentType.getWidth(), Rule.FAILURE_STRING);
this.addFailure(failure);
const sourceFile = currentType.getSourceFile();
const previousTypeEndPos = sourceFile.getLineAndCharacterOfPosition(types[i - 1].end);
const currentTypeStartPos = sourceFile.getLineAndCharacterOfPosition(currentType.pos);
if (previousTypeEndPos.line === currentTypeStartPos.line) {
const failure = this.createFailure(currentType.pos, currentType.getWidth(), Rule.FAILURE_STRING);
this.addFailure(failure);
}
}
expectedStart = currentType.end + 2;
}
+228 -100
View File
@@ -84,6 +84,7 @@ namespace ts {
IsFunctionExpression = 1 << 4,
HasLocals = 1 << 5,
IsInterface = 1 << 6,
IsObjectLiteralOrClassExpressionMethod = 1 << 7,
}
const binder = createBinder();
@@ -121,7 +122,8 @@ namespace ts {
// If this file is an external module, then it is automatically in strict-mode according to
// ES6. If it is not an external module, then we'll determine if it is in strict mode or
// not depending on if we see "use strict" in certain places (or if we hit a class/namespace).
// not depending on if we see "use strict" in certain places or if we hit a class/namespace
// or if compiler options contain alwaysStrict.
let inStrictMode: boolean;
let symbolCount = 0;
@@ -139,7 +141,7 @@ namespace ts {
file = f;
options = opts;
languageVersion = getEmitScriptTarget(options);
inStrictMode = !!file.externalModuleIndicator;
inStrictMode = bindInStrictMode(file, opts);
classifiableNames = createMap<string>();
symbolCount = 0;
skipTransformFlagAggregation = isDeclarationFile(file);
@@ -174,6 +176,16 @@ namespace ts {
return bindSourceFile;
function bindInStrictMode(file: SourceFile, opts: CompilerOptions): boolean {
if (opts.alwaysStrict && !isDeclarationFile(file)) {
// bind in strict mode source files with alwaysStrict option
return true;
}
else {
return !!file.externalModuleIndicator;
}
}
function createSymbol(flags: SymbolFlags, name: string): Symbol {
symbolCount++;
return new Symbol(flags, name);
@@ -355,11 +367,24 @@ namespace ts {
? Diagnostics.Cannot_redeclare_block_scoped_variable_0
: Diagnostics.Duplicate_identifier_0;
forEach(symbol.declarations, declaration => {
if (hasModifier(declaration, ModifierFlags.Default)) {
if (symbol.declarations && symbol.declarations.length) {
// If the current node is a default export of some sort, then check if
// there are any other default exports that we need to error on.
// We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
if (isDefaultExport) {
message = Diagnostics.A_module_cannot_have_multiple_default_exports;
}
});
else {
// This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
// Error on multiple export default in the following case:
// 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
// 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
if (symbol.declarations && symbol.declarations.length &&
(isDefaultExport || (node.kind === SyntaxKind.ExportAssignment && !(<ExportAssignment>node).isExportEquals))) {
message = Diagnostics.A_module_cannot_have_multiple_default_exports;
}
}
}
forEach(symbol.declarations, declaration => {
file.bindDiagnostics.push(createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration)));
@@ -473,8 +498,8 @@ namespace ts {
}
else {
currentFlow = { flags: FlowFlags.Start };
if (containerFlags & ContainerFlags.IsFunctionExpression) {
(<FlowStart>currentFlow).container = <FunctionExpression | ArrowFunction>node;
if (containerFlags & (ContainerFlags.IsFunctionExpression | ContainerFlags.IsObjectLiteralOrClassExpressionMethod)) {
(<FlowStart>currentFlow).container = <FunctionExpression | ArrowFunction | MethodDeclaration>node;
}
currentReturnTarget = undefined;
}
@@ -760,6 +785,15 @@ namespace ts {
};
}
function createFlowArrayMutation(antecedent: FlowNode, node: CallExpression | BinaryExpression): FlowNode {
setFlowNodeReferenced(antecedent);
return <FlowArrayMutation>{
flags: FlowFlags.ArrayMutation,
antecedent,
node
};
}
function finishFlowLabel(flow: FlowLabel): FlowNode {
const antecedents = flow.antecedents;
if (!antecedents) {
@@ -950,24 +984,44 @@ namespace ts {
}
function bindTryStatement(node: TryStatement): void {
const postFinallyLabel = createBranchLabel();
const preFinallyLabel = createBranchLabel();
const preTryFlow = currentFlow;
// TODO: Every statement in try block is potentially an exit point!
bind(node.tryBlock);
addAntecedent(postFinallyLabel, currentFlow);
addAntecedent(preFinallyLabel, currentFlow);
const flowAfterTry = currentFlow;
let flowAfterCatch = unreachableFlow;
if (node.catchClause) {
currentFlow = preTryFlow;
bind(node.catchClause);
addAntecedent(postFinallyLabel, currentFlow);
addAntecedent(preFinallyLabel, currentFlow);
flowAfterCatch = currentFlow;
}
if (node.finallyBlock) {
currentFlow = preTryFlow;
// in finally flow is combined from pre-try/flow from try/flow from catch
// pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable
addAntecedent(preFinallyLabel, preTryFlow);
currentFlow = finishFlowLabel(preFinallyLabel);
bind(node.finallyBlock);
// if flow after finally is unreachable - keep it
// otherwise check if flows after try and after catch are unreachable
// if yes - convert current flow to unreachable
// i.e.
// try { return "1" } finally { console.log(1); }
// console.log(2); // this line should be unreachable even if flow falls out of finally block
if (!(currentFlow.flags & FlowFlags.Unreachable)) {
if ((flowAfterTry.flags & FlowFlags.Unreachable) && (flowAfterCatch.flags & FlowFlags.Unreachable)) {
currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow
? reportedUnreachableFlow
: unreachableFlow;
}
}
}
// if try statement has finally block and flow after finally block is unreachable - keep it
// otherwise use whatever flow was accumulated at postFinallyLabel
if (!node.finallyBlock || !(currentFlow.flags & FlowFlags.Unreachable)) {
currentFlow = finishFlowLabel(postFinallyLabel);
else {
currentFlow = finishFlowLabel(preFinallyLabel);
}
}
@@ -1111,7 +1165,7 @@ namespace ts {
}
else {
forEachChild(node, bind);
if (node.operator === SyntaxKind.PlusEqualsToken || node.operator === SyntaxKind.MinusMinusToken) {
if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) {
bindAssignmentTargetFlow(node.operand);
}
}
@@ -1140,6 +1194,12 @@ namespace ts {
forEachChild(node, bind);
if (operator === SyntaxKind.EqualsToken && !isAssignmentTarget(node)) {
bindAssignmentTargetFlow(node.left);
if (node.left.kind === SyntaxKind.ElementAccessExpression) {
const elementAccess = <ElementAccessExpression>node.left;
if (isNarrowableOperand(elementAccess.expression)) {
currentFlow = createFlowArrayMutation(currentFlow, node);
}
}
}
}
}
@@ -1200,6 +1260,12 @@ namespace ts {
else {
forEachChild(node, bind);
}
if (node.expression.kind === SyntaxKind.PropertyAccessExpression) {
const propertyAccess = <PropertyAccessExpression>node.expression;
if (isNarrowableOperand(propertyAccess.expression) && isPushOrUnshiftIdentifier(propertyAccess.name)) {
currentFlow = createFlowArrayMutation(currentFlow, node);
}
}
}
function getContainerFlags(node: Node): ContainerFlags {
@@ -1224,9 +1290,12 @@ namespace ts {
case SyntaxKind.SourceFile:
return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals;
case SyntaxKind.MethodDeclaration:
if (isObjectLiteralOrClassExpressionMethod(node)) {
return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals | ContainerFlags.IsFunctionLike | ContainerFlags.IsObjectLiteralOrClassExpressionMethod;
}
case SyntaxKind.Constructor:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
@@ -1360,7 +1429,7 @@ namespace ts {
function hasExportDeclarations(node: ModuleDeclaration | SourceFile): boolean {
const body = node.kind === SyntaxKind.SourceFile ? node : (<ModuleDeclaration>node).body;
if (body && (body.kind === SyntaxKind.SourceFile || body.kind === SyntaxKind.ModuleBlock)) {
for (const stat of (<Block>body).statements) {
for (const stat of (<BlockLike>body).statements) {
if (stat.kind === SyntaxKind.ExportDeclaration || stat.kind === SyntaxKind.ExportAssignment) {
return true;
}
@@ -1636,7 +1705,7 @@ namespace ts {
}
function checkStrictModeFunctionDeclaration(node: FunctionDeclaration) {
if (languageVersion < ScriptTarget.ES6) {
if (languageVersion < ScriptTarget.ES2015) {
// Report error if function is not top level function declaration
if (blockScopeContainer.kind !== SyntaxKind.SourceFile &&
blockScopeContainer.kind !== SyntaxKind.ModuleDeclaration &&
@@ -1944,12 +2013,15 @@ namespace ts {
bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node));
}
else {
// An export default clause with an expression exports a value
// We want to exclude both class and function here, this is necessary to issue an error when there are both
// default export-assignment and default export function and class declaration.
const flags = node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(<ExportAssignment>node)
// An export default clause with an EntityNameExpression exports all meanings of that identifier
? SymbolFlags.Alias
// An export default clause with any other expression exports a value
: SymbolFlags.Property;
declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes);
declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.Property | SymbolFlags.AliasExcludes | SymbolFlags.Class | SymbolFlags.Function);
}
}
@@ -2209,9 +2281,9 @@ namespace ts {
if (currentFlow) {
node.flowNode = currentFlow;
}
checkStrictModeFunctionName(<FunctionExpression>node);
const bindingName = (<FunctionExpression>node).name ? (<FunctionExpression>node).name.text : "__function";
return bindAnonymousDeclaration(<FunctionExpression>node, SymbolFlags.Function, bindingName);
checkStrictModeFunctionName(node);
const bindingName = node.name ? node.name.text : "__function";
return bindAnonymousDeclaration(node, SymbolFlags.Function, bindingName);
}
function bindPropertyOrMethodOrAccessor(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) {
@@ -2224,6 +2296,10 @@ namespace ts {
}
}
if (currentFlow && isObjectLiteralOrClassExpressionMethod(node)) {
node.flowNode = currentFlow;
}
return hasDynamicName(node)
? bindAnonymousDeclaration(node, symbolFlags, "__computed")
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
@@ -2297,6 +2373,9 @@ namespace ts {
case SyntaxKind.CallExpression:
return computeCallExpression(<CallExpression>node, subtreeFlags);
case SyntaxKind.NewExpression:
return computeNewExpression(<NewExpression>node, subtreeFlags);
case SyntaxKind.ModuleDeclaration:
return computeModuleDeclaration(<ModuleDeclaration>node, subtreeFlags);
@@ -2374,11 +2453,15 @@ namespace ts {
const expression = node.expression;
const expressionKind = expression.kind;
if (node.typeArguments) {
transformFlags |= TransformFlags.AssertTypeScript;
}
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression
|| isSuperOrSuperProperty(expression, expressionKind)) {
// If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2400,6 +2483,21 @@ namespace ts {
return false;
}
function computeNewExpression(node: NewExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
if (node.typeArguments) {
transformFlags |= TransformFlags.AssertTypeScript;
}
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) {
// If the this node contains a SpreadElementExpression then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES2015;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.ArrayLiteralOrCallOrNewExcludes;
}
function computeBinaryExpression(node: BinaryExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const operatorTokenKind = node.operatorToken.kind;
@@ -2409,12 +2507,12 @@ namespace ts {
&& (leftKind === SyntaxKind.ObjectLiteralExpression
|| leftKind === SyntaxKind.ArrayLiteralExpression)) {
// Destructuring assignments are ES6 syntax.
transformFlags |= TransformFlags.AssertES6 | TransformFlags.DestructuringAssignment;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.DestructuringAssignment;
}
else if (operatorTokenKind === SyntaxKind.AsteriskAsteriskToken
|| operatorTokenKind === SyntaxKind.AsteriskAsteriskEqualsToken) {
// Exponentiation is ES7 syntax.
transformFlags |= TransformFlags.AssertES7;
// Exponentiation is ES2016 syntax.
transformFlags |= TransformFlags.AssertES2016;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2428,14 +2526,12 @@ namespace ts {
const initializer = node.initializer;
const dotDotDotToken = node.dotDotDotToken;
// If the parameter has a question token, then it is TypeScript syntax.
if (node.questionToken) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// If the parameter's name is 'this', then it is TypeScript syntax.
if (subtreeFlags & TransformFlags.ContainsDecorators
|| (name && isIdentifier(name) && name.originalKeywordKind === SyntaxKind.ThisKeyword)) {
// The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript
// syntax.
if (node.questionToken
|| node.type
|| subtreeFlags & TransformFlags.ContainsDecorators
|| isThisIdentifier(name)) {
transformFlags |= TransformFlags.AssertTypeScript;
}
@@ -2447,7 +2543,7 @@ namespace ts {
// If a parameter has an initializer, a binding pattern or a dotDotDot token, then
// it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
if (subtreeFlags & TransformFlags.ContainsBindingPattern || initializer || dotDotDotToken) {
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsDefaultValueAssignments;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsDefaultValueAssignments;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2488,13 +2584,14 @@ namespace ts {
}
else {
// A ClassDeclaration is ES6 syntax.
transformFlags = subtreeFlags | TransformFlags.AssertES6;
transformFlags = subtreeFlags | TransformFlags.AssertES2015;
// A class with a parameter property assignment, property initializer, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax.
if ((subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask)
|| (modifierFlags & ModifierFlags.Export)) {
|| (modifierFlags & ModifierFlags.Export)
|| node.typeParameters) {
transformFlags |= TransformFlags.AssertTypeScript;
}
@@ -2511,11 +2608,12 @@ namespace ts {
function computeClassExpression(node: ClassExpression, subtreeFlags: TransformFlags) {
// A ClassExpression is ES6 syntax.
let transformFlags = subtreeFlags | TransformFlags.AssertES6;
let transformFlags = subtreeFlags | TransformFlags.AssertES2015;
// A class with a parameter property assignment, property initializer, or decorator is
// TypeScript syntax.
if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask) {
if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask
|| node.typeParameters) {
transformFlags |= TransformFlags.AssertTypeScript;
}
@@ -2535,7 +2633,7 @@ namespace ts {
switch (node.token) {
case SyntaxKind.ExtendsKeyword:
// An `extends` HeritageClause is ES6 syntax.
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
break;
case SyntaxKind.ImplementsKeyword:
@@ -2555,7 +2653,7 @@ namespace ts {
function computeExpressionWithTypeArguments(node: ExpressionWithTypeArguments, subtreeFlags: TransformFlags) {
// An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
// extends clause of a class.
let transformFlags = subtreeFlags | TransformFlags.AssertES6;
let transformFlags = subtreeFlags | TransformFlags.AssertES2015;
// If an ExpressionWithTypeArguments contains type arguments, then it
// is TypeScript syntax.
@@ -2569,10 +2667,10 @@ namespace ts {
function computeConstructor(node: ConstructorDeclaration, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const body = node.body;
if (body === undefined) {
// An overload constructor is TypeScript syntax.
// TypeScript-specific modifiers and overloads are TypeScript syntax
if (hasModifier(node, ModifierFlags.TypeScriptModifier)
|| !node.body) {
transformFlags |= TransformFlags.AssertTypeScript;
}
@@ -2582,23 +2680,25 @@ namespace ts {
function computeMethod(node: MethodDeclaration, subtreeFlags: TransformFlags) {
// A MethodDeclaration is ES6 syntax.
let transformFlags = subtreeFlags | TransformFlags.AssertES6;
const modifierFlags = getModifierFlags(node);
const body = node.body;
const typeParameters = node.typeParameters;
const asteriskToken = node.asteriskToken;
let transformFlags = subtreeFlags | TransformFlags.AssertES2015;
// A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded,
// generic, or has a decorator.
if (!body
|| typeParameters
|| (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract))
|| (subtreeFlags & TransformFlags.ContainsDecorators)) {
// Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
// overloads are TypeScript syntax.
if (node.decorators
|| hasModifier(node, ModifierFlags.TypeScriptModifier)
|| node.typeParameters
|| node.type
|| !node.body) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// An async method declaration is ES2017 syntax.
if (hasModifier(node, ModifierFlags.Async)) {
transformFlags |= TransformFlags.AssertES2017;
}
// Currently, we only support generators that were originally async function bodies.
if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
transformFlags |= TransformFlags.AssertGenerator;
}
@@ -2608,14 +2708,13 @@ namespace ts {
function computeAccessor(node: AccessorDeclaration, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const modifierFlags = getModifierFlags(node);
const body = node.body;
// A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded,
// generic, or has a decorator.
if (!body
|| (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract))
|| (subtreeFlags & TransformFlags.ContainsDecorators)) {
// Decorators, TypeScript-specific modifiers, type annotations, and overloads are
// TypeScript syntax.
if (node.decorators
|| hasModifier(node, ModifierFlags.TypeScriptModifier)
|| node.type
|| !node.body) {
transformFlags |= TransformFlags.AssertTypeScript;
}
@@ -2641,7 +2740,6 @@ namespace ts {
let transformFlags: TransformFlags;
const modifierFlags = getModifierFlags(node);
const body = node.body;
const asteriskToken = node.asteriskToken;
if (!body || (modifierFlags & ModifierFlags.Ambient)) {
// An ambient declaration is TypeScript syntax.
@@ -2653,19 +2751,27 @@ namespace ts {
// If a FunctionDeclaration is exported, then it is either ES6 or TypeScript syntax.
if (modifierFlags & ModifierFlags.Export) {
transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES2015;
}
// If a FunctionDeclaration is async, then it is TypeScript syntax.
if (modifierFlags & ModifierFlags.Async) {
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (modifierFlags & ModifierFlags.TypeScriptModifier
|| node.typeParameters
|| node.type) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// An async function declaration is ES2017 syntax.
if (modifierFlags & ModifierFlags.Async) {
transformFlags |= TransformFlags.AssertES2017;
}
// If a FunctionDeclaration's subtree has marked the container as needing to capture the
// lexical this, or the function contains parameters with initializers, then this node is
// ES6 syntax.
if (subtreeFlags & TransformFlags.ES6FunctionSyntaxMask) {
transformFlags |= TransformFlags.AssertES6;
if (subtreeFlags & TransformFlags.ES2015FunctionSyntaxMask) {
transformFlags |= TransformFlags.AssertES2015;
}
// If a FunctionDeclaration is generator function and is the body of a
@@ -2673,7 +2779,7 @@ namespace ts {
// down-level generator.
// Currently we do not support transforming any other generator fucntions
// down level.
if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
transformFlags |= TransformFlags.AssertGenerator;
}
}
@@ -2684,19 +2790,25 @@ namespace ts {
function computeFunctionExpression(node: FunctionExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const modifierFlags = getModifierFlags(node);
const asteriskToken = node.asteriskToken;
// An async function expression is TypeScript syntax.
if (modifierFlags & ModifierFlags.Async) {
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (hasModifier(node, ModifierFlags.TypeScriptModifier)
|| node.typeParameters
|| node.type) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// An async function expression is ES2017 syntax.
if (hasModifier(node, ModifierFlags.Async)) {
transformFlags |= TransformFlags.AssertES2017;
}
// If a FunctionExpression's subtree has marked the container as needing to capture the
// lexical this, or the function contains parameters with initializers, then this node is
// ES6 syntax.
if (subtreeFlags & TransformFlags.ES6FunctionSyntaxMask) {
transformFlags |= TransformFlags.AssertES6;
if (subtreeFlags & TransformFlags.ES2015FunctionSyntaxMask) {
transformFlags |= TransformFlags.AssertES2015;
}
// If a FunctionExpression is generator function and is the body of a
@@ -2704,7 +2816,7 @@ namespace ts {
// down-level generator.
// Currently we do not support transforming any other generator fucntions
// down level.
if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
transformFlags |= TransformFlags.AssertGenerator;
}
@@ -2714,14 +2826,21 @@ namespace ts {
function computeArrowFunction(node: ArrowFunction, subtreeFlags: TransformFlags) {
// An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
let transformFlags = subtreeFlags | TransformFlags.AssertES6;
const modifierFlags = getModifierFlags(node);
let transformFlags = subtreeFlags | TransformFlags.AssertES2015;
// An async arrow function is TypeScript syntax.
if (modifierFlags & ModifierFlags.Async) {
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (hasModifier(node, ModifierFlags.TypeScriptModifier)
|| node.typeParameters
|| node.type) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// An async arrow function is ES2017 syntax.
if (hasModifier(node, ModifierFlags.Async)) {
transformFlags |= TransformFlags.AssertES2017;
}
// If an ArrowFunction contains a lexical this, its container must capture the lexical this.
if (subtreeFlags & TransformFlags.ContainsLexicalThis) {
transformFlags |= TransformFlags.ContainsCapturedLexicalThis;
@@ -2752,7 +2871,12 @@ namespace ts {
// A VariableDeclaration with a binding pattern is ES6 syntax.
if (nameKind === SyntaxKind.ObjectBindingPattern || nameKind === SyntaxKind.ArrayBindingPattern) {
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
}
// Type annotations are TypeScript syntax.
if (node.type) {
transformFlags |= TransformFlags.AssertTypeScript;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2773,11 +2897,11 @@ namespace ts {
// If a VariableStatement is exported, then it is either ES6 or TypeScript syntax.
if (modifierFlags & ModifierFlags.Export) {
transformFlags |= TransformFlags.AssertES6 | TransformFlags.AssertTypeScript;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.AssertTypeScript;
}
if (declarationListTransformFlags & TransformFlags.ContainsBindingPattern) {
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
}
@@ -2791,7 +2915,7 @@ namespace ts {
// A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding
&& isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2817,7 +2941,7 @@ namespace ts {
// then we treat the statement as ES6 so that we can indicate that we do not
// need to hold on to the right-hand side.
if (node.expression.transformFlags & TransformFlags.DestructuringAssignment) {
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2840,12 +2964,12 @@ namespace ts {
let transformFlags = subtreeFlags | TransformFlags.ContainsHoistedDeclarationOrCompletion;
if (subtreeFlags & TransformFlags.ContainsBindingPattern) {
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
// If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
if (node.flags & NodeFlags.BlockScoped) {
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBlockScopedBinding;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBlockScopedBinding;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2858,14 +2982,18 @@ namespace ts {
let excludeFlags = TransformFlags.NodeExcludes;
switch (kind) {
case SyntaxKind.AsyncKeyword:
case SyntaxKind.AwaitExpression:
// async/await is ES2017 syntax
transformFlags |= TransformFlags.AssertES2017;
break;
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.AbstractKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.AsyncKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.AwaitExpression:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMember:
case SyntaxKind.TypeAssertionExpression:
@@ -2890,7 +3018,7 @@ namespace ts {
case SyntaxKind.ExportKeyword:
// This node is both ES6 and TypeScript syntax.
transformFlags |= TransformFlags.AssertES6 | TransformFlags.AssertTypeScript;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.AssertTypeScript;
break;
case SyntaxKind.DefaultKeyword:
@@ -2903,12 +3031,12 @@ namespace ts {
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.ForOfStatement:
// These nodes are ES6 syntax.
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
break;
case SyntaxKind.YieldExpression:
// This node is ES6 syntax.
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsYield;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsYield;
break;
case SyntaxKind.AnyKeyword:
@@ -2969,7 +3097,7 @@ namespace ts {
case SyntaxKind.SuperKeyword:
// This node is ES6 syntax.
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
break;
case SyntaxKind.ThisKeyword:
@@ -2980,7 +3108,7 @@ namespace ts {
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
// These nodes are ES6 syntax.
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
break;
case SyntaxKind.Decorator:
@@ -2993,7 +3121,7 @@ namespace ts {
if (subtreeFlags & TransformFlags.ContainsComputedPropertyName) {
// If an ObjectLiteralExpression contains a ComputedPropertyName, then it
// is an ES6 node.
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) {
@@ -3010,7 +3138,7 @@ namespace ts {
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) {
// If the this node contains a SpreadElementExpression, then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
break;
@@ -3021,14 +3149,14 @@ namespace ts {
case SyntaxKind.ForInStatement:
// A loop containing a block scoped binding *may* need to be transformed from ES6.
if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding) {
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
break;
case SyntaxKind.SourceFile:
if (subtreeFlags & TransformFlags.ContainsCapturedLexicalThis) {
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
break;
+372 -116
View File
File diff suppressed because it is too large Load Diff
+10 -3
View File
@@ -101,7 +101,7 @@ namespace ts {
"amd": ModuleKind.AMD,
"system": ModuleKind.System,
"umd": ModuleKind.UMD,
"es6": ModuleKind.ES6,
"es6": ModuleKind.ES2015,
"es2015": ModuleKind.ES2015,
}),
description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015,
@@ -261,8 +261,10 @@ namespace ts {
type: createMap({
"es3": ScriptTarget.ES3,
"es5": ScriptTarget.ES5,
"es6": ScriptTarget.ES6,
"es6": ScriptTarget.ES2015,
"es2015": ScriptTarget.ES2015,
"es2016": ScriptTarget.ES2016,
"es2017": ScriptTarget.ES2017,
}),
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015,
paramType: Diagnostics.VERSION,
@@ -444,6 +446,11 @@ namespace ts {
name: "importHelpers",
type: "boolean",
description: Diagnostics.Import_emit_helpers_from_tslib
},
{
name: "alwaysStrict",
type: "boolean",
description: Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
}
];
@@ -975,7 +982,7 @@ namespace ts {
basePath: string, errors: Diagnostic[], configFileName?: string): CompilerOptions {
const options: CompilerOptions = getBaseFileName(configFileName) === "jsconfig.json"
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true }
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true }
: {};
convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_compiler_option_0, errors);
return options;
+59 -41
View File
@@ -20,6 +20,9 @@ namespace ts {
const createObject = Object.create;
// More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times.
export const collator: { compare(a: string, b: string): number } = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined;
export function createMap<T>(template?: MapLike<T>): Map<T> {
const map: Map<T> = createObject(null); // tslint:disable-line:no-null-keyword
@@ -212,7 +215,7 @@ namespace ts {
* true for all elements, otherwise returns a new array instance containing the filtered subset.
*/
export function filter<T, U extends T>(array: T[], f: (x: T) => x is U): U[];
export function filter<T>(array: T[], f: (x: T) => boolean): T[]
export function filter<T>(array: T[], f: (x: T) => boolean): T[];
export function filter<T>(array: T[], f: (x: T) => boolean): T[] {
if (array) {
const len = array.length;
@@ -265,13 +268,33 @@ namespace ts {
if (array) {
result = [];
for (let i = 0; i < array.length; i++) {
const v = array[i];
result.push(f(v, i));
result.push(f(array[i], i));
}
}
return result;
}
// Maps from T to T and avoids allocation if all elements map to themselves
export function sameMap<T>(array: T[], f: (x: T, i: number) => T): T[] {
let result: T[];
if (array) {
for (let i = 0; i < array.length; i++) {
if (result) {
result.push(f(array[i], i));
}
else {
const item = array[i];
const mapped = f(item, i);
if (item !== mapped) {
result = array.slice(0, i);
result.push(mapped);
}
}
}
}
return result || array;
}
/**
* Flattens an array containing a mix of array or non-array elements.
*
@@ -399,6 +422,17 @@ namespace ts {
return result;
}
export function some<T>(array: T[], predicate?: (value: T) => boolean): boolean {
if (array) {
for (const v of array) {
if (!predicate || predicate(v)) {
return true;
}
}
}
return false;
}
export function concatenate<T>(array1: T[], array2: T[]): T[] {
if (!array2 || !array2.length) return array1;
if (!array1 || !array1.length) return array2;
@@ -1016,7 +1050,8 @@ namespace ts {
if (a === undefined) return Comparison.LessThan;
if (b === undefined) return Comparison.GreaterThan;
if (ignoreCase) {
if (String.prototype.localeCompare) {
if (collator && String.prototype.localeCompare) {
// accent means a ≠ b, a ≠ á, a = A
const result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" });
return result < 0 ? Comparison.LessThan : result > 0 ? Comparison.GreaterThan : Comparison.EqualTo;
}
@@ -1097,7 +1132,9 @@ namespace ts {
return path.replace(/\\/g, "/");
}
// Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files")
/**
* Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files")
*/
export function getRootLength(path: string): number {
if (path.charCodeAt(0) === CharacterCodes.slash) {
if (path.charCodeAt(1) !== CharacterCodes.slash) return 1;
@@ -1126,9 +1163,14 @@ namespace ts {
return 0;
}
/**
* Internally, we represent paths as strings with '/' as the directory separator.
* When we make system calls (eg: LanguageServiceHost.getDirectory()),
* we expect the host to correctly handle paths in our specified format.
*/
export const directorySeparator = "/";
const directorySeparatorCharCode = CharacterCodes.slash;
function getNormalizedParts(normalizedSlashedPath: string, rootLength: number) {
function getNormalizedParts(normalizedSlashedPath: string, rootLength: number): string[] {
const parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator);
const normalized: string[] = [];
for (const part of parts) {
@@ -1168,6 +1210,11 @@ namespace ts {
return path.charCodeAt(path.length - 1) === directorySeparatorCharCode;
}
/**
* Returns the path except for its basename. Eg:
*
* /path/to/file.ext -> /path/to
*/
export function getDirectoryPath(path: Path): Path;
export function getDirectoryPath(path: string): string;
export function getDirectoryPath(path: string): any {
@@ -1191,7 +1238,7 @@ namespace ts {
export function getEmitModuleKind(compilerOptions: CompilerOptions) {
return typeof compilerOptions.module === "number" ?
compilerOptions.module :
getEmitScriptTarget(compilerOptions) === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.CommonJS;
getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES2015 ? ModuleKind.ES2015 : ModuleKind.CommonJS;
}
/* @internal */
@@ -1813,9 +1860,9 @@ namespace ts {
export interface ObjectAllocator {
getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node;
getTokenConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token;
getIdentifierConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token;
getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile;
getTokenConstructor(): new <TKind extends SyntaxKind>(kind: TKind, pos?: number, end?: number) => Token<TKind>;
getIdentifierConstructor(): new (kind: SyntaxKind.Identifier, pos?: number, end?: number) => Identifier;
getSourceFileConstructor(): new (kind: SyntaxKind.SourceFile, pos?: number, end?: number) => SourceFile;
getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol;
getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type;
getSignatureConstructor(): new (checker: TypeChecker) => Signature;
@@ -1867,10 +1914,10 @@ namespace ts {
declare var process: any;
declare var require: any;
let currentAssertionLevel: AssertionLevel;
export let currentAssertionLevel = AssertionLevel.None;
export function shouldAssert(level: AssertionLevel): boolean {
return getCurrentAssertionLevel() >= level;
return currentAssertionLevel >= level;
}
export function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string): void {
@@ -1887,35 +1934,6 @@ namespace ts {
export function fail(message?: string): void {
Debug.assert(/*expression*/ false, message);
}
function getCurrentAssertionLevel() {
if (currentAssertionLevel !== undefined) {
return currentAssertionLevel;
}
if (sys === undefined) {
return AssertionLevel.None;
}
const developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV"));
currentAssertionLevel = developmentMode
? AssertionLevel.Normal
: AssertionLevel.None;
return currentAssertionLevel;
}
}
export function getEnvironmentVariable(name: string, host?: CompilerHost) {
if (host && host.getEnvironmentVariable) {
return host.getEnvironmentVariable(name);
}
if (sys && sys.getEnvironmentVariable) {
return sys.getEnvironmentVariable(name);
}
return "";
}
/** Remove an item from an array, moving everything to its right one space left. */
+3 -4
View File
@@ -1121,7 +1121,7 @@ namespace ts {
writeLine();
}
function emitVariableDeclaration(node: VariableDeclaration) {
function emitVariableDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration) {
// If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted
// so there is no check needed to see if declaration is visible
if (node.kind !== SyntaxKind.VariableDeclaration || resolver.isDeclarationVisible(node)) {
@@ -1136,7 +1136,7 @@ namespace ts {
// If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor
// we don't want to emit property declaration with "?"
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature ||
(node.kind === SyntaxKind.Parameter && !isParameterPropertyDeclaration(node))) && hasQuestionToken(node)) {
(node.kind === SyntaxKind.Parameter && !isParameterPropertyDeclaration(<ParameterDeclaration>node))) && hasQuestionToken(node)) {
write("?");
}
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && node.parent.kind === SyntaxKind.TypeLiteral) {
@@ -1626,8 +1626,7 @@ namespace ts {
}
}
function emitBindingElement(bindingElement: BindingElement) {
function emitBindingElement(bindingElement: BindingElement | OmittedExpression) {
if (bindingElement.kind === SyntaxKind.OmittedExpression) {
// If bindingElement is an omittedExpression (i.e. containing elision),
// we will emit blank space (although this may differ from users' original code,
+37 -2
View File
@@ -1923,7 +1923,7 @@
"category": "Error",
"code": 2685
},
"Identifier '{0}' must be imported from a module": {
"'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead.": {
"category": "Error",
"code": 2686
},
@@ -2861,6 +2861,10 @@
"category": "Error",
"code": 6140
},
"Parse in strict mode and emit \"use strict\" for each source file": {
"category": "Message",
"code": 6141
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005
@@ -2957,6 +2961,10 @@
"category": "Error",
"code": 7033
},
"Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined.": {
"category": "Error",
"code": 7034
},
"You cannot rename this element.": {
"category": "Error",
"code": 8000
@@ -3069,7 +3077,6 @@
"category": "Error",
"code": 17010
},
"Circularity detected while resolving configuration: {0}": {
"category": "Error",
"code": 18000
@@ -3077,5 +3084,33 @@
"The path in an 'extends' options must be relative or rooted.": {
"category": "Error",
"code": 18001
},
"Add missing 'super()' call.": {
"category": "Message",
"code": 90001
},
"Make 'super()' call the first statement in the constructor.": {
"category": "Message",
"code": 90002
},
"Change 'extends' to 'implements'": {
"category": "Message",
"code": 90003
},
"Remove unused identifiers": {
"category": "Message",
"code": 90004
},
"Implement interface on reference": {
"category": "Message",
"code": 90005
},
"Implement interface on class": {
"category": "Message",
"code": 90006
},
"Implement inherited abstract class": {
"category": "Message",
"code": 90007
}
}
+33 -9
View File
@@ -68,7 +68,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
@@ -504,15 +504,29 @@ const _super = (function (geti, seti) {
// Contextual keywords
case SyntaxKind.AbstractKeyword:
case SyntaxKind.AsKeyword:
case SyntaxKind.AnyKeyword:
case SyntaxKind.AsyncKeyword:
case SyntaxKind.AwaitKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.ConstructorKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.GetKeyword:
case SyntaxKind.IsKeyword:
case SyntaxKind.ModuleKeyword:
case SyntaxKind.NamespaceKeyword:
case SyntaxKind.NeverKeyword:
case SyntaxKind.ReadonlyKeyword:
case SyntaxKind.RequireKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.SetKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.TypeKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.FromKeyword:
case SyntaxKind.GlobalKeyword:
case SyntaxKind.OfKeyword:
writeTokenText(kind);
return;
@@ -655,7 +669,7 @@ const _super = (function (geti, seti) {
case SyntaxKind.ModuleDeclaration:
return emitModuleDeclaration(<ModuleDeclaration>node);
case SyntaxKind.ModuleBlock:
return emitModuleBlock(<Block>node);
return emitModuleBlock(<ModuleBlock>node);
case SyntaxKind.CaseBlock:
return emitCaseBlock(<CaseBlock>node);
case SyntaxKind.ImportEqualsDeclaration:
@@ -1198,12 +1212,14 @@ const _super = (function (geti, seti) {
function emitCallExpression(node: CallExpression) {
emitExpression(node.expression);
emitTypeArguments(node, node.typeArguments);
emitExpressionList(node, node.arguments, ListFormat.CallExpressionArguments);
}
function emitNewExpression(node: NewExpression) {
write("new ");
emitExpression(node.expression);
emitTypeArguments(node, node.typeArguments);
emitExpressionList(node, node.arguments, ListFormat.NewExpressionArguments);
}
@@ -1394,7 +1410,7 @@ const _super = (function (geti, seti) {
}
}
function emitBlockStatements(node: Block) {
function emitBlockStatements(node: BlockLike) {
if (getEmitFlags(node) & EmitFlags.SingleLine) {
emitList(node, node.statements, ListFormat.SingleLineBlockStatements);
}
@@ -1575,6 +1591,7 @@ const _super = (function (geti, seti) {
function emitVariableDeclaration(node: VariableDeclaration) {
emit(node.name);
emitWithPrefix(": ", node.type);
emitExpressionWithPrefix(" = ", node.initializer);
}
@@ -1795,7 +1812,7 @@ const _super = (function (geti, seti) {
}
function emitModuleBlock(node: ModuleBlock) {
if (isSingleLineEmptyBlock(node)) {
if (isEmptyBlock(node)) {
write("{ }");
}
else {
@@ -2165,7 +2182,7 @@ const _super = (function (geti, seti) {
// Only Emit __extends function when target ES5.
// For target ES6 and above, we can emit classDeclaration as is.
if ((languageVersion < ScriptTarget.ES6) && (!extendsEmitted && node.flags & NodeFlags.HasClassExtends)) {
if ((languageVersion < ScriptTarget.ES2015) && (!extendsEmitted && node.flags & NodeFlags.HasClassExtends)) {
writeLines(extendsHelper);
extendsEmitted = true;
helpersEmitted = true;
@@ -2192,9 +2209,12 @@ const _super = (function (geti, seti) {
helpersEmitted = true;
}
if (!awaiterEmitted && node.flags & NodeFlags.HasAsyncFunctions) {
// Only emit __awaiter function when target ES5/ES6.
// Only emit __generator function when target ES5.
// For target ES2017 and above, we can emit async/await as is.
if ((languageVersion < ScriptTarget.ES2017) && (!awaiterEmitted && node.flags & NodeFlags.HasAsyncFunctions)) {
writeLines(awaiterHelper);
if (languageVersion < ScriptTarget.ES6) {
if (languageVersion < ScriptTarget.ES2015) {
writeLines(generatorHelper);
}
@@ -2615,7 +2635,11 @@ const _super = (function (geti, seti) {
function isSingleLineEmptyBlock(block: Block) {
return !block.multiLine
&& block.statements.length === 0
&& isEmptyBlock(block);
}
function isEmptyBlock(block: BlockLike) {
return block.statements.length === 0
&& rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
}
+81 -44
View File
@@ -105,6 +105,7 @@ namespace ts {
export function createLiteral(textSource: StringLiteral | Identifier, location?: TextRange): StringLiteral;
export function createLiteral(value: string, location?: TextRange): StringLiteral;
export function createLiteral(value: number, location?: TextRange): NumericLiteral;
export function createLiteral(value: boolean, location?: TextRange): BooleanLiteral;
export function createLiteral(value: string | number | boolean, location?: TextRange): PrimaryExpression;
export function createLiteral(value: string | number | boolean | StringLiteral | Identifier, location?: TextRange): PrimaryExpression {
if (typeof value === "number") {
@@ -120,7 +121,7 @@ namespace ts {
node.text = value;
return node;
}
else {
else if (value) {
const node = <StringLiteral>createNode(SyntaxKind.StringLiteral, location, /*flags*/ undefined);
node.textSourceNode = value;
node.text = value.text;
@@ -187,8 +188,8 @@ namespace ts {
// Punctuation
export function createToken(token: SyntaxKind) {
return createNode(token);
export function createToken<TKind extends SyntaxKind>(token: TKind) {
return <Token<TKind>>createNode(token);
}
// Reserved words
@@ -238,7 +239,7 @@ namespace ts {
);
}
export function createParameterDeclaration(decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: Node, name: string | Identifier | BindingPattern, questionToken: Node, type: TypeNode, initializer: Expression, location?: TextRange, flags?: NodeFlags) {
export function createParameterDeclaration(decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: DotDotDotToken, name: string | Identifier | BindingPattern, questionToken: QuestionToken, type: TypeNode, initializer: Expression, location?: TextRange, flags?: NodeFlags) {
const node = <ParameterDeclaration>createNode(SyntaxKind.Parameter, location, flags);
node.decorators = decorators ? createNodeArray(decorators) : undefined;
node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
@@ -260,7 +261,7 @@ namespace ts {
// Type members
export function createProperty(decorators: Decorator[], modifiers: Modifier[], name: string | PropertyName, questionToken: Node, type: TypeNode, initializer: Expression, location?: TextRange) {
export function createProperty(decorators: Decorator[], modifiers: Modifier[], name: string | PropertyName, questionToken: QuestionToken, type: TypeNode, initializer: Expression, location?: TextRange) {
const node = <PropertyDeclaration>createNode(SyntaxKind.PropertyDeclaration, location);
node.decorators = decorators ? createNodeArray(decorators) : undefined;
node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
@@ -278,7 +279,7 @@ namespace ts {
return node;
}
export function createMethod(decorators: Decorator[], modifiers: Modifier[], asteriskToken: Node, name: string | PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags) {
export function createMethod(decorators: Decorator[], modifiers: Modifier[], asteriskToken: AsteriskToken, name: string | PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags) {
const node = <MethodDeclaration>createNode(SyntaxKind.MethodDeclaration, location, flags);
node.decorators = decorators ? createNodeArray(decorators) : undefined;
node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
@@ -381,7 +382,7 @@ namespace ts {
return node;
}
export function createBindingElement(propertyName: string | PropertyName, dotDotDotToken: Node, name: string | BindingName, initializer?: Expression, location?: TextRange) {
export function createBindingElement(propertyName: string | PropertyName, dotDotDotToken: DotDotDotToken, name: string | BindingName, initializer?: Expression, location?: TextRange) {
const node = <BindingElement>createNode(SyntaxKind.BindingElement, location);
node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName;
node.dotDotDotToken = dotDotDotToken;
@@ -497,14 +498,14 @@ namespace ts {
return node;
}
export function createTaggedTemplate(tag: Expression, template: Template, location?: TextRange) {
export function createTaggedTemplate(tag: Expression, template: TemplateLiteral, location?: TextRange) {
const node = <TaggedTemplateExpression>createNode(SyntaxKind.TaggedTemplateExpression, location);
node.tag = parenthesizeForAccess(tag);
node.template = template;
return node;
}
export function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: Template) {
export function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral) {
if (node.tag !== tag || node.template !== template) {
return updateNode(createTaggedTemplate(tag, template, node), node);
}
@@ -524,9 +525,9 @@ namespace ts {
return node;
}
export function createFunctionExpression(asteriskToken: Node, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags) {
export function createFunctionExpression(modifiers: Modifier[], asteriskToken: AsteriskToken, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags) {
const node = <FunctionExpression>createNode(SyntaxKind.FunctionExpression, location, flags);
node.modifiers = undefined;
node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
node.asteriskToken = asteriskToken;
node.name = typeof name === "string" ? createIdentifier(name) : name;
node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined;
@@ -536,20 +537,20 @@ namespace ts {
return node;
}
export function updateFunctionExpression(node: FunctionExpression, name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block) {
if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) {
return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node);
export function updateFunctionExpression(node: FunctionExpression, modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block) {
if (node.name !== name || node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) {
return updateNode(createFunctionExpression(modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node);
}
return node;
}
export function createArrowFunction(modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, equalsGreaterThanToken: Node, body: ConciseBody, location?: TextRange, flags?: NodeFlags) {
export function createArrowFunction(modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, equalsGreaterThanToken: EqualsGreaterThanToken, body: ConciseBody, location?: TextRange, flags?: NodeFlags) {
const node = <ArrowFunction>createNode(SyntaxKind.ArrowFunction, location, flags);
node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined;
node.parameters = createNodeArray(parameters);
node.type = type;
node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(SyntaxKind.EqualsGreaterThanToken);
node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(SyntaxKind.EqualsGreaterThanToken);
node.body = parenthesizeConciseBody(body);
return node;
}
@@ -613,7 +614,7 @@ namespace ts {
return node;
}
export function createPrefix(operator: SyntaxKind, operand: Expression, location?: TextRange) {
export function createPrefix(operator: PrefixUnaryOperator, operand: Expression, location?: TextRange) {
const node = <PrefixUnaryExpression>createNode(SyntaxKind.PrefixUnaryExpression, location);
node.operator = operator;
node.operand = parenthesizePrefixOperand(operand);
@@ -627,7 +628,7 @@ namespace ts {
return node;
}
export function createPostfix(operand: Expression, operator: SyntaxKind, location?: TextRange) {
export function createPostfix(operand: Expression, operator: PostfixUnaryOperator, location?: TextRange) {
const node = <PostfixUnaryExpression>createNode(SyntaxKind.PostfixUnaryExpression, location);
node.operand = parenthesizePostfixOperand(operand);
node.operator = operator;
@@ -641,8 +642,8 @@ namespace ts {
return node;
}
export function createBinary(left: Expression, operator: SyntaxKind | Node, right: Expression, location?: TextRange) {
const operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator;
export function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression, location?: TextRange) {
const operatorToken = typeof operator === "number" ? createToken(operator) : operator;
const operatorKind = operatorToken.kind;
const node = <BinaryExpression>createNode(SyntaxKind.BinaryExpression, location);
node.left = parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
@@ -658,7 +659,7 @@ namespace ts {
return node;
}
export function createConditional(condition: Expression, questionToken: Node, whenTrue: Expression, colonToken: Node, whenFalse: Expression, location?: TextRange) {
export function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression, location?: TextRange) {
const node = <ConditionalExpression>createNode(SyntaxKind.ConditionalExpression, location);
node.condition = condition;
node.questionToken = questionToken;
@@ -675,21 +676,21 @@ namespace ts {
return node;
}
export function createTemplateExpression(head: TemplateLiteralFragment, templateSpans: TemplateSpan[], location?: TextRange) {
export function createTemplateExpression(head: TemplateHead, templateSpans: TemplateSpan[], location?: TextRange) {
const node = <TemplateExpression>createNode(SyntaxKind.TemplateExpression, location);
node.head = head;
node.templateSpans = createNodeArray(templateSpans);
return node;
}
export function updateTemplateExpression(node: TemplateExpression, head: TemplateLiteralFragment, templateSpans: TemplateSpan[]) {
export function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: TemplateSpan[]) {
if (node.head !== head || node.templateSpans !== templateSpans) {
return updateNode(createTemplateExpression(head, templateSpans, node), node);
}
return node;
}
export function createYield(asteriskToken: Node, expression: Expression, location?: TextRange) {
export function createYield(asteriskToken: AsteriskToken, expression: Expression, location?: TextRange) {
const node = <YieldExpression>createNode(SyntaxKind.YieldExpression, location);
node.asteriskToken = asteriskToken;
node.expression = expression;
@@ -756,14 +757,14 @@ namespace ts {
// Misc
export function createTemplateSpan(expression: Expression, literal: TemplateLiteralFragment, location?: TextRange) {
export function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail, location?: TextRange) {
const node = <TemplateSpan>createNode(SyntaxKind.TemplateSpan, location);
node.expression = expression;
node.literal = literal;
return node;
}
export function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateLiteralFragment) {
export function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail) {
if (node.expression !== expression || node.literal !== literal) {
return updateNode(createTemplateSpan(expression, literal, node), node);
}
@@ -932,14 +933,14 @@ namespace ts {
return node;
}
export function updateForOf(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement) {
export function updateForOf(node: ForOfStatement, initializer: ForInitializer, expression: Expression, statement: Statement) {
if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) {
return updateNode(createForOf(initializer, expression, statement, node), node);
}
return node;
}
export function createContinue(label?: Identifier, location?: TextRange): BreakStatement {
export function createContinue(label?: Identifier, location?: TextRange): ContinueStatement {
const node = <ContinueStatement>createNode(SyntaxKind.ContinueStatement, location);
if (label) {
node.label = label;
@@ -1065,7 +1066,7 @@ namespace ts {
return node;
}
export function createFunctionDeclaration(decorators: Decorator[], modifiers: Modifier[], asteriskToken: Node, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags) {
export function createFunctionDeclaration(decorators: Decorator[], modifiers: Modifier[], asteriskToken: AsteriskToken, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags) {
const node = <FunctionDeclaration>createNode(SyntaxKind.FunctionDeclaration, location, flags);
node.decorators = decorators ? createNodeArray(decorators) : undefined;
node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
@@ -1560,7 +1561,7 @@ namespace ts {
return createParameterDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
createSynthesizedNode(SyntaxKind.DotDotDotToken),
createToken(SyntaxKind.DotDotDotToken),
name,
/*questionToken*/ undefined,
/*type*/ undefined,
@@ -1735,7 +1736,8 @@ namespace ts {
export function createAwaiterHelper(externalHelpersModuleName: Identifier | undefined, hasLexicalArguments: boolean, promiseConstructor: EntityName | Expression, body: Block) {
const generatorFunc = createFunctionExpression(
createNode(SyntaxKind.AsteriskToken),
/*modifiers*/ undefined,
createToken(SyntaxKind.AsteriskToken),
/*name*/ undefined,
/*typeParameters*/ undefined,
/*parameters*/ [],
@@ -1908,6 +1910,7 @@ namespace ts {
createCall(
createParen(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -1983,7 +1986,7 @@ namespace ts {
}
else if (callee.kind === SyntaxKind.SuperKeyword) {
thisArg = createThis();
target = languageVersion < ScriptTarget.ES6 ? createIdentifier("_super", /*location*/ callee) : <PrimaryExpression>callee;
target = languageVersion < ScriptTarget.ES2015 ? createIdentifier("_super", /*location*/ callee) : <PrimaryExpression>callee;
}
else {
switch (callee.kind) {
@@ -2089,6 +2092,7 @@ namespace ts {
const properties: ObjectLiteralElementLike[] = [];
if (getAccessor) {
const getterFunction = createFunctionExpression(
getAccessor.modifiers,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -2104,6 +2108,7 @@ namespace ts {
if (setAccessor) {
const setterFunction = createFunctionExpression(
setAccessor.modifiers,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -2170,6 +2175,7 @@ namespace ts {
createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name),
setOriginalNode(
createFunctionExpression(
method.modifiers,
method.asteriskToken,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -2205,7 +2211,7 @@ namespace ts {
* @param visitor: Optional callback used to visit any custom prologue directives.
*/
export function addPrologueDirectives(target: Statement[], source: Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult<Node>): number {
Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array");
Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
let foundUseStrict = false;
let statementOffset = 0;
const numStatements = source.length;
@@ -2218,22 +2224,53 @@ namespace ts {
target.push(statement);
}
else {
if (ensureUseStrict && !foundUseStrict) {
target.push(startOnNewLine(createStatement(createLiteral("use strict"))));
foundUseStrict = true;
}
if (getEmitFlags(statement) & EmitFlags.CustomPrologue) {
target.push(visitor ? visitNode(statement, visitor, isStatement) : statement);
}
else {
break;
}
break;
}
statementOffset++;
}
if (ensureUseStrict && !foundUseStrict) {
target.push(startOnNewLine(createStatement(createLiteral("use strict"))));
}
while (statementOffset < numStatements) {
const statement = source[statementOffset];
if (getEmitFlags(statement) & EmitFlags.CustomPrologue) {
target.push(visitor ? visitNode(statement, visitor, isStatement) : statement);
}
else {
break;
}
statementOffset++;
}
return statementOffset;
}
/**
* Ensures "use strict" directive is added
*
* @param node source file
*/
export function ensureUseStrict(node: SourceFile): SourceFile {
let foundUseStrict = false;
for (const statement of node.statements) {
if (isPrologueDirective(statement)) {
if (isUseStrictPrologue(statement as ExpressionStatement)) {
foundUseStrict = true;
break;
}
}
else {
break;
}
}
if (!foundUseStrict) {
const statements: Statement[] = [];
statements.push(startOnNewLine(createStatement(createLiteral("use strict"))));
// add "use strict" as the first statement
return updateSourceFileNode(node, statements.concat(node.statements));
}
return node;
}
/**
* Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
* order of operations.
@@ -2909,4 +2946,4 @@ namespace ts {
function tryGetModuleNameFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration, host: EmitHost, resolver: EmitResolver, compilerOptions: CompilerOptions) {
return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
}
}
}
+42 -25
View File
@@ -95,7 +95,7 @@ namespace ts {
currentDirectory = host.getCurrentDirectory();
}
return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host);
}
/**
@@ -675,23 +675,33 @@ namespace ts {
/* @internal */
export function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState, checkOneLevel: boolean): string {
return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, /*typesOnly*/ false);
}
function loadModuleFromNodeModulesAtTypes(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string {
return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, /*checkOneLevel*/ false, /*typesOnly*/ true);
}
function loadModuleFromNodeModulesWorker(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState, checkOneLevel: boolean, typesOnly: boolean): string {
directory = normalizeSlashes(directory);
while (true) {
const baseName = getBaseFileName(directory);
if (baseName !== "node_modules") {
// Try to load source from the package
const packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
if (packageResult && hasTypeScriptFileExtension(packageResult)) {
// Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package
return packageResult;
}
else {
// Else prefer a types package over non-TypeScript results (e.g. JavaScript files)
const typesResult = loadModuleFromNodeModulesFolder(combinePaths("@types", moduleName), directory, failedLookupLocations, state);
if (typesResult || packageResult) {
return typesResult || packageResult;
let packageResult: string | undefined;
if (!typesOnly) {
// Try to load source from the package
packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
if (packageResult && hasTypeScriptFileExtension(packageResult)) {
// Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package
return packageResult;
}
}
// Else prefer a types package over non-TypeScript results (e.g. JavaScript files)
const typesResult = loadModuleFromNodeModulesFolder(combinePaths("@types", moduleName), directory, failedLookupLocations, state);
if (typesResult || packageResult) {
return typesResult || packageResult;
}
}
const parentPath = getDirectoryPath(directory);
@@ -709,7 +719,7 @@ namespace ts {
const state = { compilerOptions, host, traceEnabled, skipTsx: !compilerOptions.jsx };
const failedLookupLocations: string[] = [];
const supportedExtensions = getSupportedExtensions(compilerOptions);
let containingDirectory = getDirectoryPath(containingFile);
const containingDirectory = getDirectoryPath(containingFile);
const resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
if (resolvedFileName) {
@@ -718,18 +728,9 @@ namespace ts {
let referencedSourceFile: string;
if (moduleHasNonRelativeName(moduleName)) {
while (true) {
const searchName = normalizePath(combinePaths(containingDirectory, moduleName));
referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
if (referencedSourceFile) {
break;
}
const parentPath = getDirectoryPath(containingDirectory);
if (parentPath === containingDirectory) {
break;
}
containingDirectory = parentPath;
}
referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) ||
// If we didn't find the file normally, look it up in @types.
loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state);
}
else {
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
@@ -741,4 +742,20 @@ namespace ts {
? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations };
}
/** Climb up parent directories looking for a module. */
function loadModuleFromAncestorDirectories(moduleName: string, containingDirectory: string, supportedExtensions: string[], failedLookupLocations: string[], state: ModuleResolutionState): string | undefined {
while (true) {
const searchName = normalizePath(combinePaths(containingDirectory, moduleName));
const referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
if (referencedSourceFile) {
return referencedSourceFile;
}
const parentPath = getDirectoryPath(containingDirectory);
if (parentPath === containingDirectory) {
return undefined;
}
containingDirectory = parentPath;
}
}
}
+51 -39
View File
@@ -637,7 +637,7 @@ namespace ts {
sourceFile.statements = parseList(ParsingContext.SourceElements, parseStatement);
Debug.assert(token() === SyntaxKind.EndOfFileToken);
sourceFile.endOfFileToken = parseTokenNode();
sourceFile.endOfFileToken = <EndOfFileToken>parseTokenNode();
setExternalModuleIndicator(sourceFile);
@@ -1004,6 +1004,7 @@ namespace ts {
return false;
}
function parseOptionalToken<TKind extends SyntaxKind>(t: TKind): Token<TKind>;
function parseOptionalToken(t: SyntaxKind): Node {
if (token() === t) {
return parseTokenNode();
@@ -1011,6 +1012,7 @@ namespace ts {
return undefined;
}
function parseExpectedToken<TKind extends SyntaxKind>(t: TKind, reportAtCurrentPosition: boolean, diagnosticMessage: DiagnosticMessage, arg0?: any): Token<TKind>;
function parseExpectedToken(t: SyntaxKind, reportAtCurrentPosition: boolean, diagnosticMessage: DiagnosticMessage, arg0?: any): Node {
return parseOptionalToken(t) ||
createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0);
@@ -1047,7 +1049,7 @@ namespace ts {
}
// note: this function creates only node
function createNode(kind: SyntaxKind, pos?: number): Node | Token | Identifier {
function createNode<TKind extends SyntaxKind>(kind: TKind, pos?: number): Node | Token<TKind> | Identifier {
nodeCount++;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
@@ -1394,8 +1396,8 @@ namespace ts {
// Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
return token() === SyntaxKind.CloseParenToken || token() === SyntaxKind.CloseBracketToken /*|| token === SyntaxKind.OpenBraceToken*/;
case ParsingContext.TypeArguments:
// Tokens other than '>' are here for better error recovery
return token() === SyntaxKind.GreaterThanToken || token() === SyntaxKind.OpenParenToken;
// All other tokens should cause the type-argument to terminate except comma token
return token() !== SyntaxKind.CommaToken;
case ParsingContext.HeritageClauses:
return token() === SyntaxKind.OpenBraceToken || token() === SyntaxKind.CloseBraceToken;
case ParsingContext.JsxAttributes:
@@ -1920,7 +1922,7 @@ namespace ts {
function parseTemplateExpression(): TemplateExpression {
const template = <TemplateExpression>createNode(SyntaxKind.TemplateExpression);
template.head = parseTemplateLiteralFragment();
template.head = parseTemplateHead();
Debug.assert(template.head.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind");
const templateSpans = createNodeArray<TemplateSpan>();
@@ -1940,14 +1942,13 @@ namespace ts {
const span = <TemplateSpan>createNode(SyntaxKind.TemplateSpan);
span.expression = allowInAnd(parseExpression);
let literal: TemplateLiteralFragment;
let literal: TemplateMiddle | TemplateTail;
if (token() === SyntaxKind.CloseBraceToken) {
reScanTemplateToken();
literal = parseTemplateLiteralFragment();
literal = parseTemplateMiddleOrTemplateTail();
}
else {
literal = <TemplateLiteralFragment>parseExpectedToken(SyntaxKind.TemplateTail, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken));
literal = <TemplateTail>parseExpectedToken(SyntaxKind.TemplateTail, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken));
}
span.literal = literal;
@@ -1958,8 +1959,16 @@ namespace ts {
return <LiteralExpression>parseLiteralLikeNode(token(), internName);
}
function parseTemplateLiteralFragment(): TemplateLiteralFragment {
return <TemplateLiteralFragment>parseLiteralLikeNode(token(), /*internName*/ false);
function parseTemplateHead(): TemplateHead {
const fragment = parseLiteralLikeNode(token(), /*internName*/ false);
Debug.assert(fragment.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind");
return <TemplateHead>fragment;
}
function parseTemplateMiddleOrTemplateTail(): TemplateMiddle | TemplateTail {
const fragment = parseLiteralLikeNode(token(), /*internName*/ false);
Debug.assert(fragment.kind === SyntaxKind.TemplateMiddle || fragment.kind === SyntaxKind.TemplateTail, "Template fragment has wrong token kind");
return <TemplateMiddle | TemplateTail>fragment;
}
function parseLiteralLikeNode(kind: SyntaxKind, internName: boolean): LiteralLikeNode {
@@ -2719,7 +2728,7 @@ namespace ts {
}
let expr = parseAssignmentExpressionOrHigher();
let operatorToken: Node;
let operatorToken: BinaryOperatorToken;
while ((operatorToken = parseOptionalToken(SyntaxKind.CommaToken))) {
expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher());
}
@@ -2812,7 +2821,7 @@ namespace ts {
// Note: we call reScanGreaterToken so that we get an appropriately merged token
// for cases like > > = becoming >>=
if (isLeftHandSideExpression(expr) && isAssignmentOperator(reScanGreaterToken())) {
return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher());
return makeBinaryExpression(expr, <BinaryOperatorToken>parseTokenNode(), parseAssignmentExpressionOrHigher());
}
// It wasn't an assignment or a lambda. This is a conditional expression:
@@ -3247,7 +3256,7 @@ namespace ts {
}
}
else {
leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
leftOperand = makeBinaryExpression(leftOperand, <BinaryOperatorToken>parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
}
}
@@ -3307,7 +3316,7 @@ namespace ts {
return -1;
}
function makeBinaryExpression(left: Expression, operatorToken: Node, right: Expression): BinaryExpression {
function makeBinaryExpression(left: Expression, operatorToken: BinaryOperatorToken, right: Expression): BinaryExpression {
const node = <BinaryExpression>createNode(SyntaxKind.BinaryExpression, left.pos);
node.left = left;
node.operatorToken = operatorToken;
@@ -3324,7 +3333,7 @@ namespace ts {
function parsePrefixUnaryExpression() {
const node = <PrefixUnaryExpression>createNode(SyntaxKind.PrefixUnaryExpression);
node.operator = token();
node.operator = <PrefixUnaryOperator>token();
nextToken();
node.operand = parseSimpleUnaryExpression();
@@ -3511,7 +3520,7 @@ namespace ts {
function parseIncrementExpression(): IncrementExpression {
if (token() === SyntaxKind.PlusPlusToken || token() === SyntaxKind.MinusMinusToken) {
const node = <PrefixUnaryExpression>createNode(SyntaxKind.PrefixUnaryExpression);
node.operator = token();
node.operator = <PrefixUnaryOperator>token();
nextToken();
node.operand = parseLeftHandSideExpressionOrHigher();
return finishNode(node);
@@ -3527,7 +3536,7 @@ namespace ts {
if ((token() === SyntaxKind.PlusPlusToken || token() === SyntaxKind.MinusMinusToken) && !scanner.hasPrecedingLineBreak()) {
const node = <PostfixUnaryExpression>createNode(SyntaxKind.PostfixUnaryExpression, expression.pos);
node.operand = expression;
node.operator = token();
node.operator = <PostfixUnaryOperator>token();
nextToken();
return finishNode(node);
}
@@ -3700,7 +3709,7 @@ namespace ts {
badNode.end = invalidElement.end;
badNode.left = result;
badNode.right = invalidElement;
badNode.operatorToken = createMissingNode(SyntaxKind.CommaToken, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined);
badNode.operatorToken = <BinaryOperatorToken>createMissingNode(SyntaxKind.CommaToken, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined);
badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
return <JsxElement><Node>badNode;
}
@@ -3836,7 +3845,7 @@ namespace ts {
if (token() === SyntaxKind.EqualsToken) {
switch (scanJsxAttributeValue()) {
case SyntaxKind.StringLiteral:
node.initializer = parseLiteralNode();
node.initializer = <StringLiteral>parseLiteralNode();
break;
default:
node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
@@ -3921,7 +3930,7 @@ namespace ts {
const tagExpression = <TaggedTemplateExpression>createNode(SyntaxKind.TaggedTemplateExpression, expression.pos);
tagExpression.tag = expression;
tagExpression.template = token() === SyntaxKind.NoSubstitutionTemplateLiteral
? parseLiteralNode()
? <NoSubstitutionTemplateLiteral>parseLiteralNode()
: parseTemplateExpression();
expression = finishNode(tagExpression);
continue;
@@ -4959,7 +4968,7 @@ namespace ts {
return addJSDocComment(finishNode(node));
}
function parseMethodDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>, asteriskToken: Node, name: PropertyName, questionToken: Node, diagnosticMessage?: DiagnosticMessage): MethodDeclaration {
function parseMethodDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>, asteriskToken: AsteriskToken, name: PropertyName, questionToken: QuestionToken, diagnosticMessage?: DiagnosticMessage): MethodDeclaration {
const method = <MethodDeclaration>createNode(SyntaxKind.MethodDeclaration, fullStart);
method.decorators = decorators;
method.modifiers = modifiers;
@@ -4973,7 +4982,7 @@ namespace ts {
return addJSDocComment(finishNode(method));
}
function parsePropertyDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>, name: PropertyName, questionToken: Node): ClassElement {
function parsePropertyDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>, name: PropertyName, questionToken: QuestionToken): ClassElement {
const property = <PropertyDeclaration>createNode(SyntaxKind.PropertyDeclaration, fullStart);
property.decorators = decorators;
property.modifiers = modifiers;
@@ -5343,7 +5352,7 @@ namespace ts {
parseExpected(SyntaxKind.EqualsToken);
node.type = parseType();
parseSemicolon();
return finishNode(node);
return addJSDocComment(finishNode(node));
}
// In an ambient declaration, the grammar only allows integer literals as initializers.
@@ -5395,7 +5404,7 @@ namespace ts {
node.flags |= flags;
node.name = parseIdentifier();
node.body = parseOptional(SyntaxKind.DotToken)
? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, NodeFlags.NestedNamespace | namespaceFlag)
? <NamespaceDeclaration>parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, NodeFlags.NestedNamespace | namespaceFlag)
: parseModuleBlock();
return addJSDocComment(finishNode(node));
}
@@ -5574,8 +5583,10 @@ namespace ts {
return finishNode(namespaceImport);
}
function parseNamedImportsOrExports(kind: SyntaxKind.NamedImports): NamedImports;
function parseNamedImportsOrExports(kind: SyntaxKind.NamedExports): NamedExports;
function parseNamedImportsOrExports(kind: SyntaxKind): NamedImportsOrExports {
const node = <NamedImports>createNode(kind);
const node = <NamedImports | NamedExports>createNode(kind);
// NamedImports:
// { }
@@ -5585,7 +5596,7 @@ namespace ts {
// ImportsList:
// ImportSpecifier
// ImportsList, ImportSpecifier
node.elements = parseBracketedList(ParsingContext.ImportOrExportSpecifiers,
node.elements = <NodeArray<ImportSpecifier> | NodeArray<ExportSpecifier>>parseBracketedList(ParsingContext.ImportOrExportSpecifiers,
kind === SyntaxKind.NamedImports ? parseImportSpecifier : parseExportSpecifier,
SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken);
return finishNode(node);
@@ -5969,14 +5980,15 @@ namespace ts {
const parameter = <ParameterDeclaration>createNode(SyntaxKind.Parameter);
parameter.type = parseJSDocType();
if (parseOptional(SyntaxKind.EqualsToken)) {
parameter.questionToken = createNode(SyntaxKind.EqualsToken);
// TODO(rbuckton): Can this be changed to SyntaxKind.QuestionToken?
parameter.questionToken = <QuestionToken>createNode(SyntaxKind.EqualsToken);
}
return finishNode(parameter);
}
function parseJSDocTypeReference(): JSDocTypeReference {
const result = <JSDocTypeReference>createNode(SyntaxKind.JSDocTypeReference);
result.name = parseSimplePropertyName();
result.name = <Identifier>parseSimplePropertyName();
if (token() === SyntaxKind.LessThanToken) {
result.typeArguments = parseTypeArguments();
@@ -6304,7 +6316,7 @@ namespace ts {
function parseTag(indent: number) {
Debug.assert(token() === SyntaxKind.AtToken);
const atToken = createNode(SyntaxKind.AtToken, scanner.getTokenPos());
const atToken = <AtToken>createNode(SyntaxKind.AtToken, scanner.getTokenPos());
atToken.end = scanner.getTextPos();
nextJSDocToken();
@@ -6410,7 +6422,7 @@ namespace ts {
return comments;
}
function parseUnknownTag(atToken: Node, tagName: Identifier) {
function parseUnknownTag(atToken: AtToken, tagName: Identifier) {
const result = <JSDocTag>createNode(SyntaxKind.JSDocTag, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
@@ -6440,7 +6452,7 @@ namespace ts {
});
}
function parseParamTag(atToken: Node, tagName: Identifier) {
function parseParamTag(atToken: AtToken, tagName: Identifier) {
let typeExpression = tryParseTypeExpression();
skipWhitespace();
@@ -6491,7 +6503,7 @@ namespace ts {
return finishNode(result);
}
function parseReturnTag(atToken: Node, tagName: Identifier): JSDocReturnTag {
function parseReturnTag(atToken: AtToken, tagName: Identifier): JSDocReturnTag {
if (forEach(tags, t => t.kind === SyntaxKind.JSDocReturnTag)) {
parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, Diagnostics._0_tag_already_specified, tagName.text);
}
@@ -6503,7 +6515,7 @@ namespace ts {
return finishNode(result);
}
function parseTypeTag(atToken: Node, tagName: Identifier): JSDocTypeTag {
function parseTypeTag(atToken: AtToken, tagName: Identifier): JSDocTypeTag {
if (forEach(tags, t => t.kind === SyntaxKind.JSDocTypeTag)) {
parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, Diagnostics._0_tag_already_specified, tagName.text);
}
@@ -6515,7 +6527,7 @@ namespace ts {
return finishNode(result);
}
function parsePropertyTag(atToken: Node, tagName: Identifier): JSDocPropertyTag {
function parsePropertyTag(atToken: AtToken, tagName: Identifier): JSDocPropertyTag {
const typeExpression = tryParseTypeExpression();
skipWhitespace();
const name = parseJSDocIdentifierName();
@@ -6533,7 +6545,7 @@ namespace ts {
return finishNode(result);
}
function parseTypedefTag(atToken: Node, tagName: Identifier): JSDocTypedefTag {
function parseTypedefTag(atToken: AtToken, tagName: Identifier): JSDocTypedefTag {
const typeExpression = tryParseTypeExpression();
skipWhitespace();
@@ -6555,7 +6567,7 @@ namespace ts {
}
}
if (!typedefTag.jsDocTypeLiteral) {
typedefTag.jsDocTypeLiteral = typeExpression.type;
typedefTag.jsDocTypeLiteral = <JSDocTypeLiteral>typeExpression.type;
}
}
else {
@@ -6607,7 +6619,7 @@ namespace ts {
function tryParseChildTag(parentTag: JSDocTypeLiteral): boolean {
Debug.assert(token() === SyntaxKind.AtToken);
const atToken = createNode(SyntaxKind.AtToken, scanner.getStartPos());
const atToken = <AtToken>createNode(SyntaxKind.AtToken, scanner.getStartPos());
atToken.end = scanner.getTextPos();
nextJSDocToken();
@@ -6637,7 +6649,7 @@ namespace ts {
return false;
}
function parseTemplateTag(atToken: Node, tagName: Identifier): JSDocTemplateTag {
function parseTemplateTag(atToken: AtToken, tagName: Identifier): JSDocTemplateTag {
if (forEach(tags, t => t.kind === SyntaxKind.JSDocTemplateTag)) {
parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, Diagnostics._0_tag_already_specified, tagName.text);
}
+10 -6
View File
@@ -206,7 +206,7 @@ namespace ts {
readFile: fileName => sys.readFile(fileName),
trace: (s: string) => sys.write(s + newLine),
directoryExists: directoryName => sys.directoryExists(directoryName),
getEnvironmentVariable: name => getEnvironmentVariable(name, /*host*/ undefined),
getEnvironmentVariable: name => sys.getEnvironmentVariable ? sys.getEnvironmentVariable(name) : "",
getDirectories: (path: string) => sys.getDirectories(path),
realpath
};
@@ -358,7 +358,7 @@ namespace ts {
// load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
const typeReferences: string[] = getAutomaticTypeDirectiveNames(options, host);
if (typeReferences) {
if (typeReferences.length) {
// This containingFilename needs to match with the one used in managed-side
const containingFilename = combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts");
const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
@@ -473,6 +473,7 @@ namespace ts {
(oldOptions.configFilePath !== options.configFilePath) ||
(oldOptions.baseUrl !== options.baseUrl) ||
(oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) ||
!arrayIsEqualTo(oldOptions.lib, options.lib) ||
!arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) ||
!arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) ||
!equalOwnProperties(oldOptions.paths, options.paths)) {
@@ -1310,7 +1311,6 @@ namespace ts {
for (let i = 0; i < moduleNames.length; i++) {
const resolution = resolutions[i];
setResolvedModule(file, moduleNames[i], resolution);
const resolvedPath = resolution ? toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined;
// add file to program only if:
// - resolution was successful
@@ -1332,7 +1332,7 @@ namespace ts {
}
else if (shouldAddFile) {
findSourceFile(resolution.resolvedFileName,
resolvedPath,
toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName),
/*isDefaultLib*/ false, /*isReference*/ false,
file,
skipTrivia(file.text, file.imports[i].pos),
@@ -1473,12 +1473,16 @@ namespace ts {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"));
}
if (options.noImplicitUseStrict && options.alwaysStrict) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"));
}
const languageVersion = options.target || ScriptTarget.ES3;
const outFile = options.outFile || options.out;
const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !isDeclarationFile(f) ? f : undefined);
if (options.isolatedModules) {
if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES6) {
if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES2015) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher));
}
@@ -1488,7 +1492,7 @@ namespace ts {
programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
}
}
else if (firstNonAmbientExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) {
else if (firstNonAmbientExternalModuleSourceFile && languageVersion < ScriptTarget.ES2015 && options.module === ModuleKind.None) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
programDiagnostics.add(createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
+1 -1
View File
@@ -1190,7 +1190,7 @@ namespace ts {
}
function scanBinaryOrOctalDigits(base: number): number {
Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8");
Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8");
let value = 0;
// For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
+11 -1
View File
@@ -83,7 +83,7 @@ namespace ts {
getEnvironmentVariable?(name: string): string;
};
export var sys: System = (function() {
export let sys: System = (function() {
function getWScriptSystem(): System {
@@ -476,6 +476,10 @@ namespace ts {
// Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
// (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
let options: any;
if (!directoryExists(directoryName)) {
return;
}
if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) {
options = { persistent: true, recursive: !!recursive };
}
@@ -637,4 +641,10 @@ namespace ts {
}
return sys;
})();
if (sys && sys.getEnvironmentVariable) {
Debug.currentAssertionLevel = /^development$/i.test(sys.getEnvironmentVariable("NODE_ENV"))
? AssertionLevel.Normal
: AssertionLevel.None;
}
}
+15 -8
View File
@@ -1,17 +1,18 @@
/// <reference path="visitor.ts" />
/// <reference path="transformers/ts.ts" />
/// <reference path="transformers/jsx.ts" />
/// <reference path="transformers/es7.ts" />
/// <reference path="transformers/es6.ts" />
/// <reference path="transformers/es2017.ts" />
/// <reference path="transformers/es2016.ts" />
/// <reference path="transformers/es2015.ts" />
/// <reference path="transformers/generators.ts" />
/// <reference path="transformers/module/module.ts" />
/// <reference path="transformers/module/system.ts" />
/// <reference path="transformers/module/es6.ts" />
/// <reference path="transformers/module/es2015.ts" />
/* @internal */
namespace ts {
const moduleTransformerMap = createMap<Transformer>({
[ModuleKind.ES6]: transformES6Module,
[ModuleKind.ES2015]: transformES2015Module,
[ModuleKind.System]: transformSystemModule,
[ModuleKind.AMD]: transformModule,
[ModuleKind.CommonJS]: transformModule,
@@ -115,10 +116,16 @@ namespace ts {
transformers.push(transformJsx);
}
transformers.push(transformES7);
if (languageVersion < ScriptTarget.ES2017) {
transformers.push(transformES2017);
}
if (languageVersion < ScriptTarget.ES6) {
transformers.push(transformES6);
if (languageVersion < ScriptTarget.ES2016) {
transformers.push(transformES2016);
}
if (languageVersion < ScriptTarget.ES2015) {
transformers.push(transformES2015);
transformers.push(transformGenerators);
}
@@ -339,4 +346,4 @@ namespace ts {
return statements;
}
}
}
}
+2 -2
View File
@@ -220,7 +220,7 @@ namespace ts {
function flattenDestructuring(
context: TransformationContext,
root: BindingElement | BinaryExpression,
root: VariableDeclaration | ParameterDeclaration | BindingElement | BinaryExpression,
value: Expression,
location: TextRange,
emitAssignment: (name: Identifier, value: Expression, location: TextRange, original: Node) => void,
@@ -320,7 +320,7 @@ namespace ts {
}
}
function emitBindingElement(target: BindingElement, value: Expression) {
function emitBindingElement(target: VariableDeclaration | ParameterDeclaration | BindingElement, value: Expression) {
// Any temporary assignments needed to emit target = value should point to target
const initializer = visitor ? visitNode(target.initializer, visitor, isExpression) : target.initializer;
if (initializer) {
@@ -4,7 +4,7 @@
/*@internal*/
namespace ts {
const enum ES6SubstitutionFlags {
const enum ES2015SubstitutionFlags {
/** Enables substitutions for captured `this` */
CapturedThis = 1 << 0,
/** Enables substitutions for block-scoped bindings. */
@@ -163,7 +163,7 @@ namespace ts {
ReplaceWithReturn,
}
export function transformES6(context: TransformationContext) {
export function transformES2015(context: TransformationContext) {
const {
startLexicalEnvironment,
endLexicalEnvironment,
@@ -197,7 +197,7 @@ namespace ts {
* They are persisted between each SourceFile transformation and should not
* be reset.
*/
let enabledSubstitutions: ES6SubstitutionFlags;
let enabledSubstitutions: ES2015SubstitutionFlags;
return transformSourceFile;
@@ -252,7 +252,7 @@ namespace ts {
}
function shouldCheckNode(node: Node): boolean {
return (node.transformFlags & TransformFlags.ES6) !== 0 ||
return (node.transformFlags & TransformFlags.ES2015) !== 0 ||
node.kind === SyntaxKind.LabeledStatement ||
(isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node));
}
@@ -261,7 +261,7 @@ namespace ts {
if (shouldCheckNode(node)) {
return visitJavaScript(node);
}
else if (node.transformFlags & TransformFlags.ContainsES6) {
else if (node.transformFlags & TransformFlags.ContainsES2015) {
return visitEachChild(node, visitor, context);
}
else {
@@ -681,6 +681,7 @@ namespace ts {
const extendsClauseElement = getClassExtendsHeritageClauseElement(node);
const classFunction = createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -982,7 +983,7 @@ namespace ts {
if (statementOffset < ctorStatements.length) {
firstStatement = ctorStatements[statementOffset];
if (firstStatement.kind === SyntaxKind.ExpressionStatement && isSuperCallExpression((firstStatement as ExpressionStatement).expression)) {
if (firstStatement.kind === SyntaxKind.ExpressionStatement && isSuperCall((firstStatement as ExpressionStatement).expression)) {
const superCall = (firstStatement as ExpressionStatement).expression as CallExpression;
superCallExpression = setOriginalNode(
saveStateAndInvoke(superCall, visitImmediateSuperCallInBody),
@@ -1416,6 +1417,7 @@ namespace ts {
if (getAccessor) {
const getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined);
setSourceMapRange(getterFunction, getSourceMapRange(getAccessor));
setEmitFlags(getterFunction, EmitFlags.NoLeadingComments);
const getter = createPropertyAssignment("get", getterFunction);
setCommentRange(getter, getCommentRange(getAccessor));
properties.push(getter);
@@ -1424,6 +1426,7 @@ namespace ts {
if (setAccessor) {
const setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined);
setSourceMapRange(setterFunction, getSourceMapRange(setAccessor));
setEmitFlags(setterFunction, EmitFlags.NoLeadingComments);
const setter = createPropertyAssignment("set", setterFunction);
setCommentRange(setter, getCommentRange(setAccessor));
properties.push(setter);
@@ -1509,6 +1512,7 @@ namespace ts {
const expression = setOriginalNode(
createFunctionExpression(
/*modifiers*/ undefined,
node.asteriskToken,
name,
/*typeParameters*/ undefined,
@@ -2240,6 +2244,7 @@ namespace ts {
/*type*/ undefined,
setEmitFlags(
createFunctionExpression(
/*modifiers*/ undefined,
isAsyncBlockContainingAwait ? createToken(SyntaxKind.AsteriskToken) : undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -3034,7 +3039,7 @@ namespace ts {
function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) {
const savedEnclosingFunction = enclosingFunction;
if (enabledSubstitutions & ES6SubstitutionFlags.CapturedThis && isFunctionLike(node)) {
if (enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis && isFunctionLike(node)) {
// If we are tracking a captured `this`, keep track of the enclosing function.
enclosingFunction = node;
}
@@ -3049,8 +3054,8 @@ namespace ts {
* contains block-scoped bindings (e.g. `let` or `const`).
*/
function enableSubstitutionsForBlockScopedBindings() {
if ((enabledSubstitutions & ES6SubstitutionFlags.BlockScopedBindings) === 0) {
enabledSubstitutions |= ES6SubstitutionFlags.BlockScopedBindings;
if ((enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) === 0) {
enabledSubstitutions |= ES2015SubstitutionFlags.BlockScopedBindings;
context.enableSubstitution(SyntaxKind.Identifier);
}
}
@@ -3060,8 +3065,8 @@ namespace ts {
* contains a captured `this`.
*/
function enableSubstitutionsForCapturedThis() {
if ((enabledSubstitutions & ES6SubstitutionFlags.CapturedThis) === 0) {
enabledSubstitutions |= ES6SubstitutionFlags.CapturedThis;
if ((enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis) === 0) {
enabledSubstitutions |= ES2015SubstitutionFlags.CapturedThis;
context.enableSubstitution(SyntaxKind.ThisKeyword);
context.enableEmitNotification(SyntaxKind.Constructor);
context.enableEmitNotification(SyntaxKind.MethodDeclaration);
@@ -3100,7 +3105,7 @@ namespace ts {
function substituteIdentifier(node: Identifier) {
// Only substitute the identifier if we have enabled substitutions for block-scoped
// bindings.
if (enabledSubstitutions & ES6SubstitutionFlags.BlockScopedBindings) {
if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) {
const original = getParseTreeNode(node, isIdentifier);
if (original && isNameOfDeclarationWithCollidingName(original)) {
return getGeneratedNameForNode(original);
@@ -3153,7 +3158,7 @@ namespace ts {
* @param node An Identifier node.
*/
function substituteExpressionIdentifier(node: Identifier): Identifier {
if (enabledSubstitutions & ES6SubstitutionFlags.BlockScopedBindings) {
if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) {
const declaration = resolver.getReferencedDeclarationWithCollidingName(node);
if (declaration) {
return getGeneratedNameForNode(declaration.name);
@@ -3169,7 +3174,7 @@ namespace ts {
* @param node The ThisKeyword node.
*/
function substituteThisKeyword(node: PrimaryExpression): PrimaryExpression {
if (enabledSubstitutions & ES6SubstitutionFlags.CapturedThis
if (enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis
&& enclosingFunction
&& getEmitFlags(enclosingFunction) & EmitFlags.CapturesThis) {
return createIdentifier("_this", /*location*/ node);
@@ -3198,7 +3203,7 @@ namespace ts {
* @param node The declaration.
* @param allowComments Allow comments for the name.
*/
function getDeclarationName(node: DeclarationStatement | ClassExpression, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags?: EmitFlags) {
function getDeclarationName(node: ClassDeclaration | ClassExpression | FunctionDeclaration, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags?: EmitFlags) {
if (node.name && !isGeneratedIdentifier(node.name)) {
const name = getMutableClone(node.name);
emitFlags |= getEmitFlags(node.name);
@@ -3256,4 +3261,4 @@ namespace ts {
return isIdentifier(expression) && expression === parameter.name;
}
}
}
}
@@ -3,7 +3,7 @@
/*@internal*/
namespace ts {
export function transformES7(context: TransformationContext) {
export function transformES2016(context: TransformationContext) {
const { hoistVariableDeclaration } = context;
return transformSourceFile;
@@ -17,10 +17,10 @@ namespace ts {
}
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.ES7) {
if (node.transformFlags & TransformFlags.ES2016) {
return visitorWorker(node);
}
else if (node.transformFlags & TransformFlags.ContainsES7) {
else if (node.transformFlags & TransformFlags.ContainsES2016) {
return visitEachChild(node, visitor, context);
}
else {
@@ -40,7 +40,7 @@ namespace ts {
}
function visitBinaryExpression(node: BinaryExpression): Expression {
// We are here because ES7 adds support for the exponentiation operator.
// We are here because ES2016 adds support for the exponentiation operator.
const left = visitNode(node.left, visitor, isExpression);
const right = visitNode(node.right, visitor, isExpression);
if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskEqualsToken) {
@@ -98,4 +98,4 @@ namespace ts {
}
}
}
}
}
+510
View File
@@ -0,0 +1,510 @@
/// <reference path="../factory.ts" />
/// <reference path="../visitor.ts" />
/*@internal*/
namespace ts {
type SuperContainer = ClassDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration;
export function transformES2017(context: TransformationContext) {
const enum ES2017SubstitutionFlags {
/** Enables substitutions for async methods with `super` calls. */
AsyncMethodsWithSuper = 1 << 0
}
const {
startLexicalEnvironment,
endLexicalEnvironment,
} = context;
const resolver = context.getEmitResolver();
const compilerOptions = context.getCompilerOptions();
const languageVersion = getEmitScriptTarget(compilerOptions);
// These variables contain state that changes as we descend into the tree.
let currentSourceFileExternalHelpersModuleName: Identifier;
/**
* Keeps track of whether expression substitution has been enabled for specific edge cases.
* They are persisted between each SourceFile transformation and should not be reset.
*/
let enabledSubstitutions: ES2017SubstitutionFlags;
/**
* Keeps track of whether we are within any containing namespaces when performing
* just-in-time substitution while printing an expression identifier.
*/
let applicableSubstitutions: ES2017SubstitutionFlags;
/**
* This keeps track of containers where `super` is valid, for use with
* just-in-time substitution for `super` expressions inside of async methods.
*/
let currentSuperContainer: SuperContainer;
// Save the previous transformation hooks.
const previousOnEmitNode = context.onEmitNode;
const previousOnSubstituteNode = context.onSubstituteNode;
// Set new transformation hooks.
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
let currentScope: SourceFile | Block | ModuleBlock | CaseBlock;
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
return node;
}
currentSourceFileExternalHelpersModuleName = node.externalHelpersModuleName;
return visitEachChild(node, visitor, context);
}
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.ES2017) {
return visitorWorker(node);
}
else if (node.transformFlags & TransformFlags.ContainsES2017) {
return visitEachChild(node, visitor, context);
}
return node;
}
function visitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.AsyncKeyword:
// ES2017 async modifier should be elided for targets < ES2017
return undefined;
case SyntaxKind.AwaitExpression:
// ES2017 'await' expressions must be transformed for targets < ES2017.
return visitAwaitExpression(<AwaitExpression>node);
case SyntaxKind.MethodDeclaration:
// ES2017 method declarations may be 'async'
return visitMethodDeclaration(<MethodDeclaration>node);
case SyntaxKind.FunctionDeclaration:
// ES2017 function declarations may be 'async'
return visitFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.FunctionExpression:
// ES2017 function expressions may be 'async'
return visitFunctionExpression(<FunctionExpression>node);
case SyntaxKind.ArrowFunction:
// ES2017 arrow functions may be 'async'
return visitArrowFunction(<ArrowFunction>node);
default:
Debug.failBadSyntaxKind(node);
return node;
}
}
/**
* Visits an await expression.
*
* This function will be called any time a ES2017 await expression is encountered.
*
* @param node The await expression node.
*/
function visitAwaitExpression(node: AwaitExpression): Expression {
return setOriginalNode(
createYield(
/*asteriskToken*/ undefined,
visitNode(node.expression, visitor, isExpression),
/*location*/ node
),
node
);
}
/**
* Visits a method declaration of a class.
*
* This function will be called when one of the following conditions are met:
* - The node is marked as async
*
* @param node The method node.
*/
function visitMethodDeclaration(node: MethodDeclaration) {
if (!isAsyncFunctionLike(node)) {
return node;
}
const method = createMethod(
/*decorators*/ undefined,
visitNodes(node.modifiers, visitor, isModifier),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ node
);
// While we emit the source map for the node after skipping decorators and modifiers,
// we need to emit the comments for the original range.
setCommentRange(method, node);
setSourceMapRange(method, moveRangePastDecorators(node));
setOriginalNode(method, node);
return method;
}
/**
* Visits a function declaration.
*
* This function will be called when one of the following conditions are met:
* - The node is marked async
*
* @param node The function node.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult<Statement> {
if (!isAsyncFunctionLike(node)) {
return node;
}
const func = createFunctionDeclaration(
/*decorators*/ undefined,
visitNodes(node.modifiers, visitor, isModifier),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ node
);
setOriginalNode(func, node);
return func;
}
/**
* Visits a function expression node.
*
* This function will be called when one of the following conditions are met:
* - The node is marked async
*
* @param node The function expression node.
*/
function visitFunctionExpression(node: FunctionExpression): Expression {
if (!isAsyncFunctionLike(node)) {
return node;
}
if (nodeIsMissing(node.body)) {
return createOmittedExpression();
}
const func = createFunctionExpression(
/*modifiers*/ undefined,
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ node
);
setOriginalNode(func, node);
return func;
}
/**
* @remarks
* This function will be called when one of the following conditions are met:
* - The node is marked async
*/
function visitArrowFunction(node: ArrowFunction) {
if (!isAsyncFunctionLike(node)) {
return node;
}
const func = createArrowFunction(
visitNodes(node.modifiers, visitor, isModifier),
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
/*type*/ undefined,
node.equalsGreaterThanToken,
transformConciseBody(node),
/*location*/ node
);
setOriginalNode(func, node);
return func;
}
function transformFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody {
return <FunctionBody>transformAsyncFunctionBody(node);
}
function transformConciseBody(node: ArrowFunction): ConciseBody {
return transformAsyncFunctionBody(node);
}
function transformFunctionBodyWorker(body: Block, start = 0) {
const savedCurrentScope = currentScope;
currentScope = body;
startLexicalEnvironment();
const statements = visitNodes(body.statements, visitor, isStatement, start);
const visited = updateBlock(body, statements);
const declarations = endLexicalEnvironment();
currentScope = savedCurrentScope;
return mergeFunctionBodyLexicalEnvironment(visited, declarations);
}
function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody | FunctionBody {
const nodeType = node.original ? (<FunctionLikeDeclaration>node.original).type : node.type;
const promiseConstructor = languageVersion < ScriptTarget.ES2015 ? getPromiseConstructor(nodeType) : undefined;
const isArrowFunction = node.kind === SyntaxKind.ArrowFunction;
const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0;
// An async function is emit as an outer function that calls an inner
// generator function. To preserve lexical bindings, we pass the current
// `this` and `arguments` objects to `__awaiter`. The generator function
// passed to `__awaiter` is executed inside of the callback to the
// promise constructor.
if (!isArrowFunction) {
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, (<Block>node.body).statements, /*ensureUseStrict*/ false, visitor);
statements.push(
createReturn(
createAwaiterHelper(
currentSourceFileExternalHelpersModuleName,
hasLexicalArguments,
promiseConstructor,
transformFunctionBodyWorker(<Block>node.body, statementOffset)
)
)
);
const block = createBlock(statements, /*location*/ node.body, /*multiLine*/ true);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
if (languageVersion >= ScriptTarget.ES2015) {
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) {
enableSubstitutionForAsyncMethodsWithSuper();
setEmitFlags(block, EmitFlags.EmitAdvancedSuperHelper);
}
else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) {
enableSubstitutionForAsyncMethodsWithSuper();
setEmitFlags(block, EmitFlags.EmitSuperHelper);
}
}
return block;
}
else {
return createAwaiterHelper(
currentSourceFileExternalHelpersModuleName,
hasLexicalArguments,
promiseConstructor,
<Block>transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ true)
);
}
}
function transformConciseBodyWorker(body: Block | Expression, forceBlockFunctionBody: boolean) {
if (isBlock(body)) {
return transformFunctionBodyWorker(body);
}
else {
startLexicalEnvironment();
const visited: Expression | Block = visitNode(body, visitor, isConciseBody);
const declarations = endLexicalEnvironment();
const merged = mergeFunctionBodyLexicalEnvironment(visited, declarations);
if (forceBlockFunctionBody && !isBlock(merged)) {
return createBlock([
createReturn(<Expression>merged)
]);
}
else {
return merged;
}
}
}
function getPromiseConstructor(type: TypeNode) {
const typeName = getEntityNameFromTypeNode(type);
if (typeName && isEntityName(typeName)) {
const serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
|| serializationKind === TypeReferenceSerializationKind.Unknown) {
return typeName;
}
}
return undefined;
}
function enableSubstitutionForAsyncMethodsWithSuper() {
if ((enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper) === 0) {
enabledSubstitutions |= ES2017SubstitutionFlags.AsyncMethodsWithSuper;
// We need to enable substitutions for call, property access, and element access
// if we need to rewrite super calls.
context.enableSubstitution(SyntaxKind.CallExpression);
context.enableSubstitution(SyntaxKind.PropertyAccessExpression);
context.enableSubstitution(SyntaxKind.ElementAccessExpression);
// We need to be notified when entering and exiting declarations that bind super.
context.enableEmitNotification(SyntaxKind.ClassDeclaration);
context.enableEmitNotification(SyntaxKind.MethodDeclaration);
context.enableEmitNotification(SyntaxKind.GetAccessor);
context.enableEmitNotification(SyntaxKind.SetAccessor);
context.enableEmitNotification(SyntaxKind.Constructor);
}
}
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.PropertyAccessExpression:
return substitutePropertyAccessExpression(<PropertyAccessExpression>node);
case SyntaxKind.ElementAccessExpression:
return substituteElementAccessExpression(<ElementAccessExpression>node);
case SyntaxKind.CallExpression:
if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper) {
return substituteCallExpression(<CallExpression>node);
}
break;
}
return node;
}
function substitutePropertyAccessExpression(node: PropertyAccessExpression) {
if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) {
const flags = getSuperContainerAsyncMethodFlags();
if (flags) {
return createSuperAccessInAsyncMethod(
createLiteral(node.name.text),
flags,
node
);
}
}
return node;
}
function substituteElementAccessExpression(node: ElementAccessExpression) {
if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) {
const flags = getSuperContainerAsyncMethodFlags();
if (flags) {
return createSuperAccessInAsyncMethod(
node.argumentExpression,
flags,
node
);
}
}
return node;
}
function substituteCallExpression(node: CallExpression): Expression {
const expression = node.expression;
if (isSuperProperty(expression)) {
const flags = getSuperContainerAsyncMethodFlags();
if (flags) {
const argumentExpression = isPropertyAccessExpression(expression)
? substitutePropertyAccessExpression(expression)
: substituteElementAccessExpression(expression);
return createCall(
createPropertyAccess(argumentExpression, "call"),
/*typeArguments*/ undefined,
[
createThis(),
...node.arguments
]
);
}
}
return node;
}
function isSuperContainer(node: Node): node is SuperContainer {
const kind = node.kind;
return kind === SyntaxKind.ClassDeclaration
|| kind === SyntaxKind.Constructor
|| kind === SyntaxKind.MethodDeclaration
|| kind === SyntaxKind.GetAccessor
|| kind === SyntaxKind.SetAccessor;
}
/**
* Hook for node emit.
*
* @param node The node to emit.
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void {
const savedApplicableSubstitutions = applicableSubstitutions;
const savedCurrentSuperContainer = currentSuperContainer;
// If we need to support substitutions for `super` in an async method,
// we should track it here.
if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) {
currentSuperContainer = node;
}
previousOnEmitNode(emitContext, node, emitCallback);
applicableSubstitutions = savedApplicableSubstitutions;
currentSuperContainer = savedCurrentSuperContainer;
}
/**
* Hooks node substitutions.
*
* @param node The node to substitute.
* @param isExpression A value indicating whether the node is to be used in an expression
* position.
*/
function onSubstituteNode(emitContext: EmitContext, node: Node) {
node = previousOnSubstituteNode(emitContext, node);
if (emitContext === EmitContext.Expression) {
return substituteExpression(<Expression>node);
}
return node;
}
function createSuperAccessInAsyncMethod(argumentExpression: Expression, flags: NodeCheckFlags, location: TextRange): LeftHandSideExpression {
if (flags & NodeCheckFlags.AsyncMethodWithSuperBinding) {
return createPropertyAccess(
createCall(
createIdentifier("_super"),
/*typeArguments*/ undefined,
[argumentExpression]
),
"value",
location
);
}
else {
return createCall(
createIdentifier("_super"),
/*typeArguments*/ undefined,
[argumentExpression],
location
);
}
}
function getSuperContainerAsyncMethodFlags() {
return currentSuperContainer !== undefined
&& resolver.getNodeCheckFlags(currentSuperContainer) & (NodeCheckFlags.AsyncMethodWithSuper | NodeCheckFlags.AsyncMethodWithSuperBinding);
}
}
}
+6 -4
View File
@@ -496,6 +496,7 @@ namespace ts {
if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
node = setOriginalNode(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
node.name,
/*typeParameters*/ undefined,
@@ -528,7 +529,7 @@ namespace ts {
*
* @param node The node to visit.
*/
function visitAccessorDeclaration(node: GetAccessorDeclaration) {
function visitAccessorDeclaration(node: AccessorDeclaration) {
const savedInGeneratorFunctionBody = inGeneratorFunctionBody;
const savedInStatementContainingYield = inStatementContainingYield;
inGeneratorFunctionBody = false;
@@ -660,12 +661,12 @@ namespace ts {
}
}
function isCompoundAssignment(kind: SyntaxKind) {
function isCompoundAssignment(kind: BinaryOperator): kind is CompoundAssignmentOperator {
return kind >= SyntaxKind.FirstCompoundAssignment
&& kind <= SyntaxKind.LastCompoundAssignment;
}
function getOperatorForCompoundAssignment(kind: SyntaxKind) {
function getOperatorForCompoundAssignment(kind: CompoundAssignmentOperator): BitwiseOperatorOrHigher {
switch (kind) {
case SyntaxKind.PlusEqualsToken: return SyntaxKind.PlusToken;
case SyntaxKind.MinusEqualsToken: return SyntaxKind.MinusToken;
@@ -2591,6 +2592,7 @@ namespace ts {
createThis(),
setEmitFlags(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -3080,4 +3082,4 @@ namespace ts {
);
}
}
}
}
@@ -0,0 +1,43 @@
/// <reference path="../../factory.ts" />
/// <reference path="../../visitor.ts" />
/*@internal*/
namespace ts {
export function transformES2015Module(context: TransformationContext) {
const compilerOptions = context.getCompilerOptions();
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
return node;
}
if (isExternalModule(node) || compilerOptions.isolatedModules) {
return visitEachChild(node, visitor, context);
}
return node;
}
function visitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
}
return node;
}
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<ImportEqualsDeclaration> {
// Elide `import=` as it is not legal with --module ES6
return undefined;
}
function visitExportAssignment(node: ExportAssignment): VisitResult<ExportAssignment> {
// Elide `export=` as it is not legal with --module ES6
return node.isExportEquals ? undefined : node;
}
}
}
-144
View File
@@ -1,144 +0,0 @@
/// <reference path="../../factory.ts" />
/// <reference path="../../visitor.ts" />
/*@internal*/
namespace ts {
export function transformES6Module(context: TransformationContext) {
const compilerOptions = context.getCompilerOptions();
const resolver = context.getEmitResolver();
let currentSourceFile: SourceFile;
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
return node;
}
if (isExternalModule(node) || compilerOptions.isolatedModules) {
currentSourceFile = node;
return visitEachChild(node, visitor, context);
}
return node;
}
function visitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ImportClause:
return visitImportClause(<ImportClause>node);
case SyntaxKind.NamedImports:
case SyntaxKind.NamespaceImport:
return visitNamedBindings(<NamedImportBindings>node);
case SyntaxKind.ImportSpecifier:
return visitImportSpecifier(<ImportSpecifier>node);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(<ExportDeclaration>node);
case SyntaxKind.NamedExports:
return visitNamedExports(<NamedExports>node);
case SyntaxKind.ExportSpecifier:
return visitExportSpecifier(<ExportSpecifier>node);
}
return node;
}
function visitExportAssignment(node: ExportAssignment): ExportAssignment {
if (node.isExportEquals) {
return undefined; // do not emit export equals for ES6
}
const original = getOriginalNode(node);
return nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined;
}
function visitExportDeclaration(node: ExportDeclaration): ExportDeclaration {
if (!node.exportClause) {
return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined;
}
if (!resolver.isValueAliasDeclaration(node)) {
return undefined;
}
const newExportClause = visitNode(node.exportClause, visitor, isNamedExports, /*optional*/ true);
if (node.exportClause === newExportClause) {
return node;
}
return newExportClause
? createExportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
newExportClause,
node.moduleSpecifier)
: undefined;
}
function visitNamedExports(node: NamedExports): NamedExports {
const newExports = visitNodes(node.elements, visitor, isExportSpecifier);
if (node.elements === newExports) {
return node;
}
return newExports.length ? createNamedExports(newExports) : undefined;
}
function visitExportSpecifier(node: ExportSpecifier): ExportSpecifier {
return resolver.isValueAliasDeclaration(node) ? node : undefined;
}
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): ImportEqualsDeclaration {
return !isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
function visitImportDeclaration(node: ImportDeclaration) {
if (node.importClause) {
const newImportClause = visitNode(node.importClause, visitor, isImportClause);
if (!newImportClause.name && !newImportClause.namedBindings) {
return undefined;
}
else if (newImportClause !== node.importClause) {
return createImportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
newImportClause,
node.moduleSpecifier);
}
}
return node;
}
function visitImportClause(node: ImportClause): ImportClause {
let newDefaultImport = node.name;
if (!resolver.isReferencedAliasDeclaration(node)) {
newDefaultImport = undefined;
}
const newNamedBindings = visitNode(node.namedBindings, visitor, isNamedImportBindings, /*optional*/ true);
return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings
? createImportClause(newDefaultImport, newNamedBindings)
: node;
}
function visitNamedBindings(node: NamedImportBindings): VisitResult<NamedImportBindings> {
if (node.kind === SyntaxKind.NamespaceImport) {
return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
else {
const newNamedImportElements = visitNodes((<NamedImports>node).elements, visitor, isImportSpecifier);
if (!newNamedImportElements || newNamedImportElements.length == 0) {
return undefined;
}
if (newNamedImportElements === (<NamedImports>node).elements) {
return node;
}
return createNamedImports(newNamedImportElements);
}
}
function visitImportSpecifier(node: ImportSpecifier) {
return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
}
}
+29 -29
View File
@@ -59,7 +59,7 @@ namespace ts {
currentSourceFile = node;
// Collect information about the external module.
({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node, resolver));
({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node));
// Perform the transformation.
const transformModule = transformModuleDelegates[moduleKind] || transformModuleDelegates[ModuleKind.None];
@@ -179,6 +179,7 @@ namespace ts {
//
// function (require, exports, module1, module2) ...
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -228,7 +229,7 @@ namespace ts {
}
function addExportEqualsIfNeeded(statements: Statement[], emitAsReturn: boolean) {
if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) {
if (exportEquals) {
if (emitAsReturn) {
const statement = createReturn(
exportEquals.expression,
@@ -415,7 +416,7 @@ namespace ts {
)
],
/*location*/ undefined,
/*flags*/ languageVersion >= ScriptTarget.ES6 ? NodeFlags.Const : NodeFlags.None),
/*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None),
/*location*/ node
)
);
@@ -461,23 +462,21 @@ namespace ts {
);
}
for (const specifier of node.exportClause.elements) {
if (resolver.isValueAliasDeclaration(specifier)) {
const exportedValue = createPropertyAccess(
generatedName,
specifier.propertyName || specifier.name
);
statements.push(
createStatement(
createExportAssignment(specifier.name, exportedValue),
/*location*/ specifier
)
);
}
const exportedValue = createPropertyAccess(
generatedName,
specifier.propertyName || specifier.name
);
statements.push(
createStatement(
createExportAssignment(specifier.name, exportedValue),
/*location*/ specifier
)
);
}
return singleOrMany(statements);
}
else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) {
else {
// export * from "mod";
return createStatement(
createCall(
@@ -495,15 +494,14 @@ namespace ts {
}
function visitExportAssignment(node: ExportAssignment): VisitResult<Statement> {
if (!node.isExportEquals) {
if (nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) {
const statements: Statement[] = [];
addExportDefault(statements, node.expression, /*location*/ node);
return statements;
}
if (node.isExportEquals) {
// Elide as `export=` is handled in addExportEqualsIfNeeded
return undefined;
}
return undefined;
const statements: Statement[] = [];
addExportDefault(statements, node.expression, /*location*/ node);
return statements;
}
function addExportDefault(statements: Statement[], expression: Expression, location: TextRange): void {
@@ -568,7 +566,7 @@ namespace ts {
}
function collectExportMembers(names: Identifier[], node: Node): Identifier[] {
if (isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && isDeclaration(node)) {
if (isAliasSymbolDeclaration(node) && isDeclaration(node)) {
const name = node.name;
if (isIdentifier(name)) {
names.push(name);
@@ -599,7 +597,7 @@ namespace ts {
}
else {
statements.push(
createExportStatement(node.name, setEmitFlags(getSynthesizedClone(node.name), EmitFlags.LocalName), /*location*/ node)
createExportStatement(<Identifier>node.name, setEmitFlags(getSynthesizedClone(node.name), EmitFlags.LocalName), /*location*/ node)
);
}
}
@@ -701,11 +699,13 @@ namespace ts {
const statements: Statement[] = [];
const name = node.name || getGeneratedNameForNode(node);
if (hasModifier(node, ModifierFlags.Export)) {
// Keep async modifier for ES2017 transformer
const isAsync = hasModifier(node, ModifierFlags.Async);
statements.push(
setOriginalNode(
createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
isAsync ? [<Modifier>createNode(SyntaxKind.AsyncKeyword)] : undefined,
node.asteriskToken,
name,
/*typeParameters*/ undefined,
@@ -796,7 +796,7 @@ namespace ts {
addVarForExportedEnumOrNamespaceDeclaration(statements, original);
}
addExportMemberAssignments(statements, original.name);
addExportMemberAssignments(statements, <Identifier>original.name);
return statements;
}
@@ -819,7 +819,7 @@ namespace ts {
}
function getDeclarationName(node: DeclarationStatement) {
return node.name ? getSynthesizedClone(node.name) : getGeneratedNameForNode(node);
return node.name ? getSynthesizedClone(<Identifier>node.name) : getGeneratedNameForNode(node);
}
function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void {
@@ -916,7 +916,7 @@ namespace ts {
if (node.kind === SyntaxKind.PostfixUnaryExpression) {
transformedUnaryExpression = createBinary(
operand,
createNode(operator === SyntaxKind.PlusPlusToken ? SyntaxKind.PlusEqualsToken : SyntaxKind.MinusEqualsToken),
createToken(operator === SyntaxKind.PlusPlusToken ? SyntaxKind.PlusEqualsToken : SyntaxKind.MinusEqualsToken),
createLiteral(1),
/*location*/ node
);
+21 -21
View File
@@ -91,7 +91,7 @@ namespace ts {
Debug.assert(!exportFunctionForFile);
// Collect information about the external module and dependency groups.
({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node, resolver));
({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node));
// Make sure that the name of the 'exports' function does not conflict with
// existing identifiers.
@@ -110,6 +110,7 @@ namespace ts {
const moduleName = tryGetModuleNameFromFile(node, host, compilerOptions);
const dependencies = createArrayLiteral(map(dependencyGroups, getNameOfDependencyGroup));
const body = createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -244,6 +245,7 @@ namespace ts {
),
createPropertyAssignment("execute",
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -430,6 +432,7 @@ namespace ts {
setters.push(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -573,28 +576,23 @@ namespace ts {
}
function visitExportSpecifier(specifier: ExportSpecifier): Statement {
if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name)
|| resolver.isValueAliasDeclaration(specifier)) {
recordExportName(specifier.name);
return createExportStatement(
specifier.name,
specifier.propertyName || specifier.name
);
}
return undefined;
recordExportName(specifier.name);
return createExportStatement(
specifier.name,
specifier.propertyName || specifier.name
);
}
function visitExportAssignment(node: ExportAssignment): Statement {
if (!node.isExportEquals) {
if (nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) {
return createExportStatement(
createLiteral("default"),
node.expression
);
}
if (node.isExportEquals) {
// Elide `export=` as it is illegal in a SystemJS module.
return undefined;
}
return undefined;
return createExportStatement(
createLiteral("default"),
node.expression
);
}
/**
@@ -662,9 +660,11 @@ namespace ts {
if (hasModifier(node, ModifierFlags.Export)) {
// If the function is exported, ensure it has a name and rewrite the function without any export flags.
const name = node.name || getGeneratedNameForNode(node);
// Keep async modifier for ES2017 transformer
const isAsync = hasModifier(node, ModifierFlags.Async);
const newNode = createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
isAsync ? [<Modifier>createNode(SyntaxKind.AsyncKeyword)] : undefined,
node.asteriskToken,
name,
/*typeParameters*/ undefined,
@@ -1201,7 +1201,7 @@ namespace ts {
* @param node The declaration statement.
*/
function getDeclarationName(node: DeclarationStatement) {
return node.name ? getSynthesizedClone(node.name) : getGeneratedNameForNode(node);
return node.name ? getSynthesizedClone(<Identifier>node.name) : getGeneratedNameForNode(node);
}
function addExportStarFunction(statements: Statement[], localNames: Identifier) {
@@ -1402,4 +1402,4 @@ namespace ts {
return updated;
}
}
}
}
+266 -244
View File
@@ -4,8 +4,6 @@
/*@internal*/
namespace ts {
type SuperContainer = ClassDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration;
/**
* Indicates whether to emit type metadata in the new format.
*/
@@ -16,8 +14,6 @@ namespace ts {
ClassAliases = 1 << 0,
/** Enables substitutions for namespace exports. */
NamespaceExports = 1 << 1,
/** Enables substitutions for async methods with `super` calls. */
AsyncMethodsWithSuper = 1 << 2,
/* Enables substitutions for unqualified enum members */
NonQualifiedEnumMembers = 1 << 3
}
@@ -72,12 +68,6 @@ namespace ts {
*/
let applicableSubstitutions: TypeScriptSubstitutionFlags;
/**
* This keeps track of containers where `super` is valid, for use with
* just-in-time substitution for `super` expressions inside of async methods.
*/
let currentSuperContainer: SuperContainer;
return transformSourceFile;
/**
@@ -147,6 +137,35 @@ namespace ts {
return node;
}
/**
* Specialized visitor that visits the immediate children of a SourceFile.
*
* @param node The node to visit.
*/
function sourceElementVisitor(node: Node): VisitResult<Node> {
return saveStateAndInvoke(node, sourceElementVisitorWorker);
}
/**
* Specialized visitor that visits the immediate children of a SourceFile.
*
* @param node The node to visit.
*/
function sourceElementVisitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(<ExportDeclaration>node);
default:
return visitorWorker(node);
}
}
/**
* Specialized visitor that visits the immediate children of a namespace.
*
@@ -244,7 +263,6 @@ namespace ts {
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.AbstractKeyword:
case SyntaxKind.AsyncKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.ReadonlyKeyword:
@@ -286,8 +304,7 @@ namespace ts {
// TypeScript property declarations are elided.
case SyntaxKind.Constructor:
// TypeScript constructors are transformed in `visitClassDeclaration`.
return undefined;
return visitConstructor(<ConstructorDeclaration>node);
case SyntaxKind.InterfaceDeclaration:
// TypeScript interfaces are elided, but some comments may be preserved.
@@ -304,7 +321,6 @@ namespace ts {
// - property declarations
// - index signatures
// - method overload signatures
// - async methods
return visitClassDeclaration(<ClassDeclaration>node);
case SyntaxKind.ClassExpression:
@@ -317,7 +333,6 @@ namespace ts {
// - property declarations
// - index signatures
// - method overload signatures
// - async methods
return visitClassExpression(<ClassExpression>node);
case SyntaxKind.HeritageClause:
@@ -332,7 +347,7 @@ namespace ts {
return visitExpressionWithTypeArguments(<ExpressionWithTypeArguments>node);
case SyntaxKind.MethodDeclaration:
// TypeScript method declarations may be 'async', and may have decorators, modifiers
// TypeScript method declarations may have decorators, modifiers
// or type annotations.
return visitMethodDeclaration(<MethodDeclaration>node);
@@ -341,19 +356,19 @@ namespace ts {
return visitGetAccessor(<GetAccessorDeclaration>node);
case SyntaxKind.SetAccessor:
// Set Accessors can have TypeScript modifiers, decorators, and type annotations.
// Set Accessors can have TypeScript modifiers and type annotations.
return visitSetAccessor(<SetAccessorDeclaration>node);
case SyntaxKind.FunctionDeclaration:
// TypeScript function declarations may be 'async'
// Typescript function declarations can have modifiers, decorators, and type annotations.
return visitFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.FunctionExpression:
// TypeScript function expressions may be 'async'
// TypeScript function expressions can have modifiers and type annotations.
return visitFunctionExpression(<FunctionExpression>node);
case SyntaxKind.ArrowFunction:
// TypeScript arrow functions may be 'async'
// TypeScript arrow functions can have modifiers and type annotations.
return visitArrowFunction(<ArrowFunction>node);
case SyntaxKind.Parameter:
@@ -377,6 +392,12 @@ namespace ts {
// TypeScript type assertions are removed, but their subtrees are preserved.
return visitAssertionExpression(<AssertionExpression>node);
case SyntaxKind.CallExpression:
return visitCallExpression(<CallExpression>node);
case SyntaxKind.NewExpression:
return visitNewExpression(<NewExpression>node);
case SyntaxKind.NonNullExpression:
// TypeScript non-null expressions are removed, but their subtrees are preserved.
return visitNonNullExpression(<NonNullExpression>node);
@@ -385,14 +406,13 @@ namespace ts {
// TypeScript enum declarations do not exist in ES6 and must be rewritten.
return visitEnumDeclaration(<EnumDeclaration>node);
case SyntaxKind.AwaitExpression:
// TypeScript 'await' expressions must be transformed.
return visitAwaitExpression(<AwaitExpression>node);
case SyntaxKind.VariableStatement:
// TypeScript namespace exports for variable statements must be transformed.
return visitVariableStatement(<VariableStatement>node);
case SyntaxKind.VariableDeclaration:
return visitVariableDeclaration(<VariableDeclaration>node);
case SyntaxKind.ModuleDeclaration:
// TypeScript namespace declarations must be transformed.
return visitModuleDeclaration(<ModuleDeclaration>node);
@@ -436,6 +456,11 @@ namespace ts {
function visitSourceFile(node: SourceFile) {
currentSourceFile = node;
// ensure "use strict" is emitted in all scenarios in alwaysStrict mode
if (compilerOptions.alwaysStrict) {
node = ensureUseStrict(node);
}
// If the source file requires any helpers and is an external module, and
// the importHelpers compiler option is enabled, emit a synthesized import
// statement for the helpers library.
@@ -457,7 +482,7 @@ namespace ts {
statements.push(externalHelpersModuleImport);
currentSourceFileExternalHelpersModuleName = externalHelpersModuleName;
addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset));
addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset));
addRange(statements, endLexicalEnvironment());
currentSourceFileExternalHelpersModuleName = undefined;
@@ -465,7 +490,7 @@ namespace ts {
node.externalHelpersModuleName = externalHelpersModuleName;
}
else {
node = visitEachChild(node, visitor, context);
node = visitEachChild(node, sourceElementVisitor, context);
}
setEmitFlags(node, EmitFlags.EmitEmitHelpers | getEmitFlags(node));
@@ -989,7 +1014,7 @@ namespace ts {
}
const statement = statements[index];
if (statement.kind === SyntaxKind.ExpressionStatement && isSuperCallExpression((<ExpressionStatement>statement).expression)) {
if (statement.kind === SyntaxKind.ExpressionStatement && isSuperCall((<ExpressionStatement>statement).expression)) {
result.push(visitNode(statement, visitor, isStatement));
return index + 1;
}
@@ -1794,17 +1819,48 @@ namespace ts {
return createIdentifier("Number");
case SyntaxKind.SymbolKeyword:
return languageVersion < ScriptTarget.ES6
return languageVersion < ScriptTarget.ES2015
? getGlobalSymbolNameWithFallback()
: createIdentifier("Symbol");
case SyntaxKind.TypeReference:
return serializeTypeReferenceNode(<TypeReferenceNode>node);
case SyntaxKind.IntersectionType:
case SyntaxKind.UnionType:
{
const unionOrIntersection = <UnionOrIntersectionTypeNode>node;
let serializedUnion: Identifier;
for (const typeNode of unionOrIntersection.types) {
const serializedIndividual = serializeTypeNode(typeNode) as Identifier;
// Non identifier
if (serializedIndividual.kind !== SyntaxKind.Identifier) {
serializedUnion = undefined;
break;
}
// One of the individual is global object, return immediately
if (serializedIndividual.text === "Object") {
return serializedIndividual;
}
// Different types
if (serializedUnion && serializedUnion.text !== serializedIndividual.text) {
serializedUnion = undefined;
break;
}
serializedUnion = serializedIndividual;
}
// If we were able to find common type
if (serializedUnion) {
return serializedUnion;
}
}
// Fallthrough
case SyntaxKind.TypeQuery:
case SyntaxKind.TypeLiteral:
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
case SyntaxKind.AnyKeyword:
case SyntaxKind.ThisType:
break;
@@ -1860,7 +1916,7 @@ namespace ts {
return createIdentifier("Array");
case TypeReferenceSerializationKind.ESSymbolType:
return languageVersion < ScriptTarget.ES6
return languageVersion < ScriptTarget.ES2015
? getGlobalSymbolNameWithFallback()
: createIdentifier("Symbol");
@@ -2052,12 +2108,20 @@ namespace ts {
return !nodeIsMissing(node.body);
}
function visitConstructor(node: ConstructorDeclaration) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return undefined;
}
return visitEachChild(node, visitor, context);
}
/**
* Visits a method declaration of a class.
*
* This function will be called when one of the following conditions are met:
* - The node is an overload
* - The node is marked as abstract, async, public, private, protected, or readonly
* - The node is marked as abstract, public, private, protected, or readonly
* - The node has both a decorator and a computed property name
*
* @param node The method node.
@@ -2168,8 +2232,8 @@ namespace ts {
*
* This function will be called when one of the following conditions are met:
* - The node is an overload
* - The node is marked async
* - The node is exported from a TypeScript namespace
* - The node has decorators
*
* @param node The function node.
*/
@@ -2204,7 +2268,7 @@ namespace ts {
* Visits a function expression node.
*
* This function will be called when one of the following conditions are met:
* - The node is marked async
* - The node has type annotations
*
* @param node The function expression node.
*/
@@ -2214,6 +2278,7 @@ namespace ts {
}
const func = createFunctionExpression(
visitNodes(node.modifiers, visitor, isModifier),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
@@ -2231,11 +2296,11 @@ namespace ts {
/**
* @remarks
* This function will be called when one of the following conditions are met:
* - The node is marked async
* - The node has type annotations
*/
function visitArrowFunction(node: ArrowFunction) {
const func = createArrowFunction(
/*modifiers*/ undefined,
visitNodes(node.modifiers, visitor, isModifier),
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
/*type*/ undefined,
@@ -2250,30 +2315,25 @@ namespace ts {
}
function transformFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody {
if (isAsyncFunctionLike(node)) {
return <FunctionBody>transformAsyncFunctionBody(node);
}
return transformFunctionBodyWorker(node.body);
}
function transformFunctionBodyWorker(body: Block, start = 0) {
const savedCurrentScope = currentScope;
const savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
currentScope = body;
currentScopeFirstDeclarationsOfName = createMap<Node>();
startLexicalEnvironment();
const statements = visitNodes(body.statements, visitor, isStatement, start);
const visited = updateBlock(body, statements);
const declarations = endLexicalEnvironment();
currentScope = savedCurrentScope;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
return mergeFunctionBodyLexicalEnvironment(visited, declarations);
}
function transformConciseBody(node: ArrowFunction): ConciseBody {
if (isAsyncFunctionLike(node)) {
return transformAsyncFunctionBody(node);
}
return transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ false);
}
@@ -2297,72 +2357,6 @@ namespace ts {
}
}
function getPromiseConstructor(type: TypeNode) {
const typeName = getEntityNameFromTypeNode(type);
if (typeName && isEntityName(typeName)) {
const serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
|| serializationKind === TypeReferenceSerializationKind.Unknown) {
return typeName;
}
}
return undefined;
}
function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody | FunctionBody {
const promiseConstructor = languageVersion < ScriptTarget.ES6 ? getPromiseConstructor(node.type) : undefined;
const isArrowFunction = node.kind === SyntaxKind.ArrowFunction;
const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0;
// An async function is emit as an outer function that calls an inner
// generator function. To preserve lexical bindings, we pass the current
// `this` and `arguments` objects to `__awaiter`. The generator function
// passed to `__awaiter` is executed inside of the callback to the
// promise constructor.
if (!isArrowFunction) {
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, (<Block>node.body).statements, /*ensureUseStrict*/ false, visitor);
statements.push(
createReturn(
createAwaiterHelper(
currentSourceFileExternalHelpersModuleName,
hasLexicalArguments,
promiseConstructor,
transformFunctionBodyWorker(<Block>node.body, statementOffset)
)
)
);
const block = createBlock(statements, /*location*/ node.body, /*multiLine*/ true);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
if (languageVersion >= ScriptTarget.ES6) {
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) {
enableSubstitutionForAsyncMethodsWithSuper();
setEmitFlags(block, EmitFlags.EmitAdvancedSuperHelper);
}
else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) {
enableSubstitutionForAsyncMethodsWithSuper();
setEmitFlags(block, EmitFlags.EmitSuperHelper);
}
}
return block;
}
else {
return createAwaiterHelper(
currentSourceFileExternalHelpersModuleName,
hasLexicalArguments,
promiseConstructor,
<Block>transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ true)
);
}
}
/**
* Visits a parameter declaration node.
*
@@ -2374,7 +2368,7 @@ namespace ts {
* @param node The parameter declaration node.
*/
function visitParameter(node: ParameterDeclaration) {
if (node.name && isIdentifier(node.name) && node.name.originalKeywordKind === SyntaxKind.ThisKeyword) {
if (parameterIsThisKeyword(node)) {
return undefined;
}
@@ -2445,22 +2439,12 @@ namespace ts {
}
}
/**
* Visits an await expression.
*
* This function will be called any time a TypeScript await expression is encountered.
*
* @param node The await expression node.
*/
function visitAwaitExpression(node: AwaitExpression): Expression {
return setOriginalNode(
createYield(
/*asteriskToken*/ undefined,
visitNode(node.expression, visitor, isExpression),
/*location*/ node
),
node
);
function visitVariableDeclaration(node: VariableDeclaration) {
return updateVariableDeclaration(
node,
visitNode(node.name, visitor, isBindingName),
/*type*/ undefined,
visitNode(node.initializer, visitor, isExpression));
}
/**
@@ -2505,6 +2489,22 @@ namespace ts {
return createPartiallyEmittedExpression(expression, node);
}
function visitCallExpression(node: CallExpression) {
return updateCall(
node,
visitNode(node.expression, visitor, isExpression),
/*typeArguments*/ undefined,
visitNodes(node.arguments, visitor, isExpression));
}
function visitNewExpression(node: NewExpression) {
return updateNew(
node,
visitNode(node.expression, visitor, isExpression),
/*typeArguments*/ undefined,
visitNodes(node.arguments, visitor, isExpression));
}
/**
* Determines whether to emit an enum declaration.
*
@@ -2586,6 +2586,7 @@ namespace ts {
const enumStatement = createStatement(
createCall(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -2699,7 +2700,7 @@ namespace ts {
function isES6ExportedDeclaration(node: Node) {
return isExternalModuleExport(node)
&& moduleKind === ModuleKind.ES6;
&& moduleKind === ModuleKind.ES2015;
}
/**
@@ -2857,6 +2858,7 @@ namespace ts {
const moduleStatement = createStatement(
createCall(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -2962,6 +2964,133 @@ namespace ts {
}
}
/**
* Visits an import declaration, eliding it if it is not referenced.
*
* @param node The import declaration node.
*/
function visitImportDeclaration(node: ImportDeclaration): VisitResult<Statement> {
if (!node.importClause) {
// Do not elide a side-effect only import declaration.
// import "foo";
return node;
}
// Elide the declaration if the import clause was elided.
const importClause = visitNode(node.importClause, visitImportClause, isImportClause, /*optional*/ true);
return importClause
? updateImportDeclaration(
node,
/*decorators*/ undefined,
/*modifiers*/ undefined,
importClause,
node.moduleSpecifier)
: undefined;
}
/**
* Visits an import clause, eliding it if it is not referenced.
*
* @param node The import clause node.
*/
function visitImportClause(node: ImportClause): VisitResult<ImportClause> {
// Elide the import clause if we elide both its name and its named bindings.
const name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
const namedBindings = visitNode(node.namedBindings, visitNamedImportBindings, isNamedImportBindings, /*optional*/ true);
return (name || namedBindings) ? updateImportClause(node, name, namedBindings) : undefined;
}
/**
* Visits named import bindings, eliding it if it is not referenced.
*
* @param node The named import bindings node.
*/
function visitNamedImportBindings(node: NamedImportBindings): VisitResult<NamedImportBindings> {
if (node.kind === SyntaxKind.NamespaceImport) {
// Elide a namespace import if it is not referenced.
return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
else {
// Elide named imports if all of its import specifiers are elided.
const elements = visitNodes(node.elements, visitImportSpecifier, isImportSpecifier);
return some(elements) ? updateNamedImports(node, elements) : undefined;
}
}
/**
* Visits an import specifier, eliding it if it is not referenced.
*
* @param node The import specifier node.
*/
function visitImportSpecifier(node: ImportSpecifier): VisitResult<ImportSpecifier> {
// Elide an import specifier if it is not referenced.
return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
/**
* Visits an export assignment, eliding it if it does not contain a clause that resolves
* to a value.
*
* @param node The export assignment node.
*/
function visitExportAssignment(node: ExportAssignment): VisitResult<Statement> {
// Elide the export assignment if it does not reference a value.
return resolver.isValueAliasDeclaration(node)
? visitEachChild(node, visitor, context)
: undefined;
}
/**
* Visits an export declaration, eliding it if it does not contain a clause that resolves
* to a value.
*
* @param node The export declaration node.
*/
function visitExportDeclaration(node: ExportDeclaration): VisitResult<Statement> {
if (!node.exportClause) {
// Elide a star export if the module it references does not export a value.
return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined;
}
if (!resolver.isValueAliasDeclaration(node)) {
// Elide the export declaration if it does not export a value.
return undefined;
}
// Elide the export declaration if all of its named exports are elided.
const exportClause = visitNode(node.exportClause, visitNamedExports, isNamedExports, /*optional*/ true);
return exportClause
? updateExportDeclaration(
node,
/*decorators*/ undefined,
/*modifiers*/ undefined,
exportClause,
node.moduleSpecifier)
: undefined;
}
/**
* Visits named exports, eliding it if it does not contain an export specifier that
* resolves to a value.
*
* @param node The named exports node.
*/
function visitNamedExports(node: NamedExports): VisitResult<NamedExports> {
// Elide the named exports if all of its export specifiers were elided.
const elements = visitNodes(node.elements, visitExportSpecifier, isExportSpecifier);
return some(elements) ? updateNamedExports(node, elements) : undefined;
}
/**
* Visits an export specifier, eliding it if it does not resolve to a value.
*
* @param node The export specifier node.
*/
function visitExportSpecifier(node: ExportSpecifier): VisitResult<ExportSpecifier> {
// Elide an export specifier if it does not reference a value.
return resolver.isValueAliasDeclaration(node) ? node : undefined;
}
/**
* Determines whether to emit an import equals declaration.
*
@@ -2983,7 +3112,10 @@ namespace ts {
*/
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<Statement> {
if (isExternalModuleImportEqualsDeclaration(node)) {
return visitEachChild(node, visitor, context);
// Elide external module `import=` if it is not referenced.
return resolver.isReferencedAliasDeclaration(node)
? visitEachChild(node, visitor, context)
: undefined;
}
if (!shouldEmitImportEqualsDeclaration(node)) {
@@ -3069,7 +3201,7 @@ namespace ts {
return createStatement(expression, /*location*/ undefined);
}
function addExportMemberAssignment(statements: Statement[], node: DeclarationStatement) {
function addExportMemberAssignment(statements: Statement[], node: ClassDeclaration | FunctionDeclaration) {
const expression = createAssignment(
getExportName(node),
getLocalName(node, /*noSourceMaps*/ true)
@@ -3147,7 +3279,7 @@ namespace ts {
* @param noSourceMaps A value indicating whether source maps may not be emitted for the name.
* @param allowComments A value indicating whether comments may be emitted for the name.
*/
function getLocalName(node: DeclarationStatement | ClassExpression, noSourceMaps?: boolean, allowComments?: boolean) {
function getLocalName(node: FunctionDeclaration | ClassDeclaration | ClassExpression | ModuleDeclaration | EnumDeclaration, noSourceMaps?: boolean, allowComments?: boolean) {
return getDeclarationName(node, allowComments, !noSourceMaps, EmitFlags.LocalName);
}
@@ -3161,7 +3293,7 @@ namespace ts {
* @param noSourceMaps A value indicating whether source maps may not be emitted for the name.
* @param allowComments A value indicating whether comments may be emitted for the name.
*/
function getExportName(node: DeclarationStatement | ClassExpression, noSourceMaps?: boolean, allowComments?: boolean) {
function getExportName(node: FunctionDeclaration | ClassDeclaration | ClassExpression | ModuleDeclaration | EnumDeclaration, noSourceMaps?: boolean, allowComments?: boolean) {
if (isNamespaceExport(node)) {
return getNamespaceMemberName(getDeclarationName(node), allowComments, !noSourceMaps);
}
@@ -3177,9 +3309,9 @@ namespace ts {
* @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
* @param emitFlags Additional NodeEmitFlags to specify for the name.
*/
function getDeclarationName(node: DeclarationStatement | ClassExpression, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags?: EmitFlags) {
function getDeclarationName(node: FunctionDeclaration | ClassDeclaration | ClassExpression | ModuleDeclaration | EnumDeclaration, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags?: EmitFlags) {
if (node.name) {
const name = getMutableClone(node.name);
const name = getMutableClone(<Identifier>node.name);
emitFlags |= getEmitFlags(node.name);
if (!allowSourceMaps) {
emitFlags |= EmitFlags.NoSourceMap;
@@ -3217,25 +3349,6 @@ namespace ts {
}
}
function enableSubstitutionForAsyncMethodsWithSuper() {
if ((enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper) === 0) {
enabledSubstitutions |= TypeScriptSubstitutionFlags.AsyncMethodsWithSuper;
// We need to enable substitutions for call, property access, and element access
// if we need to rewrite super calls.
context.enableSubstitution(SyntaxKind.CallExpression);
context.enableSubstitution(SyntaxKind.PropertyAccessExpression);
context.enableSubstitution(SyntaxKind.ElementAccessExpression);
// We need to be notified when entering and exiting declarations that bind super.
context.enableEmitNotification(SyntaxKind.ClassDeclaration);
context.enableEmitNotification(SyntaxKind.MethodDeclaration);
context.enableEmitNotification(SyntaxKind.GetAccessor);
context.enableEmitNotification(SyntaxKind.SetAccessor);
context.enableEmitNotification(SyntaxKind.Constructor);
}
}
function enableSubstitutionForClassAliases() {
if ((enabledSubstitutions & TypeScriptSubstitutionFlags.ClassAliases) === 0) {
enabledSubstitutions |= TypeScriptSubstitutionFlags.ClassAliases;
@@ -3263,15 +3376,6 @@ namespace ts {
}
}
function isSuperContainer(node: Node): node is SuperContainer {
const kind = node.kind;
return kind === SyntaxKind.ClassDeclaration
|| kind === SyntaxKind.Constructor
|| kind === SyntaxKind.MethodDeclaration
|| kind === SyntaxKind.GetAccessor
|| kind === SyntaxKind.SetAccessor;
}
function isTransformedModuleDeclaration(node: Node): boolean {
return getOriginalNode(node).kind === SyntaxKind.ModuleDeclaration;
}
@@ -3288,12 +3392,6 @@ namespace ts {
*/
function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void {
const savedApplicableSubstitutions = applicableSubstitutions;
const savedCurrentSuperContainer = currentSuperContainer;
// If we need to support substitutions for `super` in an async method,
// we should track it here.
if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) {
currentSuperContainer = node;
}
if (enabledSubstitutions & TypeScriptSubstitutionFlags.NamespaceExports && isTransformedModuleDeclaration(node)) {
applicableSubstitutions |= TypeScriptSubstitutionFlags.NamespaceExports;
@@ -3306,7 +3404,6 @@ namespace ts {
previousOnEmitNode(emitContext, node, emitCallback);
applicableSubstitutions = savedApplicableSubstitutions;
currentSuperContainer = savedCurrentSuperContainer;
}
/**
@@ -3353,11 +3450,6 @@ namespace ts {
return substitutePropertyAccessExpression(<PropertyAccessExpression>node);
case SyntaxKind.ElementAccessExpression:
return substituteElementAccessExpression(<ElementAccessExpression>node);
case SyntaxKind.CallExpression:
if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper) {
return substituteCallExpression(<CallExpression>node);
}
break;
}
return node;
@@ -3412,54 +3504,11 @@ namespace ts {
return undefined;
}
function substituteCallExpression(node: CallExpression): Expression {
const expression = node.expression;
if (isSuperProperty(expression)) {
const flags = getSuperContainerAsyncMethodFlags();
if (flags) {
const argumentExpression = isPropertyAccessExpression(expression)
? substitutePropertyAccessExpression(expression)
: substituteElementAccessExpression(expression);
return createCall(
createPropertyAccess(argumentExpression, "call"),
/*typeArguments*/ undefined,
[
createThis(),
...node.arguments
]
);
}
}
return node;
}
function substitutePropertyAccessExpression(node: PropertyAccessExpression) {
if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) {
const flags = getSuperContainerAsyncMethodFlags();
if (flags) {
return createSuperAccessInAsyncMethod(
createLiteral(node.name.text),
flags,
node
);
}
}
return substituteConstantValue(node);
}
function substituteElementAccessExpression(node: ElementAccessExpression) {
if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) {
const flags = getSuperContainerAsyncMethodFlags();
if (flags) {
return createSuperAccessInAsyncMethod(
node.argumentExpression,
flags,
node
);
}
}
return substituteConstantValue(node);
}
@@ -3492,32 +3541,5 @@ namespace ts {
? resolver.getConstantValue(<PropertyAccessExpression | ElementAccessExpression>node)
: undefined;
}
function createSuperAccessInAsyncMethod(argumentExpression: Expression, flags: NodeCheckFlags, location: TextRange): LeftHandSideExpression {
if (flags & NodeCheckFlags.AsyncMethodWithSuperBinding) {
return createPropertyAccess(
createCall(
createIdentifier("_super"),
/*typeArguments*/ undefined,
[argumentExpression]
),
"value",
location
);
}
else {
return createCall(
createIdentifier("_super"),
/*typeArguments*/ undefined,
[argumentExpression],
location
);
}
}
function getSuperContainerAsyncMethodFlags() {
return currentSuperContainer !== undefined
&& resolver.getNodeCheckFlags(currentSuperContainer) & (NodeCheckFlags.AsyncMethodWithSuper | NodeCheckFlags.AsyncMethodWithSuperBinding);
}
}
}
+4 -3
View File
@@ -24,13 +24,14 @@
"visitor.ts",
"transformers/ts.ts",
"transformers/jsx.ts",
"transformers/es7.ts",
"transformers/es6.ts",
"transformers/es2017.ts",
"transformers/es2016.ts",
"transformers/es2015.ts",
"transformers/generators.ts",
"transformers/destructuring.ts",
"transformers/module/module.ts",
"transformers/module/system.ts",
"transformers/module/es6.ts",
"transformers/module/es2015.ts",
"transformer.ts",
"comments.ts",
"sourcemap.ts",
+528 -289
View File
File diff suppressed because it is too large Load Diff
+70 -35
View File
@@ -337,7 +337,7 @@ namespace ts {
export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile, languageVersion: ScriptTarget) {
// Any template literal or string literal with an extended escape
// (e.g. "\u{0067}") will need to be downleveled as a escaped string literal.
if (languageVersion < ScriptTarget.ES6 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
if (languageVersion < ScriptTarget.ES2015 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
return getQuotedEscapedLiteralText('"', node.text, '"');
}
@@ -345,7 +345,7 @@ namespace ts {
// the node's parent reference, then simply get the text as it was originally written.
if (!nodeIsSynthesized(node) && node.parent) {
const text = getSourceTextOfNodeFromSourceFile(sourceFile, node);
if (languageVersion < ScriptTarget.ES6 && isBinaryOrOctalIntegerLiteral(node, text)) {
if (languageVersion < ScriptTarget.ES2015 && isBinaryOrOctalIntegerLiteral(node, text)) {
return node.text;
}
return text;
@@ -609,7 +609,7 @@ namespace ts {
return !!(getCombinedNodeFlags(node) & NodeFlags.Let);
}
export function isSuperCallExpression(n: Node): boolean {
export function isSuperCall(n: Node): n is SuperCall {
return n.kind === SyntaxKind.CallExpression && (<CallExpression>n).expression.kind === SyntaxKind.SuperKeyword;
}
@@ -895,6 +895,12 @@ namespace ts {
return node && node.kind === SyntaxKind.MethodDeclaration && node.parent.kind === SyntaxKind.ObjectLiteralExpression;
}
export function isObjectLiteralOrClassExpressionMethod(node: Node): node is MethodDeclaration {
return node.kind === SyntaxKind.MethodDeclaration &&
(node.parent.kind === SyntaxKind.ObjectLiteralExpression ||
node.parent.kind === SyntaxKind.ClassExpression);
}
export function isIdentifierTypePredicate(predicate: TypePredicate): predicate is IdentifierTypePredicate {
return predicate && predicate.kind === TypePredicateKind.Identifier;
}
@@ -1047,7 +1053,7 @@ namespace ts {
/**
* Determines whether a node is a property or element access expression for super.
*/
export function isSuperProperty(node: Node): node is (PropertyAccessExpression | ElementAccessExpression) {
export function isSuperProperty(node: Node): node is SuperProperty {
const kind = node.kind;
return (kind === SyntaxKind.PropertyAccessExpression || kind === SyntaxKind.ElementAccessExpression)
&& (<PropertyAccessExpression | ElementAccessExpression>node).expression.kind === SyntaxKind.SuperKeyword;
@@ -1375,7 +1381,7 @@ namespace ts {
}
}
export function getNamespaceDeclarationNode(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration) {
export function getNamespaceDeclarationNode(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): ImportEqualsDeclaration | NamespaceImport {
if (node.kind === SyntaxKind.ImportEqualsDeclaration) {
return <ImportEqualsDeclaration>node;
}
@@ -1895,6 +1901,10 @@ namespace ts {
return node.kind === SyntaxKind.Identifier && (<Identifier>node).text === "Symbol";
}
export function isPushOrUnshiftIdentifier(node: Identifier) {
return node.text === "push" || node.text === "unshift";
}
export function isModifierKind(token: SyntaxKind): boolean {
switch (token) {
case SyntaxKind.AbstractKeyword:
@@ -2459,7 +2469,7 @@ namespace ts {
return file.moduleName || getExternalModuleNameFromPath(host, file.fileName);
}
export function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): string {
export function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): string {
const file = resolver.getExternalModuleFileFromDeclaration(declaration);
if (!file || isDeclarationFile(file)) {
return undefined;
@@ -2707,15 +2717,35 @@ namespace ts {
});
}
export function getSetAccessorTypeAnnotationNode(accessor: AccessorDeclaration): TypeNode {
/** Get the type annotaion for the value parameter. */
export function getSetAccessorTypeAnnotationNode(accessor: SetAccessorDeclaration): TypeNode {
if (accessor && accessor.parameters.length > 0) {
const hasThis = accessor.parameters.length === 2 &&
accessor.parameters[0].name.kind === SyntaxKind.Identifier &&
(accessor.parameters[0].name as Identifier).originalKeywordKind === SyntaxKind.ThisKeyword;
const hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
return accessor.parameters[hasThis ? 1 : 0].type;
}
}
export function getThisParameter(signature: SignatureDeclaration): ParameterDeclaration | undefined {
if (signature.parameters.length) {
const thisParameter = signature.parameters[0];
if (parameterIsThisKeyword(thisParameter)) {
return thisParameter;
}
}
}
export function parameterIsThisKeyword(parameter: ParameterDeclaration): boolean {
return isThisIdentifier(parameter.name);
}
export function isThisIdentifier(node: Node | undefined): boolean {
return node && node.kind === SyntaxKind.Identifier && identifierIsThisKeyword(node as Identifier);
}
export function identifierIsThisKeyword(id: Identifier): boolean {
return id.originalKeywordKind === SyntaxKind.ThisKeyword;
}
export interface AllAccessorDeclarations {
firstAccessor: AccessorDeclaration;
secondAccessor: AccessorDeclaration;
@@ -3476,7 +3506,7 @@ namespace ts {
return positionIsSynthesized(range.pos) ? -1 : skipTrivia(sourceFile.text, range.pos);
}
export function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver) {
export function collectExternalModuleInfo(sourceFile: SourceFile) {
const externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[] = [];
const exportSpecifiers = createMap<ExportSpecifier[]>();
let exportEquals: ExportAssignment = undefined;
@@ -3484,19 +3514,16 @@ namespace ts {
for (const node of sourceFile.statements) {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
if (!(<ImportDeclaration>node).importClause ||
resolver.isReferencedAliasDeclaration((<ImportDeclaration>node).importClause, /*checkChildren*/ true)) {
// import "mod"
// import x from "mod" where x is referenced
// import * as x from "mod" where x is referenced
// import { x, y } from "mod" where at least one import is referenced
externalImports.push(<ImportDeclaration>node);
}
// import "mod"
// import x from "mod"
// import * as x from "mod"
// import { x, y } from "mod"
externalImports.push(<ImportDeclaration>node);
break;
case SyntaxKind.ImportEqualsDeclaration:
if ((<ImportEqualsDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference && resolver.isReferencedAliasDeclaration(node)) {
// import x = require("mod") where x is referenced
if ((<ImportEqualsDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference) {
// import x = require("mod")
externalImports.push(<ImportEqualsDeclaration>node);
}
break;
@@ -3505,13 +3532,11 @@ namespace ts {
if ((<ExportDeclaration>node).moduleSpecifier) {
if (!(<ExportDeclaration>node).exportClause) {
// export * from "mod"
if (resolver.moduleExportsSomeValue((<ExportDeclaration>node).moduleSpecifier)) {
externalImports.push(<ExportDeclaration>node);
hasExportStarsToExportValues = true;
}
externalImports.push(<ExportDeclaration>node);
hasExportStarsToExportValues = true;
}
else if (resolver.isValueAliasDeclaration(node)) {
// export { x, y } from "mod" where at least one export is a value symbol
else {
// export { x, y } from "mod"
externalImports.push(<ExportDeclaration>node);
}
}
@@ -3605,14 +3630,14 @@ namespace ts {
return SyntaxKind.FirstTemplateToken <= kind && kind <= SyntaxKind.LastTemplateToken;
}
function isTemplateLiteralFragmentKind(kind: SyntaxKind) {
return kind === SyntaxKind.TemplateHead
|| kind === SyntaxKind.TemplateMiddle
|| kind === SyntaxKind.TemplateTail;
export function isTemplateHead(node: Node): node is TemplateHead {
return node.kind === SyntaxKind.TemplateHead;
}
export function isTemplateLiteralFragment(node: Node): node is TemplateLiteralFragment {
return isTemplateLiteralFragmentKind(node.kind);
export function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail {
const kind = node.kind;
return kind === SyntaxKind.TemplateMiddle
|| kind === SyntaxKind.TemplateTail;
}
// Identifiers
@@ -3777,7 +3802,7 @@ namespace ts {
return node.kind === SyntaxKind.CallExpression;
}
export function isTemplate(node: Node): node is Template {
export function isTemplateLiteral(node: Node): node is TemplateLiteral {
const kind = node.kind;
return kind === SyntaxKind.TemplateExpression
|| kind === SyntaxKind.NoSubstitutionTemplateLiteral;
@@ -4141,7 +4166,17 @@ namespace ts {
namespace ts {
export function getDefaultLibFileName(options: CompilerOptions): string {
return options.target === ScriptTarget.ES6 ? "lib.es6.d.ts" : "lib.d.ts";
switch (options.target) {
case ScriptTarget.ES2017:
return "lib.es2017.d.ts";
case ScriptTarget.ES2016:
return "lib.es2016.d.ts";
case ScriptTarget.ES2015:
return "lib.es6.d.ts";
default:
return "lib.d.ts";
}
}
export function textSpanEnd(span: TextSpan) {
+5 -4
View File
@@ -799,7 +799,7 @@ namespace ts {
case SyntaxKind.TaggedTemplateExpression:
return updateTaggedTemplate(<TaggedTemplateExpression>node,
visitNode((<TaggedTemplateExpression>node).tag, visitor, isExpression),
visitNode((<TaggedTemplateExpression>node).template, visitor, isTemplate));
visitNode((<TaggedTemplateExpression>node).template, visitor, isTemplateLiteral));
case SyntaxKind.ParenthesizedExpression:
return updateParen(<ParenthesizedExpression>node,
@@ -807,6 +807,7 @@ namespace ts {
case SyntaxKind.FunctionExpression:
return updateFunctionExpression(<FunctionExpression>node,
visitNodes((<FunctionExpression>node).modifiers, visitor, isModifier),
visitNode((<FunctionExpression>node).name, visitor, isPropertyName),
visitNodes((<FunctionExpression>node).typeParameters, visitor, isTypeParameter),
(context.startLexicalEnvironment(), visitNodes((<FunctionExpression>node).parameters, visitor, isParameter)),
@@ -862,7 +863,7 @@ namespace ts {
case SyntaxKind.TemplateExpression:
return updateTemplateExpression(<TemplateExpression>node,
visitNode((<TemplateExpression>node).head, visitor, isTemplateLiteralFragment),
visitNode((<TemplateExpression>node).head, visitor, isTemplateHead),
visitNodes((<TemplateExpression>node).templateSpans, visitor, isTemplateSpan));
case SyntaxKind.YieldExpression:
@@ -890,7 +891,7 @@ namespace ts {
case SyntaxKind.TemplateSpan:
return updateTemplateSpan(<TemplateSpan>node,
visitNode((<TemplateSpan>node).expression, visitor, isExpression),
visitNode((<TemplateSpan>node).literal, visitor, isTemplateLiteralFragment));
visitNode((<TemplateSpan>node).literal, visitor, isTemplateMiddleOrTemplateTail));
// Element
case SyntaxKind.Block:
@@ -1357,4 +1358,4 @@ namespace ts {
}
}
}
}
}
+95 -4
View File
@@ -1,4 +1,4 @@
//
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -427,7 +427,7 @@ namespace FourSlash {
if (exists !== negative) {
this.printErrorLog(negative, this.getAllDiagnostics());
throw new Error("Failure between markers: " + startMarkerName + ", " + endMarkerName);
throw new Error(`Failure between markers: '${startMarkerName}', '${endMarkerName}'`);
}
}
@@ -742,7 +742,6 @@ namespace FourSlash {
}
}
public verifyCompletionListAllowsNewIdentifier(negative: boolean) {
const completions = this.getCompletionListAtCaret();
@@ -754,6 +753,13 @@ namespace FourSlash {
}
}
public verifyCompletionListIsGlobal(expected: boolean) {
const completions = this.getCompletionListAtCaret();
if (completions && completions.isGlobalCompletion !== expected) {
this.raiseError(`verifyCompletionListIsGlobal failed - expected result to be ${completions.isGlobalCompletion}`);
}
}
public verifyCompletionListContains(symbol: string, text?: string, documentation?: string, kind?: string, spanIndex?: number) {
const completions = this.getCompletionListAtCaret();
if (completions) {
@@ -1604,7 +1610,7 @@ namespace FourSlash {
if (isFormattingEdit) {
const newContent = this.getFileContent(fileName);
if (newContent.replace(/\s/g, "") !== oldContent.replace(/\s/g, "")) {
if (this.removeWhitespace(newContent) !== this.removeWhitespace(oldContent)) {
this.raiseError("Formatting operation destroyed non-whitespace content");
}
}
@@ -1670,6 +1676,10 @@ namespace FourSlash {
}
}
private removeWhitespace(text: string): string {
return text.replace(/\s/g, "");
}
public goToBOF() {
this.goToPosition(0);
}
@@ -2031,6 +2041,47 @@ namespace FourSlash {
}
}
private getCodeFixes(errorCode?: number) {
const fileName = this.activeFile.fileName;
const diagnostics = this.getDiagnostics(fileName);
if (diagnostics.length === 0) {
this.raiseError("Errors expected.");
}
if (diagnostics.length > 1 && errorCode !== undefined) {
this.raiseError("When there's more than one error, you must specify the errror to fix.");
}
const diagnostic = !errorCode ? diagnostics[0] : ts.find(diagnostics, d => d.code == errorCode);
return this.languageService.getCodeFixesAtPosition(fileName, diagnostic.start, diagnostic.length, [diagnostic.code]);
}
public verifyCodeFixAtPosition(expectedText: string, errorCode?: number) {
const ranges = this.getRanges();
if (ranges.length == 0) {
this.raiseError("At least one range should be specified in the testfile.");
}
const actual = this.getCodeFixes(errorCode);
if (!actual || actual.length == 0) {
this.raiseError("No codefixes returned.");
}
if (actual.length > 1) {
this.raiseError("More than 1 codefix returned.");
}
this.applyEdits(actual[0].changes[0].fileName, actual[0].changes[0].textChanges, /*isFormattingEdit*/ false);
const actualText = this.rangeText(ranges[0]);
if (this.removeWhitespace(actualText) !== this.removeWhitespace(expectedText)) {
this.raiseError(`Actual text doesn't match expected text. Actual: '${actualText}' Expected: '${expectedText}'`);
}
}
public verifyDocCommentTemplate(expected?: ts.TextInsertion) {
const name = "verifyDocCommentTemplate";
const actual = this.languageService.getDocCommentTemplateAtPosition(this.activeFile.fileName, this.currentCaretPosition);
@@ -2204,6 +2255,18 @@ namespace FourSlash {
}
}
public verifyNavigationTree(json: any) {
const tree = this.languageService.getNavigationTree(this.activeFile.fileName);
if (JSON.stringify(tree, replacer) !== JSON.stringify(json)) {
this.raiseError(`verifyNavigationTree failed - expected: ${stringify(json)}, got: ${stringify(tree, replacer)}`);
}
function replacer(key: string, value: any) {
// Don't check "spans", and omit falsy values.
return key === "spans" ? undefined : (value || undefined);
}
}
public printNavigationItems(searchValue: string) {
const items = this.languageService.getNavigateToItems(searchValue);
const length = items && items.length;
@@ -2302,6 +2365,18 @@ namespace FourSlash {
}
}
public verifyCodeFixAvailable(negative: boolean, errorCode?: number) {
const fixes = this.getCodeFixes(errorCode);
if (negative && fixes && fixes.length > 0) {
this.raiseError(`verifyCodeFixAvailable failed - expected no fixes, actual: ${fixes.length}`);
}
if (!negative && (fixes === undefined || fixes.length === 0)) {
this.raiseError(`verifyCodeFixAvailable failed - expected code fixes, actual: 0`);
}
}
// Get the text of the entire line the caret is currently at
private getCurrentLineContent() {
const text = this.getFileContent(this.activeFile.fileName);
@@ -3046,6 +3121,10 @@ namespace FourSlashInterface {
this.state.verifyCompletionListIsEmpty(this.negative);
}
public completionListIsGlobal(expected: boolean) {
this.state.verifyCompletionListIsGlobal(expected);
}
public completionListAllowsNewIdentifier() {
this.state.verifyCompletionListAllowsNewIdentifier(this.negative);
}
@@ -3085,6 +3164,10 @@ namespace FourSlashInterface {
public isValidBraceCompletionAtPosition(openingBrace: string) {
this.state.verifyBraceCompletionAtPosition(this.negative, openingBrace);
}
public codeFixAvailable(errorCode?: number) {
this.state.verifyCodeFixAvailable(this.negative, errorCode);
}
}
export class Verify extends VerifyNegatable {
@@ -3264,10 +3347,18 @@ namespace FourSlashInterface {
this.DocCommentTemplate(/*expectedText*/ undefined, /*expectedOffset*/ undefined, /*empty*/ true);
}
public codeFixAtPosition(expectedText: string, errorCode?: number): void {
this.state.verifyCodeFixAtPosition(expectedText, errorCode);
}
public navigationBar(json: any) {
this.state.verifyNavigationBar(json);
}
public navigationTree(json: any) {
this.state.verifyNavigationTree(json);
}
public navigationItemsListCount(count: number, searchValue: string, matchKind?: string, fileName?: string) {
this.state.verifyNavigationItemsCount(count, searchValue, matchKind, fileName);
}
+13 -3
View File
@@ -509,7 +509,7 @@ namespace Harness {
tryEnableSourceMapsForHost?(): void;
getEnvironmentVariable?(name: string): string;
}
export var IO: IO;
export let IO: IO;
// harness always uses one kind of new line
const harnessNewLine = "\r\n";
@@ -941,7 +941,17 @@ namespace Harness {
}
export function getDefaultLibFileName(options: ts.CompilerOptions): string {
return options.target === ts.ScriptTarget.ES6 ? es2015DefaultLibFileName : defaultLibFileName;
switch (options.target) {
case ts.ScriptTarget.ES2017:
return "lib.es2017.d.ts";
case ts.ScriptTarget.ES2016:
return "lib.es2016.d.ts";
case ts.ScriptTarget.ES2015:
return es2015DefaultLibFileName;
default:
return defaultLibFileName;
}
}
// Cache these between executions so we don't have to re-parse them for every test
@@ -1634,7 +1644,7 @@ namespace Harness {
export function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[]): string {
// Collect, test, and sort the fileNames
outputFiles.sort((a, b) => cleanName(a.fileName).localeCompare(cleanName(b.fileName)));
outputFiles.sort((a, b) => ts.compareStrings(cleanName(a.fileName), cleanName(b.fileName)));
// Emit them
let result = "";
+7
View File
@@ -459,6 +459,10 @@ namespace Harness.LanguageService {
getNavigationBarItems(fileName: string): ts.NavigationBarItem[] {
return unwrapJSONCallResult(this.shim.getNavigationBarItems(fileName));
}
getNavigationTree(fileName: string): ts.NavigationTree {
return unwrapJSONCallResult(this.shim.getNavigationTree(fileName));
}
getOutliningSpans(fileName: string): ts.OutliningSpan[] {
return unwrapJSONCallResult(this.shim.getOutliningSpans(fileName));
}
@@ -486,6 +490,9 @@ namespace Harness.LanguageService {
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean {
return unwrapJSONCallResult(this.shim.isValidBraceCompletionAtPosition(fileName, position, openingBrace));
}
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): ts.CodeAction[] {
throw new Error("Not supported on the shim.");
}
getEmitOutput(fileName: string): ts.EmitOutput {
return unwrapJSONCallResult(this.shim.getEmitOutput(fileName));
}
+4 -3
View File
@@ -26,13 +26,14 @@
"../compiler/visitor.ts",
"../compiler/transformers/ts.ts",
"../compiler/transformers/jsx.ts",
"../compiler/transformers/es7.ts",
"../compiler/transformers/es6.ts",
"../compiler/transformers/es2017.ts",
"../compiler/transformers/es2016.ts",
"../compiler/transformers/es2015.ts",
"../compiler/transformers/generators.ts",
"../compiler/transformers/destructuring.ts",
"../compiler/transformers/module/module.ts",
"../compiler/transformers/module/system.ts",
"../compiler/transformers/module/es6.ts",
"../compiler/transformers/module/es2015.ts",
"../compiler/transformer.ts",
"../compiler/comments.ts",
"../compiler/sourcemap.ts",
+1 -1
View File
@@ -165,7 +165,7 @@ namespace ts {
start: undefined,
length: undefined,
}, {
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015'",
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017'",
category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
+21 -19
View File
@@ -3,6 +3,8 @@
/// <reference path="../../server/typingsInstaller/typingsInstaller.ts" />
namespace ts.projectSystem {
import CommandNames = server.CommandNames;
function createTestTypingsInstaller(host: server.ServerHost) {
return new TestTypingsInstaller("/a/data/", /*throttleLimit*/5, host);
}
@@ -75,7 +77,7 @@ namespace ts.projectSystem {
};
// Change the content of file1 to `export var T: number;export function Foo() { };`
changeModuleFile1ShapeRequest1 = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
changeModuleFile1ShapeRequest1 = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 1,
@@ -85,7 +87,7 @@ namespace ts.projectSystem {
});
// Change the content of file1 to `export var T: number;export function Foo() { };`
changeModuleFile1InternalRequest1 = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
changeModuleFile1InternalRequest1 = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 1,
@@ -95,7 +97,7 @@ namespace ts.projectSystem {
});
// Change the content of file1 to `export var T: number;export function Foo() { };`
changeModuleFile1ShapeRequest2 = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
changeModuleFile1ShapeRequest2 = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 1,
@@ -104,7 +106,7 @@ namespace ts.projectSystem {
insertString: `export var T2: number;`
});
moduleFile1FileListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path, projectFileName: configFile.path });
moduleFile1FileListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path, projectFileName: configFile.path });
});
it("should contains only itself if a module file's shape didn't change, and all files referencing it if its shape changed", () => {
@@ -120,7 +122,7 @@ namespace ts.projectSystem {
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2] }]);
// Change the content of file1 to `export var T: number;export function Foo() { console.log('hi'); };`
const changeFile1InternalRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const changeFile1InternalRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 46,
@@ -143,7 +145,7 @@ namespace ts.projectSystem {
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2] }]);
// Change file2 content to `let y = Foo();`
const removeFile1Consumer1ImportRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const removeFile1Consumer1ImportRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: file1Consumer1.path,
line: 1,
offset: 1,
@@ -156,7 +158,7 @@ namespace ts.projectSystem {
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer2] }]);
// Add the import statements back to file2
const addFile2ImportRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const addFile2ImportRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: file1Consumer1.path,
line: 1,
offset: 1,
@@ -167,7 +169,7 @@ namespace ts.projectSystem {
session.executeCommand(addFile2ImportRequest);
// Change the content of file1 to `export var T2: string;export var T: number;export function Foo() { };`
const changeModuleFile1ShapeRequest2 = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const changeModuleFile1ShapeRequest2 = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 1,
@@ -272,7 +274,7 @@ namespace ts.projectSystem {
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
openFilesForSession([globalFile3], session);
const changeGlobalFile3ShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const changeGlobalFile3ShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: globalFile3.path,
line: 1,
offset: 1,
@@ -283,7 +285,7 @@ namespace ts.projectSystem {
// check after file1 shape changes
session.executeCommand(changeGlobalFile3ShapeRequest);
const globalFile3FileListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: globalFile3.path });
const globalFile3FileListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: globalFile3.path });
sendAffectedFileRequestAndCheckResult(session, globalFile3FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2] }]);
});
@@ -316,7 +318,7 @@ namespace ts.projectSystem {
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
openFilesForSession([moduleFile1], session);
const file1ChangeShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const file1ChangeShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 27,
@@ -345,7 +347,7 @@ namespace ts.projectSystem {
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
openFilesForSession([moduleFile1], session);
const file1ChangeShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const file1ChangeShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 27,
@@ -369,7 +371,7 @@ namespace ts.projectSystem {
openFilesForSession([moduleFile1, file1Consumer1], session);
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer1Consumer1] }]);
const changeFile1Consumer1ShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const changeFile1Consumer1ShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: file1Consumer1.path,
line: 2,
offset: 1,
@@ -400,7 +402,7 @@ namespace ts.projectSystem {
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
openFilesForSession([file1, file2], session);
const file1AffectedListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: file1.path });
const file1AffectedListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: file1.path });
sendAffectedFileRequestAndCheckResult(session, file1AffectedListRequest, [{ projectFileName: configFile.path, files: [file1, file2] }]);
});
@@ -415,7 +417,7 @@ namespace ts.projectSystem {
const session = createSession(host);
openFilesForSession([file1, file2, file3], session);
const file1AffectedListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: file1.path });
const file1AffectedListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: file1.path });
sendAffectedFileRequestAndCheckResult(session, file1AffectedListRequest, [
{ projectFileName: configFile1.path, files: [file1, file2] },
@@ -437,11 +439,11 @@ namespace ts.projectSystem {
host.reloadFS([referenceFile1, configFile]);
host.triggerFileWatcherCallback(moduleFile1.path, /*removed*/ true);
const request = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path });
const request = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path });
sendAffectedFileRequestAndCheckResult(session, request, [
{ projectFileName: configFile.path, files: [referenceFile1] }
]);
const requestForMissingFile = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path });
const requestForMissingFile = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path });
sendAffectedFileRequestAndCheckResult(session, requestForMissingFile, []);
});
@@ -456,7 +458,7 @@ namespace ts.projectSystem {
const session = createSession(host);
openFilesForSession([referenceFile1], session);
const request = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path });
const request = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path });
sendAffectedFileRequestAndCheckResult(session, request, [
{ projectFileName: configFile.path, files: [referenceFile1] }
]);
@@ -483,7 +485,7 @@ namespace ts.projectSystem {
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
openFilesForSession([file1, file2], session);
const compileFileRequest = makeSessionRequest<server.protocol.CompileOnSaveEmitFileRequestArgs>(server.CommandNames.CompileOnSaveEmitFile, { file: file1.path, projectFileName: configFile.path });
const compileFileRequest = makeSessionRequest<server.protocol.CompileOnSaveEmitFileRequestArgs>(CommandNames.CompileOnSaveEmitFile, { file: file1.path, projectFileName: configFile.path });
session.executeCommand(compileFileRequest);
const expectedEmittedFileName = "/a/b/f1.js";
@@ -176,7 +176,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015'",
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017'",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -405,6 +405,7 @@ namespace ts {
allowJs: true,
maxNodeModuleJsDepth: 2,
allowSyntheticDefaultImports: true,
skipLibCheck: true,
module: ModuleKind.CommonJS,
target: ScriptTarget.ES5,
noImplicitAny: false,
@@ -433,6 +434,7 @@ namespace ts {
allowJs: false,
maxNodeModuleJsDepth: 2,
allowSyntheticDefaultImports: true,
skipLibCheck: true,
module: ModuleKind.CommonJS,
target: ScriptTarget.ES5,
noImplicitAny: false,
@@ -456,7 +458,8 @@ namespace ts {
{
allowJs: true,
maxNodeModuleJsDepth: 2,
allowSyntheticDefaultImports: true
allowSyntheticDefaultImports: true,
skipLibCheck: true
},
errors: [{
file: undefined,
@@ -477,7 +480,8 @@ namespace ts {
{
allowJs: true,
maxNodeModuleJsDepth: 2,
allowSyntheticDefaultImports: true
allowSyntheticDefaultImports: true,
skipLibCheck: true
},
errors: <Diagnostic[]>[]
}
+1 -1
View File
@@ -1017,7 +1017,7 @@ import b = require("./moduleB");
const files = [f1, f2, f3, f4];
const names = map(files, f => f.name);
const sourceFiles = arrayToMap(map(files, f => createSourceFile(f.name, f.content, ScriptTarget.ES6)), f => f.fileName);
const sourceFiles = arrayToMap(map(files, f => createSourceFile(f.name, f.content, ScriptTarget.ES2015)), f => f.fileName);
const compilerHost: CompilerHost = {
fileExists : fileName => fileName in sourceFiles,
getSourceFile: fileName => sourceFiles[fileName],
+4
View File
@@ -253,6 +253,10 @@ var x = 0;`, {
options: { compilerOptions: { allowUnusedLabels: true }, fileName: "input.js", reportDiagnostics: true }
});
transpilesCorrectly("Supports setting 'alwaysStrict'", "x;", {
options: { compilerOptions: { alwaysStrict: true }, fileName: "input.js", reportDiagnostics: true }
});
transpilesCorrectly("Supports setting 'baseUrl'", "x;", {
options: { compilerOptions: { baseUrl: "./folder/baseUrl" }, fileName: "input.js", reportDiagnostics: true }
});
+379 -22
View File
@@ -1,8 +1,10 @@
/// <reference path="..\harness.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="../../server/typingsInstaller/typingsInstaller.ts" />
namespace ts.projectSystem {
import TI = server.typingsInstaller;
import protocol = server.protocol;
import CommandNames = server.CommandNames;
const safeList = {
path: <Path>"/safeList.json",
@@ -17,10 +19,8 @@ namespace ts.projectSystem {
export interface PostExecAction {
readonly requestKind: TI.RequestKind;
readonly error: Error;
readonly stdout: string;
readonly stderr: string;
readonly callback: (err: Error, stdout: string, stderr: string) => void;
readonly success: boolean;
readonly callback: TI.RequestCompletedAction;
}
export function notImplemented(): any {
@@ -52,7 +52,7 @@ namespace ts.projectSystem {
export class TestTypingsInstaller extends TI.TypingsInstaller implements server.ITypingsInstaller {
protected projectService: server.ProjectService;
constructor(readonly globalTypingsCacheLocation: string, throttleLimit: number, readonly installTypingHost: server.ServerHost, log?: TI.Log) {
super(globalTypingsCacheLocation, "npm", safeList.path, throttleLimit, log);
super(globalTypingsCacheLocation, safeList.path, throttleLimit, log);
this.init();
}
@@ -63,7 +63,7 @@ namespace ts.projectSystem {
const actionsToRun = this.postExecActions;
this.postExecActions = [];
for (const action of actionsToRun) {
action.callback(action.error, action.stdout, action.stderr);
action.callback(action.success);
}
}
@@ -83,7 +83,7 @@ namespace ts.projectSystem {
return this.installTypingHost;
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: (err: Error, stdout: string, stderr: string) => void): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
switch (requestKind) {
case TI.NpmViewRequest:
case TI.NpmInstallRequest:
@@ -106,9 +106,7 @@ namespace ts.projectSystem {
addPostExecAction(requestKind: TI.RequestKind, stdout: string | string[], cb: TI.RequestCompletedAction) {
const out = typeof stdout === "string" ? stdout : createNpmPackageJsonString(stdout);
const action: PostExecAction = {
error: undefined,
stdout: out,
stderr: "",
success: !!out,
callback: cb,
requestKind
};
@@ -128,7 +126,7 @@ namespace ts.projectSystem {
return combinePaths(getDirectoryPath(libFile.path), "tsc.js");
}
export function toExternalFile(fileName: string): server.protocol.ExternalFile {
export function toExternalFile(fileName: string): protocol.ExternalFile {
return { fileName };
}
@@ -136,6 +134,19 @@ namespace ts.projectSystem {
return map(fileNames, toExternalFile);
}
export class TestServerEventManager {
public events: server.ProjectServiceEvent[] = [];
handler: server.ProjectServiceEventHandler = (event: server.ProjectServiceEvent) => {
this.events.push(event);
}
checkEventCountOfType(eventType: "context" | "configFileDiag", expectedCount: number) {
const eventsOfType = filter(this.events, e => e.eventName === eventType);
assert.equal(eventsOfType.length, expectedCount, `The actual event counts of type ${eventType} is ${eventsOfType.length}, while expected ${expectedCount}`);
}
}
export interface TestServerHostCreationParameters {
useCaseSensitiveFileNames?: boolean;
executingFilePath?: string;
@@ -159,11 +170,11 @@ namespace ts.projectSystem {
return host;
}
export function createSession(host: server.ServerHost, typingsInstaller?: server.ITypingsInstaller) {
export function createSession(host: server.ServerHost, typingsInstaller?: server.ITypingsInstaller, projectServiceEventHandler?: server.ProjectServiceEventHandler) {
if (typingsInstaller === undefined) {
typingsInstaller = new TestTypingsInstaller("/a/data/", /*throttleLimit*/5, host);
}
return new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
return new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ projectServiceEventHandler !== undefined, projectServiceEventHandler);
}
export interface CreateProjectServiceParameters {
@@ -514,7 +525,7 @@ namespace ts.projectSystem {
}
export function makeSessionRequest<T>(command: string, args: T) {
const newRequest: server.protocol.Request = {
const newRequest: protocol.Request = {
seq: 0,
type: "request",
command,
@@ -525,7 +536,7 @@ namespace ts.projectSystem {
export function openFilesForSession(files: FileOrFolder[], session: server.Session) {
for (const file of files) {
const request = makeSessionRequest<server.protocol.OpenRequestArgs>(server.CommandNames.Open, { file: file.path });
const request = makeSessionRequest<protocol.OpenRequestArgs>(CommandNames.Open, { file: file.path });
session.executeCommand(request);
}
}
@@ -1738,7 +1749,7 @@ namespace ts.projectSystem {
});
describe("navigate-to for javascript project", () => {
function containsNavToItem(items: server.protocol.NavtoItem[], itemName: string, itemKind: string) {
function containsNavToItem(items: protocol.NavtoItem[], itemName: string, itemKind: string) {
return find(items, item => item.name === itemName && item.kind === itemKind) !== undefined;
}
@@ -1756,12 +1767,12 @@ namespace ts.projectSystem {
openFilesForSession([file1], session);
// Try to find some interface type defined in lib.d.ts
const libTypeNavToRequest = makeSessionRequest<server.protocol.NavtoRequestArgs>(server.CommandNames.Navto, { searchValue: "Document", file: file1.path, projectFileName: configFile.path });
const items: server.protocol.NavtoItem[] = session.executeCommand(libTypeNavToRequest).response;
const libTypeNavToRequest = makeSessionRequest<protocol.NavtoRequestArgs>(CommandNames.Navto, { searchValue: "Document", file: file1.path, projectFileName: configFile.path });
const items: protocol.NavtoItem[] = session.executeCommand(libTypeNavToRequest).response;
assert.isFalse(containsNavToItem(items, "Document", "interface"), `Found lib.d.ts symbol in JavaScript project nav to request result.`);
const localFunctionNavToRequst = makeSessionRequest<server.protocol.NavtoRequestArgs>(server.CommandNames.Navto, { searchValue: "foo", file: file1.path, projectFileName: configFile.path });
const items2: server.protocol.NavtoItem[] = session.executeCommand(localFunctionNavToRequst).response;
const localFunctionNavToRequst = makeSessionRequest<protocol.NavtoRequestArgs>(CommandNames.Navto, { searchValue: "foo", file: file1.path, projectFileName: configFile.path });
const items2: protocol.NavtoItem[] = session.executeCommand(localFunctionNavToRequst).response;
assert.isTrue(containsNavToItem(items2, "foo", "function"), `Cannot find function symbol "foo".`);
});
});
@@ -1898,6 +1909,64 @@ namespace ts.projectSystem {
projectService.closeExternalProject(projectName);
projectService.checkNumberOfProjects({});
});
it("correctly handles changes in lib section of config file", () => {
const libES5 = {
path: "/compiler/lib.es5.d.ts",
content: "declare const eval: any"
};
const libES2015Promise = {
path: "/compiler/lib.es2015.promise.d.ts",
content: "declare class Promise<T> {}"
};
const app = {
path: "/src/app.ts",
content: "var x: Promise<string>;"
};
const config1 = {
path: "/src/tsconfig.json",
content: JSON.stringify(
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": true,
"sourceMap": false,
"lib": [
"es5"
]
}
})
};
const config2 = {
path: config1.path,
content: JSON.stringify(
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": true,
"sourceMap": false,
"lib": [
"es5",
"es2015.promise"
]
}
})
};
const host = createServerHost([libES5, libES2015Promise, app, config1], { executingFilePath: "/compiler/tsc.js" });
const projectService = createProjectService(host);
projectService.openClientFile(app.path);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [libES5.path, app.path]);
host.reloadFS([libES5, libES2015Promise, app, config2]);
host.triggerFileWatcherCallback(config1.path);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [libES5.path, libES2015Promise.path, app.path]);
});
});
describe("prefer typings to js", () => {
@@ -2026,7 +2095,7 @@ namespace ts.projectSystem {
const projectFileName = "externalProject";
const host = createServerHost([f]);
const projectService = createProjectService(host);
// create a project
// create a project
projectService.openExternalProject({ projectFileName, rootFiles: [toExternalFile(f.path)], options: {} });
projectService.checkNumberOfProjects({ externalProjects: 1 });
@@ -2063,4 +2132,292 @@ namespace ts.projectSystem {
projectService.inferredProjects[0].getLanguageService().getProgram();
});
});
describe("rename a module file and rename back", () => {
it("should restore the states for inferred projects", () => {
const moduleFile = {
path: "/a/b/moduleFile.ts",
content: "export function bar() { };"
};
const file1 = {
path: "/a/b/file1.ts",
content: "import * as T from './moduleFile'; T.bar();"
};
const host = createServerHost([moduleFile, file1]);
const session = createSession(host);
openFilesForSession([file1], session);
const getErrRequest = makeSessionRequest<server.protocol.SemanticDiagnosticsSyncRequestArgs>(
server.CommandNames.SemanticDiagnosticsSync,
{ file: file1.path }
);
let diags = <server.protocol.Diagnostic[]>session.executeCommand(getErrRequest).response;
assert.equal(diags.length, 0);
const moduleFileOldPath = moduleFile.path;
const moduleFileNewPath = "/a/b/moduleFile1.ts";
moduleFile.path = moduleFileNewPath;
host.reloadFS([moduleFile, file1]);
host.triggerFileWatcherCallback(moduleFileOldPath);
host.triggerDirectoryWatcherCallback("/a/b", moduleFile.path);
host.runQueuedTimeoutCallbacks();
diags = <server.protocol.Diagnostic[]>session.executeCommand(getErrRequest).response;
assert.equal(diags.length, 1);
moduleFile.path = moduleFileOldPath;
host.reloadFS([moduleFile, file1]);
host.triggerFileWatcherCallback(moduleFileNewPath);
host.triggerDirectoryWatcherCallback("/a/b", moduleFile.path);
host.runQueuedTimeoutCallbacks();
// Make a change to trigger the program rebuild
const changeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(
server.CommandNames.Change,
{ file: file1.path, line: 1, offset: 44, endLine: 1, endOffset: 44, insertString: "\n" }
);
session.executeCommand(changeRequest);
host.runQueuedTimeoutCallbacks();
diags = <server.protocol.Diagnostic[]>session.executeCommand(getErrRequest).response;
assert.equal(diags.length, 0);
});
it("should restore the states for configured projects", () => {
const moduleFile = {
path: "/a/b/moduleFile.ts",
content: "export function bar() { };"
};
const file1 = {
path: "/a/b/file1.ts",
content: "import * as T from './moduleFile'; T.bar();"
};
const configFile = {
path: "/a/b/tsconfig.json",
content: `{}`
};
const host = createServerHost([moduleFile, file1, configFile]);
const session = createSession(host);
openFilesForSession([file1], session);
const getErrRequest = makeSessionRequest<server.protocol.SemanticDiagnosticsSyncRequestArgs>(
server.CommandNames.SemanticDiagnosticsSync,
{ file: file1.path }
);
let diags = <server.protocol.Diagnostic[]>session.executeCommand(getErrRequest).response;
assert.equal(diags.length, 0);
const moduleFileOldPath = moduleFile.path;
const moduleFileNewPath = "/a/b/moduleFile1.ts";
moduleFile.path = moduleFileNewPath;
host.reloadFS([moduleFile, file1, configFile]);
host.triggerFileWatcherCallback(moduleFileOldPath);
host.triggerDirectoryWatcherCallback("/a/b", moduleFile.path);
host.runQueuedTimeoutCallbacks();
diags = <server.protocol.Diagnostic[]>session.executeCommand(getErrRequest).response;
assert.equal(diags.length, 1);
moduleFile.path = moduleFileOldPath;
host.reloadFS([moduleFile, file1, configFile]);
host.triggerFileWatcherCallback(moduleFileNewPath);
host.triggerDirectoryWatcherCallback("/a/b", moduleFile.path);
host.runQueuedTimeoutCallbacks();
diags = <server.protocol.Diagnostic[]>session.executeCommand(getErrRequest).response;
assert.equal(diags.length, 0);
});
});
describe("add the missing module file for inferred project", () => {
it("should remove the `module not found` error", () => {
const moduleFile = {
path: "/a/b/moduleFile.ts",
content: "export function bar() { };"
};
const file1 = {
path: "/a/b/file1.ts",
content: "import * as T from './moduleFile'; T.bar();"
};
const host = createServerHost([file1]);
const session = createSession(host);
openFilesForSession([file1], session);
const getErrRequest = makeSessionRequest<server.protocol.SemanticDiagnosticsSyncRequestArgs>(
server.CommandNames.SemanticDiagnosticsSync,
{ file: file1.path }
);
let diags = <server.protocol.Diagnostic[]>session.executeCommand(getErrRequest).response;
assert.equal(diags.length, 1);
host.reloadFS([file1, moduleFile]);
host.triggerDirectoryWatcherCallback(getDirectoryPath(file1.path), moduleFile.path);
host.runQueuedTimeoutCallbacks();
// Make a change to trigger the program rebuild
const changeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(
server.CommandNames.Change,
{ file: file1.path, line: 1, offset: 44, endLine: 1, endOffset: 44, insertString: "\n" }
);
session.executeCommand(changeRequest);
// Recheck
diags = <server.protocol.Diagnostic[]>session.executeCommand(getErrRequest).response;
assert.equal(diags.length, 0);
});
});
describe("Configure file diagnostics events", () => {
it("are generated when the config file has errors", () => {
const serverEventManager = new TestServerEventManager();
const file = {
path: "/a/b/app.ts",
content: "let x = 10"
};
const configFile = {
path: "/a/b/tsconfig.json",
content: `{
"compilerOptions": {
"foo": "bar",
"allowJS": true
}
}`
};
const host = createServerHost([file, configFile]);
const session = createSession(host, /*typingsInstaller*/ undefined, serverEventManager.handler);
openFilesForSession([file], session);
serverEventManager.checkEventCountOfType("configFileDiag", 1);
for (const event of serverEventManager.events) {
if (event.eventName === "configFileDiag") {
assert.equal(event.data.configFileName, configFile.path);
assert.equal(event.data.triggerFile, file.path);
return;
}
}
});
it("are generated when the config file doesn't have errors", () => {
const serverEventManager = new TestServerEventManager();
const file = {
path: "/a/b/app.ts",
content: "let x = 10"
};
const configFile = {
path: "/a/b/tsconfig.json",
content: `{
"compilerOptions": {}
}`
};
const host = createServerHost([file, configFile]);
const session = createSession(host, /*typingsInstaller*/ undefined, serverEventManager.handler);
openFilesForSession([file], session);
serverEventManager.checkEventCountOfType("configFileDiag", 1);
});
});
describe("skipLibCheck", () => {
it("should be turned on for js-only inferred projects", () => {
const file1 = {
path: "/a/b/file1.js",
content: `
/// <reference path="file2.d.ts" />
var x = 1;`
};
const file2 = {
path: "/a/b/file2.d.ts",
content: `
interface T {
name: string;
};
interface T {
name: number;
};`
};
const host = createServerHost([file1, file2]);
const session = createSession(host);
openFilesForSession([file1, file2], session);
const file2GetErrRequest = makeSessionRequest<protocol.SemanticDiagnosticsSyncRequestArgs>(
CommandNames.SemanticDiagnosticsSync,
{ file: file2.path }
);
let errorResult = <protocol.Diagnostic[]>session.executeCommand(file2GetErrRequest).response;
assert.isTrue(errorResult.length === 0);
const closeFileRequest = makeSessionRequest<protocol.FileRequestArgs>(CommandNames.Close, { file: file1.path });
session.executeCommand(closeFileRequest);
errorResult = <protocol.Diagnostic[]>session.executeCommand(file2GetErrRequest).response;
assert.isTrue(errorResult.length !== 0);
openFilesForSession([file1], session);
errorResult = <protocol.Diagnostic[]>session.executeCommand(file2GetErrRequest).response;
assert.isTrue(errorResult.length === 0);
});
it("should be turned on for js-only external projects", () => {
const jsFile = {
path: "/a/b/file1.js",
content: "let x =1;"
};
const dTsFile = {
path: "/a/b/file2.d.ts",
content: `
interface T {
name: string;
};
interface T {
name: number;
};`
};
const host = createServerHost([jsFile, dTsFile]);
const session = createSession(host);
const openExternalProjectRequest = makeSessionRequest<protocol.OpenExternalProjectArgs>(
CommandNames.OpenExternalProject,
{
projectFileName: "project1",
rootFiles: toExternalFiles([jsFile.path, dTsFile.path]),
options: {}
}
);
session.executeCommand(openExternalProjectRequest);
const dTsFileGetErrRequest = makeSessionRequest<protocol.SemanticDiagnosticsSyncRequestArgs>(
CommandNames.SemanticDiagnosticsSync,
{ file: dTsFile.path }
);
const errorResult = <protocol.Diagnostic[]>session.executeCommand(dTsFileGetErrRequest).response;
assert.isTrue(errorResult.length === 0);
});
});
describe("non-existing directories listed in config file input array", () => {
it("should be tolerated without crashing the server", () => {
const configFile = {
path: "/a/b/tsconfig.json",
content: `{
"compilerOptions": {},
"include": ["app/*", "test/**/*", "something"]
}`
};
const file1 = {
path: "/a/b/file1.ts",
content: "let t = 10;"
};
const host = createServerHost([file1, configFile]);
const projectService = createProjectService(host);
projectService.openClientFile(file1.path);
host.runQueuedTimeoutCallbacks();
checkNumberOfConfiguredProjects(projectService, 1);
checkNumberOfInferredProjects(projectService, 1);
const configuredProject = projectService.configuredProjects[0];
assert.isTrue(configuredProject.getFileNames().length == 0);
const inferredProject = projectService.inferredProjects[0];
assert.isTrue(inferredProject.containsFile(<server.NormalizedPath>file1.path));
});
});
}
+14 -14
View File
@@ -31,11 +31,11 @@ namespace ts.projectSystem {
function executeCommand(self: Installer, host: TestServerHost, installedTypings: string[], typingFiles: FileOrFolder[], requestKind: TI.RequestKind, cb: TI.RequestCompletedAction): void {
switch (requestKind) {
case TI.NpmInstallRequest:
self.addPostExecAction(requestKind, installedTypings, (err, stdout, stderr) => {
self.addPostExecAction(requestKind, installedTypings, success => {
for (const file of typingFiles) {
host.createFileOrFolder(file, /*createParentDirectory*/ true);
}
cb(err, stdout, stderr);
cb(success);
});
break;
case TI.NpmViewRequest:
@@ -81,7 +81,7 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jquery];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -125,7 +125,7 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jquery];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -221,7 +221,7 @@ namespace ts.projectSystem {
enqueueIsCalled = true;
super.enqueueInstallTypingsRequest(project, typingOptions);
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/jquery"];
const typingFiles = [jquery];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -275,7 +275,7 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/lodash", "@types/react"];
const typingFiles = [lodash, react];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -323,7 +323,7 @@ namespace ts.projectSystem {
enqueueIsCalled = true;
super.enqueueInstallTypingsRequest(project, typingOptions);
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings: string[] = [];
const typingFiles: FileOrFolder[] = [];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -398,7 +398,7 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/commander", "@types/express", "@types/jquery", "@types/moment"];
const typingFiles = [commander, express, jquery, moment];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -477,7 +477,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { throttleLimit: 3 });
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/commander", "@types/express", "@types/jquery", "@types/moment", "@types/lodash"];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
}
@@ -567,10 +567,10 @@ namespace ts.projectSystem {
constructor() {
super(host, { throttleLimit: 3 });
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
if (requestKind === TI.NpmInstallRequest) {
let typingFiles: (FileOrFolder & { typings: string}) [] = [];
if (command.indexOf("commander") >= 0) {
if (args.indexOf("@types/commander") >= 0) {
typingFiles = [commander, jquery, lodash, cordova];
}
else {
@@ -655,7 +655,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" });
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jqueryDTS];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -701,7 +701,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" });
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jqueryDTS];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -766,7 +766,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" }, { isEnabled: () => true, writeLine: msg => messages.push(msg) });
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
assert(false, "runCommand should not be invoked");
}
})();
+1 -1
View File
@@ -201,7 +201,7 @@ interface NumberConstructor {
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
+3
View File
@@ -244,6 +244,9 @@ interface Function {
*/
bind(this: Function, thisArg: any, ...argArray: any[]): any;
/** Returns a string representation of a function. */
toString(): string;
prototype: any;
readonly length: number;
-1
View File
@@ -1,6 +1,5 @@
/// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="protocol.d.ts" />
/// <reference path="session.ts" />
/// <reference types="node" />
+96 -13
View File
@@ -1,7 +1,6 @@
/// <reference path="session.ts" />
namespace ts.server {
export interface SessionClientHost extends LanguageServiceHost {
writeMessage(message: string): void;
}
@@ -214,6 +213,7 @@ namespace ts.server {
const response = this.processResponse<protocol.CompletionsResponse>(request);
return {
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: false,
entries: response.body.map(entry => {
@@ -424,11 +424,35 @@ namespace ts.server {
}
getSyntacticDiagnostics(fileName: string): Diagnostic[] {
throw new Error("Not Implemented Yet.");
const args: protocol.SyntacticDiagnosticsSyncRequestArgs = { file: fileName };
const request = this.processRequest<protocol.SyntacticDiagnosticsSyncRequest>(CommandNames.SyntacticDiagnosticsSync, args);
const response = this.processResponse<protocol.SyntacticDiagnosticsSyncResponse>(request);
return (<protocol.Diagnostic[]>response.body).map(entry => this.convertDiagnostic(entry, fileName));
}
getSemanticDiagnostics(fileName: string): Diagnostic[] {
throw new Error("Not Implemented Yet.");
const args: protocol.SemanticDiagnosticsSyncRequestArgs = { file: fileName };
const request = this.processRequest<protocol.SemanticDiagnosticsSyncRequest>(CommandNames.SemanticDiagnosticsSync, args);
const response = this.processResponse<protocol.SemanticDiagnosticsSyncResponse>(request);
return (<protocol.Diagnostic[]>response.body).map(entry => this.convertDiagnostic(entry, fileName));
}
convertDiagnostic(entry: protocol.Diagnostic, fileName: string): Diagnostic {
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
file: undefined,
start: start,
length: end - start,
messageText: entry.text,
category: undefined,
code: entry.code
};
}
getCompilerOptionsDiagnostics(): Diagnostic[] {
@@ -487,7 +511,7 @@ namespace ts.server {
return this.lastRenameEntry.locations;
}
decodeNavigationBarItems(items: protocol.NavigationBarItem[], fileName: string, lineMap: number[]): NavigationBarItem[] {
private decodeNavigationBarItems(items: protocol.NavigationBarItem[], fileName: string, lineMap: number[]): NavigationBarItem[] {
if (!items) {
return [];
}
@@ -496,10 +520,7 @@ namespace ts.server {
text: item.text,
kind: item.kind,
kindModifiers: item.kindModifiers || "",
spans: item.spans.map(span =>
createTextSpanFromBounds(
this.lineOffsetToPosition(fileName, span.start, lineMap),
this.lineOffsetToPosition(fileName, span.end, lineMap))),
spans: item.spans.map(span => this.decodeSpan(span, fileName, lineMap)),
childItems: this.decodeNavigationBarItems(item.childItems, fileName, lineMap),
indent: item.indent,
bolded: false,
@@ -508,17 +529,37 @@ namespace ts.server {
}
getNavigationBarItems(fileName: string): NavigationBarItem[] {
const args: protocol.FileRequestArgs = {
file: fileName
};
const request = this.processRequest<protocol.NavBarRequest>(CommandNames.NavBar, args);
const request = this.processRequest<protocol.NavBarRequest>(CommandNames.NavBar, { file: fileName });
const response = this.processResponse<protocol.NavBarResponse>(request);
const lineMap = this.getLineMap(fileName);
return this.decodeNavigationBarItems(response.body, fileName, lineMap);
}
private decodeNavigationTree(tree: protocol.NavigationTree, fileName: string, lineMap: number[]): NavigationTree {
return {
text: tree.text,
kind: tree.kind,
kindModifiers: tree.kindModifiers,
spans: tree.spans.map(span => this.decodeSpan(span, fileName, lineMap)),
childItems: map(tree.childItems, item => this.decodeNavigationTree(item, fileName, lineMap))
};
}
getNavigationTree(fileName: string): NavigationTree {
const request = this.processRequest<protocol.NavTreeRequest>(CommandNames.NavTree, { file: fileName });
const response = this.processResponse<protocol.NavTreeResponse>(request);
const lineMap = this.getLineMap(fileName);
return this.decodeNavigationTree(response.body, fileName, lineMap);
}
private decodeSpan(span: protocol.TextSpan, fileName: string, lineMap: number[]) {
return createTextSpanFromBounds(
this.lineOffsetToPosition(fileName, span.start, lineMap),
this.lineOffsetToPosition(fileName, span.end, lineMap));
}
getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan {
throw new Error("Not Implemented Yet.");
}
@@ -629,6 +670,48 @@ namespace ts.server {
throw new Error("Not Implemented Yet.");
}
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[] {
const startLineOffset = this.positionToOneBasedLineOffset(fileName, start);
const endLineOffset = this.positionToOneBasedLineOffset(fileName, end);
const args: protocol.CodeFixRequestArgs = {
file: fileName,
startLine: startLineOffset.line,
startOffset: startLineOffset.offset,
endLine: endLineOffset.line,
endOffset: endLineOffset.offset,
errorCodes: errorCodes,
};
const request = this.processRequest<protocol.CodeFixRequest>(CommandNames.GetCodeFixes, args);
const response = this.processResponse<protocol.CodeFixResponse>(request);
return response.body.map(entry => this.convertCodeActions(entry, fileName));
}
convertCodeActions(entry: protocol.CodeAction, fileName: string): CodeAction {
return {
description: entry.description,
changes: entry.changes.map(change => ({
fileName: change.fileName,
textChanges: change.textChanges.map(textChange => this.convertTextChangeToCodeEdit(textChange, fileName))
}))
};
}
convertTextChangeToCodeEdit(change: protocol.CodeEdit, fileName: string): ts.TextChange {
const start = this.lineOffsetToPosition(fileName, change.start);
const end = this.lineOffsetToPosition(fileName, change.end);
return {
span: {
start: start,
length: end - start
},
newText: change.newText ? change.newText : ""
};
}
getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[] {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
+19 -14
View File
@@ -1,6 +1,5 @@
/// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="protocol.d.ts" />
/// <reference path="utilities.ts" />
/// <reference path="session.ts" />
/// <reference path="scriptVersionCache.ts"/>
@@ -12,7 +11,7 @@ namespace ts.server {
export const maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
export type ProjectServiceEvent =
{ eventName: "context", data: { project: Project, fileName: NormalizedPath } } | { eventName: "configFileDiag", data: { triggerFile?: string, configFileName: string, diagnostics: Diagnostic[] } }
{ eventName: "context", data: { project: Project, fileName: NormalizedPath } } | { eventName: "configFileDiag", data: { triggerFile: string, configFileName: string, diagnostics: Diagnostic[] } };
export interface ProjectServiceEventHandler {
(event: ProjectServiceEvent): void;
@@ -180,6 +179,8 @@ namespace ts.server {
private toCanonicalFileName: (f: string) => string;
public lastDeletedFile: ScriptInfo;
constructor(public readonly host: ServerHost,
public readonly logger: Logger,
public readonly cancellationToken: HostCancellationToken,
@@ -272,7 +273,7 @@ namespace ts.server {
else {
projectsToUpdate = [];
for (const f of this.changedFiles) {
projectsToUpdate = projectsToUpdate.concat(f.containingProjects);
projectsToUpdate = projectsToUpdate.concat(f.containingProjects);
}
}
this.updateProjectGraphs(projectsToUpdate);
@@ -342,6 +343,7 @@ namespace ts.server {
if (!info.isOpen) {
this.filenameToScriptInfo.remove(info.path);
this.lastDeletedFile = info;
// capture list of projects since detachAllProjects will wipe out original list
const containingProjects = info.containingProjects.slice();
@@ -350,6 +352,7 @@ namespace ts.server {
// update projects to make sure that set of referenced files is correct
this.updateProjectGraphs(containingProjects);
this.lastDeletedFile = undefined;
if (!this.eventHandler) {
return;
@@ -389,12 +392,12 @@ namespace ts.server {
this.throttledOperations.schedule(
project.configFileName,
/*delay*/250,
() => this.handleChangeInSourceFileForConfiguredProject(project));
() => this.handleChangeInSourceFileForConfiguredProject(project, fileName));
}
private handleChangeInSourceFileForConfiguredProject(project: ConfiguredProject) {
private handleChangeInSourceFileForConfiguredProject(project: ConfiguredProject, triggerFile: string) {
const { projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.configFileName);
this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors);
this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors, triggerFile);
const newRootFiles = projectOptions.files.map((f => this.getCanonicalFileName(f)));
const currentRootFiles = project.getRootFiles().map((f => this.getCanonicalFileName(f)));
@@ -431,7 +434,7 @@ namespace ts.server {
}
const { configFileErrors } = this.convertConfigFileContentToProjectOptions(fileName);
this.reportConfigFileDiagnostics(fileName, configFileErrors);
this.reportConfigFileDiagnostics(fileName, configFileErrors, fileName);
this.logger.info(`Detected newly added tsconfig file: ${fileName}`);
this.reloadProjects();
@@ -707,7 +710,7 @@ namespace ts.server {
Debug.assert(!!parsedCommandLine.fileNames);
if (parsedCommandLine.fileNames.length === 0) {
errors.push(createCompilerDiagnostic(Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename));
(errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename));
return { success: false, configFileErrors: errors };
}
@@ -754,13 +757,15 @@ namespace ts.server {
return project;
}
private reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile?: string) {
if (diagnostics && diagnostics.length > 0) {
this.eventHandler({
eventName: "configFileDiag",
data: { configFileName, diagnostics, triggerFile }
});
private reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile: string) {
if (!this.eventHandler) {
return;
}
this.eventHandler({
eventName: "configFileDiag",
data: { configFileName, diagnostics: diagnostics || [], triggerFile }
});
}
private createAndAddConfiguredProject(configFileName: NormalizedPath, projectOptions: ProjectOptions, configFileErrors: Diagnostic[], clientFileName?: string) {
+13 -5
View File
@@ -52,7 +52,7 @@ namespace ts.server {
};
}
private resolveNamesWithLocalCache<T extends { failedLookupLocations: string[] }, R>(
private resolveNamesWithLocalCache<T extends { failedLookupLocations: string[] }, R extends { resolvedFileName?: string }>(
names: string[],
containingFile: string,
cache: ts.FileMap<Map<T>>,
@@ -65,6 +65,7 @@ namespace ts.server {
const newResolutions: Map<T> = createMap<T>();
const resolvedModules: R[] = [];
const compilerOptions = this.getCompilationSettings();
const lastDeletedFileName = this.project.projectService.lastDeletedFile && this.project.projectService.lastDeletedFile.fileName;
for (const name of names) {
// check if this is a duplicate entry in the list
@@ -94,8 +95,11 @@ namespace ts.server {
return false;
}
if (getResult(resolution)) {
// TODO: consider checking failedLookupLocations
const result = getResult(resolution);
if (result) {
if (result.resolvedFileName && result.resolvedFileName === lastDeletedFileName) {
return false;
}
return true;
}
@@ -171,12 +175,16 @@ namespace ts.server {
return this.host.fileExists(path);
}
readFile(fileName: string): string {
return this.host.readFile(fileName);
}
directoryExists(path: string): boolean {
return this.host.directoryExists(path);
}
readFile(fileName: string): string {
return this.host.readFile(fileName);
readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[] {
return this.host.readDirectory(path, extensions, exclude, include);
}
getDirectories(path: string): string[] {
+36 -5
View File
@@ -20,16 +20,42 @@ namespace ts.server {
}
}
function isJsOrDtsFile(info: ScriptInfo) {
return info.scriptKind === ScriptKind.JS || info.scriptKind == ScriptKind.JSX || fileExtensionIs(info.fileName, ".d.ts");
function countEachFileTypes(infos: ScriptInfo[]): { js: number, jsx: number, ts: number, tsx: number, dts: number } {
const result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 };
for (const info of infos) {
switch (info.scriptKind) {
case ScriptKind.JS:
result.js += 1;
break;
case ScriptKind.JSX:
result.jsx += 1;
break;
case ScriptKind.TS:
fileExtensionIs(info.fileName, ".d.ts")
? result.dts += 1
: result.ts += 1;
break;
case ScriptKind.TSX:
result.tsx += 1;
break;
}
}
return result;
}
function hasOneOrMoreJsAndNoTsFiles(project: Project) {
const counts = countEachFileTypes(project.getScriptInfos());
return counts.js > 0 && counts.ts === 0 && counts.tsx === 0;
}
export function allRootFilesAreJsOrDts(project: Project): boolean {
return project.getRootScriptInfos().every(isJsOrDtsFile);
const counts = countEachFileTypes(project.getRootScriptInfos());
return counts.ts === 0 && counts.tsx === 0;
}
export function allFilesAreJsOrDts(project: Project): boolean {
return project.getScriptInfos().every(isJsOrDtsFile);
const counts = countEachFileTypes(project.getScriptInfos());
return counts.ts === 0 && counts.tsx === 0;
}
export interface ProjectFilesWithTSDiagnostics extends protocol.ProjectFiles {
@@ -71,11 +97,16 @@ namespace ts.server {
public typesVersion = 0;
public isJsOnlyProject() {
public isNonTsProject() {
this.updateGraph();
return allFilesAreJsOrDts(this);
}
public isJsOnlyProject() {
this.updateGraph();
return hasOneOrMoreJsAndNoTsFiles(this);
}
constructor(
readonly projectKind: ProjectKind,
readonly projectService: ProjectService,
File diff suppressed because it is too large Load Diff
+2 -3
View File
@@ -4,7 +4,7 @@ namespace ts.server {
export class ScriptInfo {
/**
* All projects that include this file
* All projects that include this file
*/
readonly containingProjects: Project[] = [];
private formatCodeSettings: ts.FormatCodeSettings;
@@ -87,11 +87,10 @@ namespace ts.server {
if (this.containingProjects.length === 0) {
return Errors.ThrowNoProject();
}
Debug.assert(this.containingProjects.length !== 0);
return this.containingProjects[0];
}
setFormatOptions(formatSettings: protocol.FormatOptions): void {
setFormatOptions(formatSettings: FormatCodeSettings): void {
if (formatSettings) {
if (!this.formatCodeSettings) {
this.formatCodeSettings = getDefaultFormatCodeSettings(this.host);
-1
View File
@@ -1,6 +1,5 @@
/// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="protocol.d.ts" />
/// <reference path="session.ts" />
namespace ts.server {
+8 -1
View File
@@ -265,13 +265,16 @@ namespace ts.server {
installerEventPort: number,
canUseEvents: boolean,
useSingleInferredProject: boolean,
disableAutomaticTypingAcquisition: boolean,
globalTypingsCacheLocation: string,
logger: server.Logger) {
super(
host,
cancellationToken,
useSingleInferredProject,
new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine),
disableAutomaticTypingAcquisition
? nullTypingsInstaller
: new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine),
Buffer.byteLength,
process.hrtime,
logger,
@@ -512,17 +515,21 @@ namespace ts.server {
}
const useSingleInferredProject = sys.args.indexOf("--useSingleInferredProject") >= 0;
const disableAutomaticTypingAcquisition = sys.args.indexOf("--disableAutomaticTypingAcquisition") >= 0;
const ioSession = new IOSession(
sys,
cancellationToken,
eventPort,
/*canUseEvents*/ eventPort === undefined,
useSingleInferredProject,
disableAutomaticTypingAcquisition,
getGlobalTypingsCacheLocation(),
logger);
process.on("uncaughtException", function (err: Error) {
ioSession.logError(err, "unknown");
});
// See https://github.com/Microsoft/TypeScript/issues/11348
(process as any).noAsar = true;
// Start listening
ioSession.listen();
}
+225 -138
View File
@@ -1,6 +1,6 @@
/// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="protocol.d.ts" />
/// <reference path="protocol.ts" />
/// <reference path="editorServices.ts" />
namespace ts.server {
@@ -14,6 +14,17 @@ namespace ts.server {
return ((1e9 * seconds) + nanoseconds) / 1000000.0;
}
function shouldSkipSematicCheck(project: Project) {
if (project.getCompilerOptions().skipLibCheck !== undefined) {
return false;
}
if ((project.projectKind === ProjectKind.Inferred || project.projectKind === ProjectKind.External) && project.isJsOnlyProject()) {
return true;
}
return false;
}
interface FileStart {
file: string;
start: ILineInfo;
@@ -44,7 +55,8 @@ namespace ts.server {
return {
start: scriptInfo.positionToLineOffset(diag.start),
end: scriptInfo.positionToLineOffset(diag.start + diag.length),
text: ts.flattenDiagnosticMessageText(diag.messageText, "\n")
text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"),
code: diag.code
};
}
@@ -71,69 +83,74 @@ namespace ts.server {
}
export namespace CommandNames {
export const Brace = "brace";
export const BraceFull = "brace-full";
export const BraceCompletion = "braceCompletion";
export const Change = "change";
export const Close = "close";
export const Completions = "completions";
export const CompletionsFull = "completions-full";
export const CompletionDetails = "completionEntryDetails";
export const CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList";
export const CompileOnSaveEmitFile = "compileOnSaveEmitFile";
export const Configure = "configure";
export const Definition = "definition";
export const DefinitionFull = "definition-full";
export const Exit = "exit";
export const Format = "format";
export const Formatonkey = "formatonkey";
export const FormatFull = "format-full";
export const FormatonkeyFull = "formatonkey-full";
export const FormatRangeFull = "formatRange-full";
export const Geterr = "geterr";
export const GeterrForProject = "geterrForProject";
export const Implementation = "implementation";
export const ImplementationFull = "implementation-full";
export const SemanticDiagnosticsSync = "semanticDiagnosticsSync";
export const SyntacticDiagnosticsSync = "syntacticDiagnosticsSync";
export const NavBar = "navbar";
export const NavBarFull = "navbar-full";
export const Navto = "navto";
export const NavtoFull = "navto-full";
export const Occurrences = "occurrences";
export const DocumentHighlights = "documentHighlights";
export const DocumentHighlightsFull = "documentHighlights-full";
export const Open = "open";
export const Quickinfo = "quickinfo";
export const QuickinfoFull = "quickinfo-full";
export const References = "references";
export const ReferencesFull = "references-full";
export const Reload = "reload";
export const Rename = "rename";
export const RenameInfoFull = "rename-full";
export const RenameLocationsFull = "renameLocations-full";
export const Saveto = "saveto";
export const SignatureHelp = "signatureHelp";
export const SignatureHelpFull = "signatureHelp-full";
export const TypeDefinition = "typeDefinition";
export const ProjectInfo = "projectInfo";
export const ReloadProjects = "reloadProjects";
export const Unknown = "unknown";
export const OpenExternalProject = "openExternalProject";
export const OpenExternalProjects = "openExternalProjects";
export const CloseExternalProject = "closeExternalProject";
export const SynchronizeProjectList = "synchronizeProjectList";
export const ApplyChangedToOpenFiles = "applyChangedToOpenFiles";
export const EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full";
export const Cleanup = "cleanup";
export const OutliningSpans = "outliningSpans";
export const TodoComments = "todoComments";
export const Indentation = "indentation";
export const DocCommentTemplate = "docCommentTemplate";
export const CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full";
export const NameOrDottedNameSpan = "nameOrDottedNameSpan";
export const BreakpointStatement = "breakpointStatement";
export const CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects";
export const Brace: protocol.CommandTypes.Brace = "brace";
export const BraceFull: protocol.CommandTypes.BraceFull = "brace-full";
export const BraceCompletion: protocol.CommandTypes.BraceCompletion = "braceCompletion";
export const Change: protocol.CommandTypes.Change = "change";
export const Close: protocol.CommandTypes.Close = "close";
export const Completions: protocol.CommandTypes.Completions = "completions";
export const CompletionsFull: protocol.CommandTypes.CompletionsFull = "completions-full";
export const CompletionDetails: protocol.CommandTypes.CompletionDetails = "completionEntryDetails";
export const CompileOnSaveAffectedFileList: protocol.CommandTypes.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList";
export const CompileOnSaveEmitFile: protocol.CommandTypes.CompileOnSaveEmitFile = "compileOnSaveEmitFile";
export const Configure: protocol.CommandTypes.Configure = "configure";
export const Definition: protocol.CommandTypes.Definition = "definition";
export const DefinitionFull: protocol.CommandTypes.DefinitionFull = "definition-full";
export const Exit: protocol.CommandTypes.Exit = "exit";
export const Format: protocol.CommandTypes.Format = "format";
export const Formatonkey: protocol.CommandTypes.Formatonkey = "formatonkey";
export const FormatFull: protocol.CommandTypes.FormatFull = "format-full";
export const FormatonkeyFull: protocol.CommandTypes.FormatonkeyFull = "formatonkey-full";
export const FormatRangeFull: protocol.CommandTypes.FormatRangeFull = "formatRange-full";
export const Geterr: protocol.CommandTypes.Geterr = "geterr";
export const GeterrForProject: protocol.CommandTypes.GeterrForProject = "geterrForProject";
export const Implementation: protocol.CommandTypes.Implementation = "implementation";
export const ImplementationFull: protocol.CommandTypes.ImplementationFull = "implementation-full";
export const SemanticDiagnosticsSync: protocol.CommandTypes.SemanticDiagnosticsSync = "semanticDiagnosticsSync";
export const SyntacticDiagnosticsSync: protocol.CommandTypes.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync";
export const NavBar: protocol.CommandTypes.NavBar = "navbar";
export const NavBarFull: protocol.CommandTypes.NavBarFull = "navbar-full";
export const NavTree: protocol.CommandTypes.NavTree = "navtree";
export const NavTreeFull: protocol.CommandTypes.NavTreeFull = "navtree-full";
export const Navto: protocol.CommandTypes.Navto = "navto";
export const NavtoFull: protocol.CommandTypes.NavtoFull = "navto-full";
export const Occurrences: protocol.CommandTypes.Occurrences = "occurrences";
export const DocumentHighlights: protocol.CommandTypes.DocumentHighlights = "documentHighlights";
export const DocumentHighlightsFull: protocol.CommandTypes.DocumentHighlightsFull = "documentHighlights-full";
export const Open: protocol.CommandTypes.Open = "open";
export const Quickinfo: protocol.CommandTypes.Quickinfo = "quickinfo";
export const QuickinfoFull: protocol.CommandTypes.QuickinfoFull = "quickinfo-full";
export const References: protocol.CommandTypes.References = "references";
export const ReferencesFull: protocol.CommandTypes.ReferencesFull = "references-full";
export const Reload: protocol.CommandTypes.Reload = "reload";
export const Rename: protocol.CommandTypes.Rename = "rename";
export const RenameInfoFull: protocol.CommandTypes.RenameInfoFull = "rename-full";
export const RenameLocationsFull: protocol.CommandTypes.RenameLocationsFull = "renameLocations-full";
export const Saveto: protocol.CommandTypes.Saveto = "saveto";
export const SignatureHelp: protocol.CommandTypes.SignatureHelp = "signatureHelp";
export const SignatureHelpFull: protocol.CommandTypes.SignatureHelpFull = "signatureHelp-full";
export const TypeDefinition: protocol.CommandTypes.TypeDefinition = "typeDefinition";
export const ProjectInfo: protocol.CommandTypes.ProjectInfo = "projectInfo";
export const ReloadProjects: protocol.CommandTypes.ReloadProjects = "reloadProjects";
export const Unknown: protocol.CommandTypes.Unknown = "unknown";
export const OpenExternalProject: protocol.CommandTypes.OpenExternalProject = "openExternalProject";
export const OpenExternalProjects: protocol.CommandTypes.OpenExternalProjects = "openExternalProjects";
export const CloseExternalProject: protocol.CommandTypes.CloseExternalProject = "closeExternalProject";
export const SynchronizeProjectList: protocol.CommandTypes.SynchronizeProjectList = "synchronizeProjectList";
export const ApplyChangedToOpenFiles: protocol.CommandTypes.ApplyChangedToOpenFiles = "applyChangedToOpenFiles";
export const EncodedSemanticClassificationsFull: protocol.CommandTypes.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full";
export const Cleanup: protocol.CommandTypes.Cleanup = "cleanup";
export const OutliningSpans: protocol.CommandTypes.OutliningSpans = "outliningSpans";
export const TodoComments: protocol.CommandTypes.TodoComments = "todoComments";
export const Indentation: protocol.CommandTypes.Indentation = "indentation";
export const DocCommentTemplate: protocol.CommandTypes.DocCommentTemplate = "docCommentTemplate";
export const CompilerOptionsDiagnosticsFull: protocol.CommandTypes.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full";
export const NameOrDottedNameSpan: protocol.CommandTypes.NameOrDottedNameSpan = "nameOrDottedNameSpan";
export const BreakpointStatement: protocol.CommandTypes.BreakpointStatement = "breakpointStatement";
export const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects";
export const GetCodeFixes: protocol.CommandTypes.GetCodeFixes = "getCodeFixes";
export const GetCodeFixesFull: protocol.CommandTypes.GetCodeFixesFull = "getCodeFixes-full";
export const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes = "getSupportedCodeFixes";
}
export function formatMessage<T extends protocol.Message>(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string {
@@ -155,6 +172,8 @@ namespace ts.server {
private immediateId: any;
private changeSeq = 0;
private eventHander: ProjectServiceEventHandler;
constructor(
private host: ServerHost,
cancellationToken: HostCancellationToken,
@@ -163,17 +182,18 @@ namespace ts.server {
private byteLength: (buf: string, encoding?: string) => number,
private hrtime: (start?: number[]) => number[],
protected logger: Logger,
protected readonly canUseEvents: boolean) {
protected readonly canUseEvents: boolean,
eventHandler?: ProjectServiceEventHandler) {
const eventHandler: ProjectServiceEventHandler = canUseEvents
? event => this.handleEvent(event)
this.eventHander = canUseEvents
? eventHandler || (event => this.defaultEventHandler(event))
: undefined;
this.projectService = new ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler);
this.projectService = new ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, this.eventHander);
this.gcTimer = new GcTimer(host, /*delay*/ 7000, logger);
}
private handleEvent(event: ProjectServiceEvent) {
private defaultEventHandler(event: ProjectServiceEvent) {
switch (event.eventName) {
case "context":
const { project, fileName } = event.data;
@@ -252,12 +272,13 @@ namespace ts.server {
private semanticCheck(file: NormalizedPath, project: Project) {
try {
const diags = project.getLanguageService().getSemanticDiagnostics(file);
if (diags) {
const bakedDiags = diags.map((diag) => formatDiag(file, project, diag));
this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag");
let diags: Diagnostic[] = [];
if (!shouldSkipSematicCheck(project)) {
diags = project.getLanguageService().getSemanticDiagnostics(file);
}
const bakedDiags = diags.map((diag) => formatDiag(file, project, diag));
this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag");
}
catch (err) {
this.logError(err, "semantic check");
@@ -342,7 +363,7 @@ namespace ts.server {
}
}
private getEncodedSemanticClassifications(args: protocol.FileSpanRequestArgs) {
private getEncodedSemanticClassifications(args: protocol.EncodedSemanticClassificationsRequestArgs) {
const { file, project } = this.getFileAndProject(args);
return project.getLanguageService().getEncodedSemanticClassifications(file, args);
}
@@ -351,7 +372,7 @@ namespace ts.server {
return projectFileName && this.projectService.findProject(projectFileName);
}
private getCompilerOptionsDiagnostics(args: protocol.ProjectRequestArgs) {
private getCompilerOptionsDiagnostics(args: protocol.CompilerOptionsDiagnosticsRequestArgs) {
const project = this.getProject(args.projectFileName);
return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), /*scriptInfo*/ undefined);
}
@@ -370,6 +391,9 @@ namespace ts.server {
private getDiagnosticsWorker(args: protocol.FileRequestArgs, selector: (project: Project, file: string) => Diagnostic[], includeLinePosition: boolean) {
const { project, file } = this.getFileAndProject(args);
if (shouldSkipSematicCheck(project)) {
return [];
}
const scriptInfo = project.getScriptInfoForNormalizedPath(file);
const diagnostics = selector(project, file);
return includeLinePosition
@@ -547,7 +571,7 @@ namespace ts.server {
const scriptInfo = this.projectService.getScriptInfo(args.file);
projects = scriptInfo.containingProjects;
}
// ts.filter handles case when 'projects' is undefined
// ts.filter handles case when 'projects' is undefined
projects = filter(projects, p => p.languageServiceEnabled);
if (!projects || !projects.length) {
return Errors.ThrowNoProject();
@@ -734,8 +758,11 @@ namespace ts.server {
*/
private openClientFile(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind) {
const { configFileName, configFileErrors } = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind);
if (configFileErrors) {
this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors);
if (this.eventHander) {
this.eventHander({
eventName: "configFileDiag",
data: { triggerFile: fileName, configFileName, diagnostics: configFileErrors || [] }
});
}
}
@@ -751,7 +778,7 @@ namespace ts.server {
return this.getFileAndProjectWorker(args.file, args.projectFileName, /*refreshInferredProjects*/ false, errorOnMissingProject);
}
private getFileAndProjectWorker(uncheckedFileName: string, projectFileName: string, refreshInferredProjects: boolean, errorOnMissingProject: boolean) {
private getFileAndProjectWorker(uncheckedFileName: string, projectFileName: string, refreshInferredProjects: boolean, errorOnMissingProject: boolean) {
const file = toNormalizedPath(uncheckedFileName);
const project: Project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects);
if (!project && errorOnMissingProject) {
@@ -842,13 +869,7 @@ namespace ts.server {
return undefined;
}
return edits.map((edit) => {
return {
start: scriptInfo.positionToLineOffset(edit.span.start),
end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)),
newText: edit.newText ? edit.newText : ""
};
});
return edits.map(edit => this.convertTextChangeToCodeEdit(edit, scriptInfo));
}
private getFormattingEditsForRangeFull(args: protocol.FormatRequestArgs) {
@@ -941,19 +962,12 @@ namespace ts.server {
return completions.entries.reduce((result: protocol.CompletionEntry[], entry: ts.CompletionEntry) => {
if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) {
const { name, kind, kindModifiers, sortText, replacementSpan } = entry;
let convertedSpan: protocol.TextSpan = undefined;
if (replacementSpan) {
convertedSpan = {
start: scriptInfo.positionToLineOffset(replacementSpan.start),
end: scriptInfo.positionToLineOffset(replacementSpan.start + replacementSpan.length)
};
}
const convertedSpan: protocol.TextSpan =
replacementSpan ? this.decorateSpan(replacementSpan, scriptInfo) : undefined;
result.push({ name, kind, kindModifiers, sortText, replacementSpan: convertedSpan });
}
return result;
}, []).sort((a, b) => a.name.localeCompare(b.name));
}, []).sort((a, b) => ts.compareStrings(a.name, b.name));
}
else {
return completions;
@@ -1087,38 +1101,54 @@ namespace ts.server {
this.projectService.closeClientFile(file);
}
private decorateNavigationBarItem(project: Project, fileName: NormalizedPath, items: ts.NavigationBarItem[]): protocol.NavigationBarItem[] {
if (!items) {
return undefined;
}
const scriptInfo = project.getScriptInfoForNormalizedPath(fileName);
return items.map(item => ({
private decorateNavigationBarItems(items: ts.NavigationBarItem[], scriptInfo: ScriptInfo): protocol.NavigationBarItem[] {
return map(items, item => ({
text: item.text,
kind: item.kind,
kindModifiers: item.kindModifiers,
spans: item.spans.map(span => ({
start: scriptInfo.positionToLineOffset(span.start),
end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span))
})),
childItems: this.decorateNavigationBarItem(project, fileName, item.childItems),
spans: item.spans.map(span => this.decorateSpan(span, scriptInfo)),
childItems: this.decorateNavigationBarItems(item.childItems, scriptInfo),
indent: item.indent
}));
}
private getNavigationBarItems(args: protocol.FileRequestArgs, simplifiedResult: boolean): protocol.NavigationBarItem[] | NavigationBarItem[] {
const { file, project } = this.getFileAndProject(args);
const items = project.getLanguageService().getNavigationBarItems(file);
if (!items) {
return undefined;
}
return simplifiedResult
? this.decorateNavigationBarItem(project, file, items)
const items = project.getLanguageService(/*ensureSynchronized*/ false).getNavigationBarItems(file);
return !items
? undefined
: simplifiedResult
? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file))
: items;
}
private decorateNavigationTree(tree: ts.NavigationTree, scriptInfo: ScriptInfo): protocol.NavigationTree {
return {
text: tree.text,
kind: tree.kind,
kindModifiers: tree.kindModifiers,
spans: tree.spans.map(span => this.decorateSpan(span, scriptInfo)),
childItems: map(tree.childItems, item => this.decorateNavigationTree(item, scriptInfo))
};
}
private decorateSpan(span: TextSpan, scriptInfo: ScriptInfo): protocol.TextSpan {
return {
start: scriptInfo.positionToLineOffset(span.start),
end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span))
};
}
private getNavigationTree(args: protocol.FileRequestArgs, simplifiedResult: boolean): protocol.NavigationTree | NavigationTree {
const { file, project } = this.getFileAndProject(args);
const tree = project.getLanguageService(/*ensureSynchronized*/ false).getNavigationTree(file);
return !tree
? undefined
: simplifiedResult
? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file))
: tree;
}
private getNavigateToItems(args: protocol.NavtoRequestArgs, simplifiedResult: boolean): protocol.NavtoItem[] | NavigateToItem[] {
const projects = this.getProjects(args);
@@ -1127,7 +1157,7 @@ namespace ts.server {
return combineProjectOutput(
projects,
project => {
const navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, /*excludeDts*/ project.isJsOnlyProject());
const navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, /*excludeDts*/ project.isNonTsProject());
if (!navItems) {
return [];
}
@@ -1165,7 +1195,7 @@ namespace ts.server {
else {
return combineProjectOutput(
projects,
project => project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, /*excludeDts*/ project.isJsOnlyProject()),
project => project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, /*excludeDts*/ project.isNonTsProject()),
/*comparer*/ undefined,
navigateToItemIsEqualTo);
}
@@ -1199,6 +1229,55 @@ namespace ts.server {
}
}
private getSupportedCodeFixes(): string[] {
return ts.getSupportedCodeFixes();
}
private getCodeFixes(args: protocol.CodeFixRequestArgs, simplifiedResult: boolean): protocol.CodeAction[] | CodeAction[] {
const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args);
const scriptInfo = project.getScriptInfoForNormalizedPath(file);
const startPosition = getStartPosition();
const endPosition = getEndPosition();
const codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes);
if (!codeActions) {
return undefined;
}
if (simplifiedResult) {
return codeActions.map(codeAction => this.mapCodeAction(codeAction, scriptInfo));
}
else {
return codeActions;
}
function getStartPosition() {
return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset);
}
function getEndPosition() {
return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
}
}
private mapCodeAction(codeAction: CodeAction, scriptInfo: ScriptInfo): protocol.CodeAction {
return {
description: codeAction.description,
changes: codeAction.changes.map(change => ({
fileName: change.fileName,
textChanges: change.textChanges.map(textChange => this.convertTextChangeToCodeEdit(textChange, scriptInfo))
}))
};
}
private convertTextChangeToCodeEdit(change: ts.TextChange, scriptInfo: ScriptInfo): protocol.CodeEdit {
return {
start: scriptInfo.positionToLineOffset(change.span.start),
end: scriptInfo.positionToLineOffset(change.span.start + change.span.length),
newText: change.newText ? change.newText : ""
};
}
private getBraceMatching(args: protocol.FileLocationRequestArgs, simplifiedResult: boolean): protocol.TextSpan[] | TextSpan[] {
const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args);
@@ -1206,19 +1285,11 @@ namespace ts.server {
const position = this.getPosition(args, scriptInfo);
const spans = project.getLanguageService(/*ensureSynchronized*/ false).getBraceMatchingAtPosition(file, position);
if (!spans) {
return undefined;
}
if (simplifiedResult) {
return spans.map(span => ({
start: scriptInfo.positionToLineOffset(span.start),
end: scriptInfo.positionToLineOffset(span.start + span.length)
}));
}
else {
return spans;
}
return !spans
? undefined
: simplifiedResult
? spans.map(span => this.decorateSpan(span, scriptInfo))
: spans;
}
getDiagnosticsForProject(delay: number, fileName: string) {
@@ -1399,7 +1470,7 @@ namespace ts.server {
[CommandNames.BraceCompletion]: (request: protocol.BraceCompletionRequest) => {
return this.requiredResponse(this.isValidBraceCompletion(request.arguments));
},
[CommandNames.DocCommentTemplate]: (request: protocol.FileLocationRequest) => {
[CommandNames.DocCommentTemplate]: (request: protocol.DocCommentTemplateRequest) => {
return this.requiredResponse(this.getDocCommentTemplate(request.arguments));
},
[CommandNames.Format]: (request: protocol.FormatRequest) => {
@@ -1438,10 +1509,10 @@ namespace ts.server {
[CommandNames.SignatureHelpFull]: (request: protocol.SignatureHelpRequest) => {
return this.requiredResponse(this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ false));
},
[CommandNames.CompilerOptionsDiagnosticsFull]: (request: protocol.ProjectRequest) => {
[CommandNames.CompilerOptionsDiagnosticsFull]: (request: protocol.CompilerOptionsDiagnosticsRequest) => {
return this.requiredResponse(this.getCompilerOptionsDiagnostics(request.arguments));
},
[CommandNames.EncodedSemanticClassificationsFull]: (request: protocol.FileSpanRequest) => {
[CommandNames.EncodedSemanticClassificationsFull]: (request: protocol.EncodedSemanticClassificationsRequest) => {
return this.requiredResponse(this.getEncodedSemanticClassifications(request.arguments));
},
[CommandNames.Cleanup]: (request: protocol.Request) => {
@@ -1503,6 +1574,12 @@ namespace ts.server {
[CommandNames.NavBarFull]: (request: protocol.FileRequest) => {
return this.requiredResponse(this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ false));
},
[CommandNames.NavTree]: (request: protocol.FileRequest) => {
return this.requiredResponse(this.getNavigationTree(request.arguments, /*simplifiedResult*/ true));
},
[CommandNames.NavTreeFull]: (request: protocol.FileRequest) => {
return this.requiredResponse(this.getNavigationTree(request.arguments, /*simplifiedResult*/ false));
},
[CommandNames.Occurrences]: (request: protocol.FileLocationRequest) => {
return this.requiredResponse(this.getOccurrences(request.arguments));
},
@@ -1513,7 +1590,8 @@ namespace ts.server {
return this.requiredResponse(this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ false));
},
[CommandNames.CompilerOptionsForInferredProjects]: (request: protocol.SetCompilerOptionsForInferredProjectsRequest) => {
return this.requiredResponse(this.setCompilerOptionsForInferredProjects(request.arguments));
this.setCompilerOptionsForInferredProjects(request.arguments);
return this.requiredResponse(true);
},
[CommandNames.ProjectInfo]: (request: protocol.ProjectInfoRequest) => {
return this.requiredResponse(this.getProjectInfo(request.arguments));
@@ -1521,6 +1599,15 @@ namespace ts.server {
[CommandNames.ReloadProjects]: (request: protocol.ReloadProjectsRequest) => {
this.projectService.reloadProjects();
return this.notRequired();
},
[CommandNames.GetCodeFixes]: (request: protocol.CodeFixRequest) => {
return this.requiredResponse(this.getCodeFixes(request.arguments, /*simplifiedResult*/ true));
},
[CommandNames.GetCodeFixesFull]: (request: protocol.CodeFixRequest) => {
return this.requiredResponse(this.getCodeFixes(request.arguments, /*simplifiedResult*/ false));
},
[CommandNames.GetSupportedCodeFixes]: (request: protocol.Request) => {
return this.requiredResponse(this.getSupportedCodeFixes());
}
});
+1 -1
View File
@@ -22,7 +22,7 @@
"typingsCache.ts",
"project.ts",
"editorServices.ts",
"protocol.d.ts",
"protocol.ts",
"session.ts",
"server.ts"
]
@@ -33,23 +33,38 @@ namespace ts.server.typingsInstaller {
}
}
export class NodeTypingsInstaller extends TypingsInstaller {
private readonly exec: { (command: string, options: { cwd: string }, callback?: (error: Error, stdout: string, stderr: string) => void): any };
type HttpGet = {
(url: string, callback: (response: HttpResponse) => void): NodeJS.EventEmitter;
};
interface HttpResponse extends NodeJS.ReadableStream {
statusCode: number;
statusMessage: string;
destroy(): void;
}
type Exec = {
(command: string, options: { cwd: string }, callback?: (error: Error, stdout: string, stderr: string) => void): any
};
export class NodeTypingsInstaller extends TypingsInstaller {
private readonly exec: Exec;
private readonly httpGet: HttpGet;
private readonly npmPath: string;
readonly installTypingHost: InstallTypingHost = sys;
constructor(globalTypingsCacheLocation: string, throttleLimit: number, log: Log) {
super(
globalTypingsCacheLocation,
/*npmPath*/ getNPMLocation(process.argv[0]),
toPath("typingSafeList.json", __dirname, createGetCanonicalFileName(sys.useCaseSensitiveFileNames)),
throttleLimit,
log);
if (this.log.isEnabled()) {
this.log.writeLine(`Process id: ${process.pid}`);
}
const { exec } = require("child_process");
this.exec = exec;
this.npmPath = getNPMLocation(process.argv[0]);
this.exec = require("child_process").exec;
this.httpGet = require("http").get;
}
init() {
@@ -75,17 +90,54 @@ namespace ts.server.typingsInstaller {
}
}
protected runCommand(requestKind: RequestKind, requestId: number, command: string, cwd: string, onRequestCompleted: RequestCompletedAction): void {
protected executeRequest(requestKind: RequestKind, requestId: number, args: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void {
if (this.log.isEnabled()) {
this.log.writeLine(`#${requestId} running command '${command}'.`);
this.log.writeLine(`#${requestId} executing ${requestKind}, arguments'${JSON.stringify(args)}'.`);
}
switch (requestKind) {
case NpmViewRequest: {
// const command = `${self.npmPath} view @types/${typing} --silent name`;
// use http request to global npm registry instead of running npm view
Debug.assert(args.length === 1);
const url = `http://registry.npmjs.org/@types%2f${args[0]}`;
const start = Date.now();
this.httpGet(url, response => {
let ok = false;
if (this.log.isEnabled()) {
this.log.writeLine(`${requestKind} #${requestId} request to ${url}:: status code ${response.statusCode}, status message '${response.statusMessage}', took ${Date.now() - start} ms`);
}
switch (response.statusCode) {
case 200: // OK
case 301: // redirect - Moved - treat package as present
case 302: // redirect - Found - treat package as present
ok = true;
break;
}
response.destroy();
onRequestCompleted(ok);
}).on("error", (err: Error) => {
if (this.log.isEnabled()) {
this.log.writeLine(`${requestKind} #${requestId} query to npm registry failed with error ${err.message}, stack ${err.stack}`);
}
onRequestCompleted(/*success*/ false);
});
}
break;
case NpmInstallRequest: {
const command = `${this.npmPath} install ${args.join(" ")} --save-dev`;
const start = Date.now();
this.exec(command, { cwd }, (err, stdout, stderr) => {
if (this.log.isEnabled()) {
this.log.writeLine(`${requestKind} #${requestId} took: ${Date.now() - start} ms${sys.newLine}stdout: ${stdout}${sys.newLine}stderr: ${stderr}`);
}
// treat any output on stdout as success
onRequestCompleted(!!stdout);
});
}
break;
default:
Debug.assert(false, `Unknown request kind ${requestKind}`);
}
this.exec(command, { cwd }, (err, stdout, stderr) => {
if (this.log.isEnabled()) {
this.log.writeLine(`${requestKind} #${requestId} stdout: ${stdout}`);
this.log.writeLine(`${requestKind} #${requestId} stderr: ${stderr}`);
}
onRequestCompleted(err, stdout, stderr);
});
}
}
+13 -16
View File
@@ -65,11 +65,11 @@ namespace ts.server.typingsInstaller {
export type RequestKind = typeof NpmViewRequest | typeof NpmInstallRequest;
export type RequestCompletedAction = (err: Error, stdout: string, stderr: string) => void;
export type RequestCompletedAction = (success: boolean) => void;
type PendingRequest = {
requestKind: RequestKind;
requestId: number;
command: string;
args: string[];
cwd: string;
onRequestCompleted: RequestCompletedAction
};
@@ -88,7 +88,6 @@ namespace ts.server.typingsInstaller {
constructor(
readonly globalCachePath: string,
readonly npmPath: string,
readonly safeListPath: Path,
readonly throttleLimit: number,
protected readonly log = nullLog) {
@@ -331,13 +330,12 @@ namespace ts.server.typingsInstaller {
let execInstallCmdCount = 0;
const filteredTypings: string[] = [];
for (const typing of typingsToInstall) {
execNpmViewTyping(this, typing);
filterExistingTypings(this, typing);
}
function execNpmViewTyping(self: TypingsInstaller, typing: string) {
const command = `${self.npmPath} view @types/${typing} --silent name`;
self.execAsync(NpmViewRequest, requestId, command, cachePath, (err, stdout, stderr) => {
if (stdout) {
function filterExistingTypings(self: TypingsInstaller, typing: string) {
self.execAsync(NpmViewRequest, requestId, [typing], cachePath, ok => {
if (ok) {
filteredTypings.push(typing);
}
execInstallCmdCount++;
@@ -353,9 +351,8 @@ namespace ts.server.typingsInstaller {
return;
}
const scopedTypings = filteredTypings.map(t => "@types/" + t);
const command = `${self.npmPath} install ${scopedTypings.join(" ")} --save-dev`;
self.execAsync(NpmInstallRequest, requestId, command, cachePath, (err, stdout, stderr) => {
postInstallAction(stdout ? scopedTypings : []);
self.execAsync(NpmInstallRequest, requestId, scopedTypings, cachePath, ok => {
postInstallAction(ok ? scopedTypings : []);
});
}
}
@@ -403,8 +400,8 @@ namespace ts.server.typingsInstaller {
};
}
private execAsync(requestKind: RequestKind, requestId: number, command: string, cwd: string, onRequestCompleted: RequestCompletedAction): void {
this.pendingRunRequests.unshift({ requestKind, requestId, command, cwd, onRequestCompleted });
private execAsync(requestKind: RequestKind, requestId: number, args: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void {
this.pendingRunRequests.unshift({ requestKind, requestId, args, cwd, onRequestCompleted });
this.executeWithThrottling();
}
@@ -412,15 +409,15 @@ namespace ts.server.typingsInstaller {
while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
this.inFlightRequestCount++;
const request = this.pendingRunRequests.pop();
this.runCommand(request.requestKind, request.requestId, request.command, request.cwd, (err, stdout, stderr) => {
this.executeRequest(request.requestKind, request.requestId, request.args, request.cwd, ok => {
this.inFlightRequestCount--;
request.onRequestCompleted(err, stdout, stderr);
request.onRequestCompleted(ok);
this.executeWithThrottling();
});
}
}
protected abstract runCommand(requestKind: RequestKind, requestId: number, command: string, cwd: string, onRequestCompleted: RequestCompletedAction): void;
protected abstract executeRequest(requestKind: RequestKind, requestId: number, args: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void;
protected abstract sendResponse(response: SetTypings | InvalidateCachedTypings): void;
}
}
+44 -42
View File
@@ -157,51 +157,53 @@ namespace ts.server {
}
};
}
function throwLanguageServiceIsDisabledError() {
function throwLanguageServiceIsDisabledError(): never {
throw new Error("LanguageService is disabled");
}
export const nullLanguageService: LanguageService = {
cleanupSemanticCache: (): any => throwLanguageServiceIsDisabledError(),
getSyntacticDiagnostics: (): any => throwLanguageServiceIsDisabledError(),
getSemanticDiagnostics: (): any => throwLanguageServiceIsDisabledError(),
getCompilerOptionsDiagnostics: (): any => throwLanguageServiceIsDisabledError(),
getSyntacticClassifications: (): any => throwLanguageServiceIsDisabledError(),
getEncodedSyntacticClassifications: (): any => throwLanguageServiceIsDisabledError(),
getSemanticClassifications: (): any => throwLanguageServiceIsDisabledError(),
getEncodedSemanticClassifications: (): any => throwLanguageServiceIsDisabledError(),
getCompletionsAtPosition: (): any => throwLanguageServiceIsDisabledError(),
findReferences: (): any => throwLanguageServiceIsDisabledError(),
getCompletionEntryDetails: (): any => throwLanguageServiceIsDisabledError(),
getQuickInfoAtPosition: (): any => throwLanguageServiceIsDisabledError(),
findRenameLocations: (): any => throwLanguageServiceIsDisabledError(),
getNameOrDottedNameSpan: (): any => throwLanguageServiceIsDisabledError(),
getBreakpointStatementAtPosition: (): any => throwLanguageServiceIsDisabledError(),
getBraceMatchingAtPosition: (): any => throwLanguageServiceIsDisabledError(),
getSignatureHelpItems: (): any => throwLanguageServiceIsDisabledError(),
getDefinitionAtPosition: (): any => throwLanguageServiceIsDisabledError(),
getRenameInfo: (): any => throwLanguageServiceIsDisabledError(),
getTypeDefinitionAtPosition: (): any => throwLanguageServiceIsDisabledError(),
getReferencesAtPosition: (): any => throwLanguageServiceIsDisabledError(),
getDocumentHighlights: (): any => throwLanguageServiceIsDisabledError(),
getOccurrencesAtPosition: (): any => throwLanguageServiceIsDisabledError(),
getNavigateToItems: (): any => throwLanguageServiceIsDisabledError(),
getNavigationBarItems: (): any => throwLanguageServiceIsDisabledError(),
getOutliningSpans: (): any => throwLanguageServiceIsDisabledError(),
getTodoComments: (): any => throwLanguageServiceIsDisabledError(),
getIndentationAtPosition: (): any => throwLanguageServiceIsDisabledError(),
getFormattingEditsForRange: (): any => throwLanguageServiceIsDisabledError(),
getFormattingEditsForDocument: (): any => throwLanguageServiceIsDisabledError(),
getFormattingEditsAfterKeystroke: (): any => throwLanguageServiceIsDisabledError(),
getDocCommentTemplateAtPosition: (): any => throwLanguageServiceIsDisabledError(),
isValidBraceCompletionAtPosition: (): any => throwLanguageServiceIsDisabledError(),
getEmitOutput: (): any => throwLanguageServiceIsDisabledError(),
getProgram: (): any => throwLanguageServiceIsDisabledError(),
getNonBoundSourceFile: (): any => throwLanguageServiceIsDisabledError(),
dispose: (): any => throwLanguageServiceIsDisabledError(),
getCompletionEntrySymbol: (): any => throwLanguageServiceIsDisabledError(),
getImplementationAtPosition: (): any => throwLanguageServiceIsDisabledError(),
getSourceFile: (): any => throwLanguageServiceIsDisabledError()
cleanupSemanticCache: throwLanguageServiceIsDisabledError,
getSyntacticDiagnostics: throwLanguageServiceIsDisabledError,
getSemanticDiagnostics: throwLanguageServiceIsDisabledError,
getCompilerOptionsDiagnostics: throwLanguageServiceIsDisabledError,
getSyntacticClassifications: throwLanguageServiceIsDisabledError,
getEncodedSyntacticClassifications: throwLanguageServiceIsDisabledError,
getSemanticClassifications: throwLanguageServiceIsDisabledError,
getEncodedSemanticClassifications: throwLanguageServiceIsDisabledError,
getCompletionsAtPosition: throwLanguageServiceIsDisabledError,
findReferences: throwLanguageServiceIsDisabledError,
getCompletionEntryDetails: throwLanguageServiceIsDisabledError,
getQuickInfoAtPosition: throwLanguageServiceIsDisabledError,
findRenameLocations: throwLanguageServiceIsDisabledError,
getNameOrDottedNameSpan: throwLanguageServiceIsDisabledError,
getBreakpointStatementAtPosition: throwLanguageServiceIsDisabledError,
getBraceMatchingAtPosition: throwLanguageServiceIsDisabledError,
getSignatureHelpItems: throwLanguageServiceIsDisabledError,
getDefinitionAtPosition: throwLanguageServiceIsDisabledError,
getRenameInfo: throwLanguageServiceIsDisabledError,
getTypeDefinitionAtPosition: throwLanguageServiceIsDisabledError,
getReferencesAtPosition: throwLanguageServiceIsDisabledError,
getDocumentHighlights: throwLanguageServiceIsDisabledError,
getOccurrencesAtPosition: throwLanguageServiceIsDisabledError,
getNavigateToItems: throwLanguageServiceIsDisabledError,
getNavigationBarItems: throwLanguageServiceIsDisabledError,
getNavigationTree: throwLanguageServiceIsDisabledError,
getOutliningSpans: throwLanguageServiceIsDisabledError,
getTodoComments: throwLanguageServiceIsDisabledError,
getIndentationAtPosition: throwLanguageServiceIsDisabledError,
getFormattingEditsForRange: throwLanguageServiceIsDisabledError,
getFormattingEditsForDocument: throwLanguageServiceIsDisabledError,
getFormattingEditsAfterKeystroke: throwLanguageServiceIsDisabledError,
getDocCommentTemplateAtPosition: throwLanguageServiceIsDisabledError,
isValidBraceCompletionAtPosition: throwLanguageServiceIsDisabledError,
getEmitOutput: throwLanguageServiceIsDisabledError,
getProgram: throwLanguageServiceIsDisabledError,
getNonBoundSourceFile: throwLanguageServiceIsDisabledError,
dispose: throwLanguageServiceIsDisabledError,
getCompletionEntrySymbol: throwLanguageServiceIsDisabledError,
getImplementationAtPosition: throwLanguageServiceIsDisabledError,
getSourceFile: throwLanguageServiceIsDisabledError,
getCodeFixesAtPosition: throwLanguageServiceIsDisabledError
};
export interface ServerLanguageServiceHost {
@@ -248,7 +250,7 @@ namespace ts.server {
// another operation was already scheduled for this id - cancel it
this.host.clearTimeout(this.pendingTimeouts[operationId]);
}
// schedule new operation, pass arguments
// schedule new operation, pass arguments
this.pendingTimeouts[operationId] = this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb);
}
+1 -2
View File
@@ -954,8 +954,7 @@ namespace ts {
return;
case SyntaxKind.Parameter:
if ((<ParameterDeclaration>token.parent).name === token) {
const isThis = token.kind === SyntaxKind.Identifier && (<Identifier>token).originalKeywordKind === SyntaxKind.ThisKeyword;
return isThis ? ClassificationType.keyword : ClassificationType.parameterName;
return isThisIdentifier(token) ? ClassificationType.keyword : ClassificationType.parameterName;
}
return;
}
+48
View File
@@ -0,0 +1,48 @@
/* @internal */
namespace ts {
export interface CodeFix {
errorCodes: number[];
getCodeActions(context: CodeFixContext): CodeAction[] | undefined;
}
export interface CodeFixContext {
errorCode: number;
sourceFile: SourceFile;
span: TextSpan;
program: Program;
newLineCharacter: string;
}
export namespace codefix {
const codeFixes = createMap<CodeFix[]>();
export function registerCodeFix(action: CodeFix) {
forEach(action.errorCodes, error => {
let fixes = codeFixes[error];
if (!fixes) {
fixes = [];
codeFixes[error] = fixes;
}
fixes.push(action);
});
}
export function getSupportedErrorCodes() {
return Object.keys(codeFixes);
}
export function getFixes(context: CodeFixContext): CodeAction[] {
const fixes = codeFixes[context.errorCode];
let allActions: CodeAction[] = [];
forEach(fixes, f => {
const actions = f.getCodeActions(context);
if (actions && actions.length > 0) {
allActions = allActions.concat(actions);
}
});
return allActions;
}
}
}
+1
View File
@@ -0,0 +1 @@
///<reference path='superFixes.ts' />
+81
View File
@@ -0,0 +1,81 @@
/* @internal */
namespace ts.codefix {
function getOpenBraceEnd(constructor: ConstructorDeclaration, sourceFile: SourceFile) {
// First token is the open curly, this is where we want to put the 'super' call.
return constructor.body.getFirstToken(sourceFile).getEnd();
}
registerCodeFix({
errorCodes: [Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code],
getCodeActions: (context: CodeFixContext) => {
const sourceFile = context.sourceFile;
const token = getTokenAtPosition(sourceFile, context.span.start);
if (token.kind !== SyntaxKind.ConstructorKeyword) {
return undefined;
}
const newPosition = getOpenBraceEnd(<ConstructorDeclaration>token.parent, sourceFile);
return [{
description: getLocaleSpecificMessage(Diagnostics.Add_missing_super_call),
changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }]
}];
}
});
registerCodeFix({
errorCodes: [Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code],
getCodeActions: (context: CodeFixContext) => {
const sourceFile = context.sourceFile;
const token = getTokenAtPosition(sourceFile, context.span.start);
if (token.kind !== SyntaxKind.ThisKeyword) {
return undefined;
}
const constructor = getContainingFunction(token);
const superCall = findSuperCall((<ConstructorDeclaration>constructor).body);
if (!superCall) {
return undefined;
}
// figure out if the this access is actuall inside the supercall
// i.e. super(this.a), since in that case we won't suggest a fix
if (superCall.expression && superCall.expression.kind == SyntaxKind.CallExpression) {
const arguments = (<CallExpression>superCall.expression).arguments;
for (let i = 0; i < arguments.length; i++) {
if ((<PropertyAccessExpression>arguments[i]).expression === token) {
return undefined;
}
}
}
const newPosition = getOpenBraceEnd(<ConstructorDeclaration>constructor, sourceFile);
const changes = [{
fileName: sourceFile.fileName, textChanges: [{
newText: superCall.getText(sourceFile),
span: { start: newPosition, length: 0 }
},
{
newText: "",
span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) }
}]
}];
return [{
description: getLocaleSpecificMessage(Diagnostics.Make_super_call_the_first_statement_in_the_constructor),
changes
}];
function findSuperCall(n: Node): ExpressionStatement {
if (n.kind === SyntaxKind.ExpressionStatement && isSuperCall((<ExpressionStatement>n).expression)) {
return <ExpressionStatement>n;
}
if (isFunctionLike(n)) {
return undefined;
}
return forEachChild(n, findSuperCall);
}
}
});
}
+69 -28
View File
@@ -14,17 +14,17 @@ namespace ts.Completions {
return undefined;
}
const { symbols, isMemberCompletion, isNewIdentifierLocation, location, isJsDocTagName } = completionData;
const { symbols, isGlobalCompletion, isMemberCompletion, isNewIdentifierLocation, location, isJsDocTagName } = completionData;
if (isJsDocTagName) {
// If the current position is a jsDoc tag name, only tag names should be provided for completion
return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: JsDoc.getAllJsDocCompletionEntries() };
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: JsDoc.getAllJsDocCompletionEntries() };
}
const entries: CompletionEntry[] = [];
if (isSourceFileJavaScript(sourceFile)) {
const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ false);
const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true);
addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames));
}
else {
@@ -56,7 +56,7 @@ namespace ts.Completions {
addRange(entries, keywordCompletions);
}
return { isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries };
return { isGlobalCompletion, isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries };
function getJavaScriptCompletionEntries(sourceFile: SourceFile, position: number, uniqueNames: Map<string>): CompletionEntry[] {
const entries: CompletionEntry[] = [];
@@ -138,7 +138,9 @@ namespace ts.Completions {
return undefined;
}
if (node.parent.kind === SyntaxKind.PropertyAssignment && node.parent.parent.kind === SyntaxKind.ObjectLiteralExpression) {
if (node.parent.kind === SyntaxKind.PropertyAssignment &&
node.parent.parent.kind === SyntaxKind.ObjectLiteralExpression &&
(<PropertyAssignment>node.parent).name === node) {
// Get quoted name of properties of the object literal expression
// i.e. interface ConfigFiles {
// 'jspm:dev': string
@@ -190,7 +192,7 @@ namespace ts.Completions {
if (type) {
getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/false);
if (entries.length) {
return { isMemberCompletion: true, isNewIdentifierLocation: true, entries };
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries };
}
}
}
@@ -209,7 +211,7 @@ namespace ts.Completions {
}
if (entries.length) {
return { isMemberCompletion: false, isNewIdentifierLocation: true, entries };
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries };
}
return undefined;
@@ -221,7 +223,7 @@ namespace ts.Completions {
if (type) {
getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/false);
if (entries.length) {
return { isMemberCompletion: true, isNewIdentifierLocation: true, entries };
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries };
}
}
return undefined;
@@ -233,7 +235,7 @@ namespace ts.Completions {
const entries: CompletionEntry[] = [];
addStringLiteralCompletionsFromType(type, entries);
if (entries.length) {
return { isMemberCompletion: false, isNewIdentifierLocation: false, entries };
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries };
}
}
return undefined;
@@ -281,6 +283,7 @@ namespace ts.Completions {
entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span);
}
return {
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: true,
entries
@@ -322,15 +325,28 @@ namespace ts.Completions {
return result;
}
/**
* Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename.
*/
function getCompletionEntriesForDirectoryFragment(fragment: string, scriptPath: string, extensions: string[], includeExtensions: boolean, span: TextSpan, exclude?: string, result: CompletionEntry[] = []): CompletionEntry[] {
if (fragment === undefined) {
fragment = "";
}
fragment = normalizeSlashes(fragment);
/**
* Remove the basename from the path. Note that we don't use the basename to filter completions;
* the client is responsible for refining completions.
*/
fragment = getDirectoryPath(fragment);
if (!fragment) {
fragment = "./";
}
else {
fragment = ensureTrailingDirectorySeparator(fragment);
if (fragment === "") {
fragment = "." + directorySeparator;
}
fragment = ensureTrailingDirectorySeparator(fragment);
const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment));
const baseDirectory = getDirectoryPath(absolutePath);
const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
@@ -340,6 +356,12 @@ namespace ts.Completions {
const files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/undefined, /*include*/["./*"]);
if (files) {
/**
* Multiple file entries might map to the same truncated name once we remove extensions
* (happens iff includeExtensions === false)so we use a set-like data structure. Eg:
*
* both foo.ts and foo.tsx become foo
*/
const foundFiles = createMap<boolean>();
for (let filePath of files) {
filePath = normalizePath(filePath);
@@ -536,35 +558,44 @@ namespace ts.Completions {
return undefined;
}
const completionInfo: CompletionInfo = {
/**
* We don't want the editor to offer any other completions, such as snippets, inside a comment.
*/
isGlobalCompletion: false,
isMemberCompletion: false,
/**
* The user may type in a path that doesn't yet exist, creating a "new identifier"
* with respect to the collection of identifiers the server is aware of.
*/
isNewIdentifierLocation: true,
entries: []
};
const text = sourceFile.text.substr(range.pos, position - range.pos);
const match = tripleSlashDirectiveFragmentRegex.exec(text);
if (match) {
const prefix = match[1];
const kind = match[2];
const toComplete = match[3];
const scriptPath = getDirectoryPath(sourceFile.path);
let entries: CompletionEntry[];
if (kind === "path") {
// Give completions for a relative path
const span: TextSpan = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length);
entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getSupportedExtensions(compilerOptions), /*includeExtensions*/true, span, sourceFile.path);
completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getSupportedExtensions(compilerOptions), /*includeExtensions*/true, span, sourceFile.path);
}
else {
// Give completions based on the typings available
const span: TextSpan = { start: range.pos + prefix.length, length: match[0].length - prefix.length };
entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span);
completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span);
}
return {
isMemberCompletion: false,
isNewIdentifierLocation: true,
entries
};
}
return undefined;
return completionInfo;
}
function getCompletionEntriesFromTypings(host: LanguageServiceHost, options: CompilerOptions, scriptPath: string, span: TextSpan, result: CompletionEntry[] = []): CompletionEntry[] {
@@ -812,7 +843,7 @@ namespace ts.Completions {
}
if (isJsDocTagName) {
return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName };
return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName };
}
if (!insideJsDocTagExpression) {
@@ -884,6 +915,7 @@ namespace ts.Completions {
}
const semanticStart = timestamp();
let isGlobalCompletion = false;
let isMemberCompletion: boolean;
let isNewIdentifierLocation: boolean;
let symbols: Symbol[] = [];
@@ -919,14 +951,16 @@ namespace ts.Completions {
if (!tryGetGlobalSymbols()) {
return undefined;
}
isGlobalCompletion = true;
}
log("getCompletionData: Semantic work: " + (timestamp() - semanticStart));
return { symbols, isMemberCompletion, isNewIdentifierLocation, location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName };
return { symbols, isGlobalCompletion, isMemberCompletion, isNewIdentifierLocation, location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName };
function getTypeScriptMemberSymbols(): void {
// Right of dot member completion list
isGlobalCompletion = false;
isMemberCompletion = true;
isNewIdentifierLocation = false;
@@ -996,6 +1030,7 @@ namespace ts.Completions {
if ((jsxContainer.kind === SyntaxKind.JsxSelfClosingElement) || (jsxContainer.kind === SyntaxKind.JsxOpeningElement)) {
// Cursor is inside a JSX self-closing element or opening element
attrsType = typeChecker.getJsxElementAttributesType(<JsxOpeningLikeElement>jsxContainer);
isGlobalCompletion = false;
if (attrsType) {
symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), (<JsxOpeningLikeElement>jsxContainer).attributes);
@@ -1666,9 +1701,15 @@ namespace ts.Completions {
* Matches a triple slash reference directive with an incomplete string literal for its path. Used
* to determine if the caret is currently within the string literal and capture the literal fragment
* for completions.
* For example, this matches /// <reference path="fragment
* For example, this matches
*
* /// <reference path="fragment
*
* but not
*
* /// <reference path="fragment"
*/
const tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*<reference\s+(path|types)\s*=\s*(?:'|"))([^\3]*)$/;
const tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*<reference\s+(path|types)\s*=\s*(?:'|"))([^\3"]*)$/;
interface VisibleModuleInfo {
moduleName: string;
+4 -3
View File
@@ -175,7 +175,7 @@ namespace ts.formatting {
return rangeContainsRange((<InterfaceDeclaration>parent).members, node);
case SyntaxKind.ModuleDeclaration:
const body = (<ModuleDeclaration>parent).body;
return body && body.kind === SyntaxKind.Block && rangeContainsRange((<Block>body).statements, node);
return body && body.kind === SyntaxKind.ModuleBlock && rangeContainsRange((<ModuleBlock>body).statements, node);
case SyntaxKind.SourceFile:
case SyntaxKind.Block:
case SyntaxKind.ModuleBlock:
@@ -624,10 +624,11 @@ namespace ts.formatting {
return inheritedIndentation;
}
if (isToken(child)) {
// JSX text shouldn't affect indenting
if (isToken(child) && child.kind !== SyntaxKind.JsxText) {
// if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules
const tokenInfo = formattingScanner.readTokenInfo(child);
Debug.assert(tokenInfo.token.end === child.end);
Debug.assert(tokenInfo.token.end === child.end, "Token end is child end");
consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child);
return inheritedIndentation;
}
+2 -2
View File
@@ -31,7 +31,7 @@ namespace ts.formatting {
}
export function getFormattingScanner(sourceFile: SourceFile, startPos: number, endPos: number): FormattingScanner {
Debug.assert(scanner === undefined);
Debug.assert(scanner === undefined, "Scanner should be undefined");
scanner = sourceFile.languageVariant === LanguageVariant.JSX ? jsxScanner : standardScanner;
scanner.setText(sourceFile.text);
@@ -62,7 +62,7 @@ namespace ts.formatting {
};
function advance(): void {
Debug.assert(scanner !== undefined);
Debug.assert(scanner !== undefined, "Scanner should be present");
lastTokenInfo = undefined;
const isStarted = scanner.getStartPos() !== startPos;
+1 -1
View File
@@ -35,8 +35,8 @@ namespace ts.formatting {
}
private GetRuleBucketIndex(row: number, column: number): number {
Debug.assert(row <= SyntaxKind.LastKeyword && column <= SyntaxKind.LastKeyword, "Must compute formatting context from tokens");
const rulesBucketIndex = (row * this.mapRowLength) + column;
// Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array.");
return rulesBucketIndex;
}
+3 -4
View File
@@ -332,7 +332,7 @@ namespace ts.formatting {
(<CallExpression>node.parent).expression !== node) {
const fullCallOrNewExpression = (<CallExpression | NewExpression>node.parent).expression;
const startingExpression = getStartingExpression(<PropertyAccessExpression | CallExpression | ElementAccessExpression>fullCallOrNewExpression);
const startingExpression = getStartingExpression(fullCallOrNewExpression);
if (fullCallOrNewExpression === startingExpression) {
return Value.Unknown;
@@ -350,15 +350,14 @@ namespace ts.formatting {
return Value.Unknown;
function getStartingExpression(node: PropertyAccessExpression | CallExpression | ElementAccessExpression) {
function getStartingExpression(node: Expression) {
while (true) {
switch (node.kind) {
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.ElementAccessExpression:
node = <PropertyAccessExpression | CallExpression | ElementAccessExpression | PropertyAccessExpression>node.expression;
node = (<PropertyAccessExpression | CallExpression | NewExpression | ElementAccessExpression | PropertyAccessExpression>node).expression;
break;
default:
return node;
+2 -5
View File
@@ -6,9 +6,6 @@ namespace ts.NavigateTo {
const patternMatcher = createPatternMatcher(searchValue);
let rawItems: RawNavigateToItem[] = [];
// This means "compare in a case insensitive manner."
const baseSensitivity: Intl.CollatorOptions = { sensitivity: "base" };
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
forEach(sourceFiles, sourceFile => {
cancellationToken.throwIfCancellationRequested();
@@ -188,8 +185,8 @@ namespace ts.NavigateTo {
// We first sort case insensitively. So "Aaa" will come before "bar".
// Then we sort case sensitively, so "aaa" will come before "Aaa".
return i1.matchKind - i2.matchKind ||
i1.name.localeCompare(i2.name, undefined, baseSensitivity) ||
i1.name.localeCompare(i2.name);
ts.compareStringsCaseInsensitive(i1.name, i2.name) ||
ts.compareStrings(i1.name, i2.name);
}
function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem {
+26 -11
View File
@@ -21,6 +21,13 @@ namespace ts.NavigationBar {
return result;
}
export function getNavigationTree(sourceFile: SourceFile): NavigationTree {
curSourceFile = sourceFile;
const result = convertToTree(rootNavigationBarNode(sourceFile));
curSourceFile = undefined;
return result;
}
// Keep sourceFile handy so we don't have to search for it every time we need to call `getText`.
let curSourceFile: SourceFile;
function nodeText(node: Node): string {
@@ -323,10 +330,8 @@ namespace ts.NavigationBar {
}
}
// More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times.
const collator: { compare(a: string, b: string): number } = typeof Intl === "undefined" ? undefined : new Intl.Collator();
// Intl is missing in Safari, and node 0.10 treats "a" as greater than "B".
const localeCompareIsCorrect = collator && collator.compare("a", "B") < 0;
const localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0;
const localeCompareFix: (a: string, b: string) => number = localeCompareIsCorrect ? collator.compare : function(a, b) {
// This isn't perfect, but it passes all of our tests.
for (let i = 0; i < Math.min(a.length, b.length); i++) {
@@ -337,7 +342,7 @@ namespace ts.NavigationBar {
if (chA === "'" && chB === "\"") {
return -1;
}
const cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase());
const cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase());
if (cmp !== 0) {
return cmp;
}
@@ -502,6 +507,16 @@ namespace ts.NavigationBar {
// NavigationBarItem requires an array, but will not mutate it, so just give it this for performance.
const emptyChildItemArray: NavigationBarItem[] = [];
function convertToTree(n: NavigationBarNode): NavigationTree {
return {
text: getItemName(n.node),
kind: getNodeKind(n.node),
kindModifiers: getNodeModifiers(n.node),
spans: getSpans(n),
childItems: map(n.children, convertToTree)
};
}
function convertToTopLevelItem(n: NavigationBarNode): NavigationBarItem {
return {
text: getItemName(n.node),
@@ -526,16 +541,16 @@ namespace ts.NavigationBar {
grayed: false
};
}
}
function getSpans(n: NavigationBarNode): TextSpan[] {
const spans = [getNodeSpan(n.node)];
if (n.additionalNodes) {
for (const node of n.additionalNodes) {
spans.push(getNodeSpan(node));
}
function getSpans(n: NavigationBarNode): TextSpan[] {
const spans = [getNodeSpan(n.node)];
if (n.additionalNodes) {
for (const node of n.additionalNodes) {
spans.push(getNodeSpan(node));
}
return spans;
}
return spans;
}
function getModuleName(moduleDeclaration: ModuleDeclaration): string {
+75 -14
View File
@@ -24,14 +24,16 @@
/// <reference path='transpile.ts' />
/// <reference path='formatting\formatting.ts' />
/// <reference path='formatting\smartIndenter.ts' />
/// <reference path='codefixes\codeFixProvider.ts' />
/// <reference path='codefixes\fixes.ts' />
namespace ts {
/** The version of the language service API */
export const servicesVersion = "0.5";
function createNode(kind: SyntaxKind, pos: number, end: number, parent?: Node): NodeObject | TokenObject | IdentifierObject {
function createNode<TKind extends SyntaxKind>(kind: TKind, pos: number, end: number, parent?: Node): NodeObject | TokenObject<TKind> | IdentifierObject {
const node = kind >= SyntaxKind.FirstNode ? new NodeObject(kind, pos, end) :
kind === SyntaxKind.Identifier ? new IdentifierObject(kind, pos, end) :
kind === SyntaxKind.Identifier ? new IdentifierObject(SyntaxKind.Identifier, pos, end) :
new TokenObject(kind, pos, end);
node.parent = parent;
return node;
@@ -210,14 +212,13 @@ namespace ts {
}
}
class TokenOrIdentifierObject implements Token {
class TokenOrIdentifierObject implements Node {
public kind: SyntaxKind;
public pos: number;
public end: number;
public flags: NodeFlags;
public parent: Node;
public jsDocComments: JSDoc[];
public __tokenTag: any;
constructor(pos: number, end: number) {
// Set properties in same order as NodeObject
@@ -319,16 +320,25 @@ namespace ts {
}
}
class TokenObject extends TokenOrIdentifierObject {
public kind: SyntaxKind;
constructor(kind: SyntaxKind, pos: number, end: number) {
class TokenObject<TKind extends SyntaxKind> extends TokenOrIdentifierObject implements Token<TKind> {
public kind: TKind;
constructor(kind: TKind, pos: number, end: number) {
super(pos, end);
this.kind = kind;
}
}
class IdentifierObject extends TokenOrIdentifierObject {
constructor(kind: SyntaxKind, pos: number, end: number) {
class IdentifierObject extends TokenOrIdentifierObject implements Identifier {
public kind: SyntaxKind.Identifier;
public text: string;
_primaryExpressionBrand: any;
_memberExpressionBrand: any;
_leftHandSideExpressionBrand: any;
_incrementExpressionBrand: any;
_unaryExpressionBrand: any;
_expressionBrand: any;
constructor(kind: SyntaxKind.Identifier, pos: number, end: number) {
super(pos, end);
}
}
@@ -424,6 +434,7 @@ namespace ts {
}
class SourceFileObject extends NodeObject implements SourceFile {
public kind: SyntaxKind.SourceFile;
public _declarationBrand: any;
public fileName: string;
public path: Path;
@@ -432,7 +443,7 @@ namespace ts {
public lineMap: number[];
public statements: NodeArray<Statement>;
public endOfFileToken: Node;
public endOfFileToken: Token<SyntaxKind.EndOfFileToken>;
public amdDependencies: { name: string; path: string }[];
public moduleName: string;
@@ -655,6 +666,7 @@ namespace ts {
return {
getNodeConstructor: () => NodeObject,
getTokenConstructor: () => TokenObject,
getIdentifierConstructor: () => IdentifierObject,
getSourceFileConstructor: () => SourceFileObject,
getSymbolConstructor: () => SymbolObject,
@@ -721,9 +733,13 @@ namespace ts {
};
}
// Cache host information about script should be refreshed
export function getSupportedCodeFixes() {
return codefix.getSupportedErrorCodes();
}
// Cache host information about script Should be refreshed
// at each language service public entry point, since we don't know when
// set of scripts handled by the host changes.
// the set of scripts handled by the host changes.
class HostCache {
private fileNameToEntry: FileMap<HostFileInformation>;
private _compilationSettings: CompilerOptions;
@@ -1507,17 +1523,32 @@ namespace ts {
}
function getNavigationBarItems(fileName: string): NavigationBarItem[] {
const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
return NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName));
}
return NavigationBar.getNavigationBarItems(sourceFile);
function getNavigationTree(fileName: string): NavigationTree {
return NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName));
}
function isTsOrTsxFile(fileName: string): boolean {
const kind = getScriptKind(fileName, host);
return kind === ScriptKind.TS || kind === ScriptKind.TSX;
}
function getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[] {
if (!isTsOrTsxFile(fileName)) {
// do not run semantic classification on non-ts-or-tsx files
return [];
}
synchronizeHostData();
return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
}
function getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications {
if (!isTsOrTsxFile(fileName)) {
// do not run semantic classification on non-ts-or-tsx files
return { spans: [], endOfLineState: EndOfLineState.None };
}
synchronizeHostData();
return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
}
@@ -1632,6 +1663,34 @@ namespace ts {
return [];
}
function getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[] {
synchronizeHostData();
const sourceFile = getValidSourceFile(fileName);
const span = { start, length: end - start };
const newLineChar = getNewLineOrDefaultFromHost(host);
let allFixes: CodeAction[] = [];
forEach(errorCodes, error => {
cancellationToken.throwIfCancellationRequested();
const context = {
errorCode: error,
sourceFile: sourceFile,
span: span,
program: program,
newLineCharacter: newLineChar
};
const fixes = codefix.getFixes(context);
if (fixes) {
allFixes = allFixes.concat(fixes);
}
});
return allFixes;
}
function getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion {
return JsDoc.getDocCommentTemplateAtPosition(getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position);
}
@@ -1846,6 +1905,7 @@ namespace ts {
getRenameInfo,
findRenameLocations,
getNavigationBarItems,
getNavigationTree,
getOutliningSpans,
getTodoComments,
getBraceMatchingAtPosition,
@@ -1855,6 +1915,7 @@ namespace ts {
getFormattingEditsAfterKeystroke,
getDocCommentTemplateAtPosition,
isValidBraceCompletionAtPosition,
getCodeFixesAtPosition,
getEmitOutput,
getNonBoundSourceFile,
getSourceFile,
+10
View File
@@ -224,6 +224,9 @@ namespace ts {
*/
getNavigationBarItems(fileName: string): string;
/** Returns a JSON-encoded value of the type ts.NavigationTree. */
getNavigationTree(fileName: string): string;
/**
* Returns a JSON-encoded value of the type:
* { textSpan: { start: number, length: number }; hintSpan: { start: number, length: number }; bannerText: string; autoCollapse: boolean } [] = [];
@@ -971,6 +974,13 @@ namespace ts {
);
}
public getNavigationTree(fileName: string): string {
return this.forwardJSONCall(
`getNavigationTree('${fileName}')`,
() => this.languageService.getNavigationTree(fileName)
);
}
public getOutliningSpans(fileName: string): string {
return this.forwardJSONCall(
`getOutliningSpans('${fileName}')`,
+3 -3
View File
@@ -114,12 +114,12 @@ namespace ts.SymbolDisplay {
}
// try get the call/construct signature from the type if it matches
let callExpression: CallExpression;
let callExpression: CallExpression | NewExpression;
if (location.kind === SyntaxKind.CallExpression || location.kind === SyntaxKind.NewExpression) {
callExpression = <CallExpression>location;
callExpression = <CallExpression | NewExpression>location;
}
else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) {
callExpression = <CallExpression>location.parent;
callExpression = <CallExpression | NewExpression>location.parent;
}
if (callExpression) {
+7 -4
View File
@@ -25,13 +25,14 @@
"../compiler/visitor.ts",
"../compiler/transformers/ts.ts",
"../compiler/transformers/jsx.ts",
"../compiler/transformers/es7.ts",
"../compiler/transformers/es6.ts",
"../compiler/transformers/es2017.ts",
"../compiler/transformers/es2016.ts",
"../compiler/transformers/es2015.ts",
"../compiler/transformers/generators.ts",
"../compiler/transformers/destructuring.ts",
"../compiler/transformers/module/module.ts",
"../compiler/transformers/module/system.ts",
"../compiler/transformers/module/es6.ts",
"../compiler/transformers/module/es2015.ts",
"../compiler/transformer.ts",
"../compiler/comments.ts",
"../compiler/sourcemap.ts",
@@ -78,6 +79,8 @@
"formatting/rulesMap.ts",
"formatting/rulesProvider.ts",
"formatting/smartIndenter.ts",
"formatting/tokenRange.ts"
"formatting/tokenRange.ts",
"codeFixes/codeFixProvider.ts",
"codeFixes/fixes.ts"
]
}
+63 -17
View File
@@ -225,6 +225,7 @@ namespace ts {
getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[];
getNavigationBarItems(fileName: string): NavigationBarItem[];
getNavigationTree(fileName: string): NavigationTree;
getOutliningSpans(fileName: string): OutliningSpan[];
getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[];
@@ -239,6 +240,8 @@ namespace ts {
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[];
getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput;
getProgram(): Program;
@@ -264,6 +267,12 @@ namespace ts {
classificationType: string; // ClassificationTypeNames
}
/**
* Navigation bar interface designed for visual studio's dual-column layout.
* This does not form a proper tree.
* The navbar is returned as a list of top-level items, each of which has a list of child items.
* Child items always have an empty array for their `childItems`.
*/
export interface NavigationBarItem {
text: string;
kind: string;
@@ -275,6 +284,26 @@ namespace ts {
grayed: boolean;
}
/**
* Node in a tree of nested declarations in a file.
* The top node is always a script or module node.
*/
export interface NavigationTree {
/** Name of the declaration, or a short description, e.g. "<class>". */
text: string;
/** A ScriptElementKind */
kind: string;
/** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */
kindModifiers: string;
/**
* Spans of the nodes that generated this declaration.
* There will be more than one if this is the result of merging.
*/
spans: TextSpan[];
/** Present if non-empty */
childItems?: NavigationTree[];
}
export interface TodoCommentDescriptor {
text: string;
priority: number;
@@ -291,6 +320,18 @@ namespace ts {
newText: string;
}
export interface FileTextChanges {
fileName: string;
textChanges: TextChange[];
}
export interface CodeAction {
/** Description of the code action to display in the UI of the editor */
description: string;
/** Text changes to apply to each file as part of the code action */
changes: FileTextChanges[];
}
export interface TextInsertion {
newText: string;
/** The position in newText the caret should point to after the insertion. */
@@ -362,11 +403,11 @@ namespace ts {
export interface EditorSettings {
baseIndentSize?: number;
indentSize: number;
tabSize: number;
newLineCharacter: string;
convertTabsToSpaces: boolean;
indentStyle: IndentStyle;
indentSize?: number;
tabSize?: number;
newLineCharacter?: string;
convertTabsToSpaces?: boolean;
indentStyle?: IndentStyle;
}
/* @deprecated - consider using FormatCodeSettings instead */
@@ -387,19 +428,19 @@ namespace ts {
}
export interface FormatCodeSettings extends EditorSettings {
insertSpaceAfterCommaDelimiter: boolean;
insertSpaceAfterSemicolonInForStatements: boolean;
insertSpaceBeforeAndAfterBinaryOperators: boolean;
insertSpaceAfterKeywordsInControlFlowStatements: boolean;
insertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean;
insertSpaceAfterCommaDelimiter?: boolean;
insertSpaceAfterSemicolonInForStatements?: boolean;
insertSpaceBeforeAndAfterBinaryOperators?: boolean;
insertSpaceAfterKeywordsInControlFlowStatements?: boolean;
insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean;
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean;
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: boolean;
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean;
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean;
insertSpaceAfterTypeAssertion?: boolean;
placeOpenBraceOnNewLineForFunctions: boolean;
placeOpenBraceOnNewLineForControlBlocks: boolean;
placeOpenBraceOnNewLineForFunctions?: boolean;
placeOpenBraceOnNewLineForControlBlocks?: boolean;
}
export interface DefinitionInfo {
@@ -503,8 +544,13 @@ namespace ts {
}
export interface CompletionInfo {
isGlobalCompletion: boolean;
isMemberCompletion: boolean;
isNewIdentifierLocation: boolean; // true when the current location also allows for a new identifier
/**
* true when the current location also allows for a new identifier
*/
isNewIdentifierLocation: boolean;
entries: CompletionEntry[];
}
+4 -4
View File
@@ -376,7 +376,7 @@ namespace ts {
return true;
case SyntaxKind.Identifier:
// 'this' as a parameter
return (node as Identifier).originalKeywordKind === SyntaxKind.ThisKeyword && node.parent.kind === SyntaxKind.Parameter;
return identifierIsThisKeyword(node as Identifier) && node.parent.kind === SyntaxKind.Parameter;
default:
return false;
}
@@ -750,7 +750,7 @@ namespace ts {
return find(startNode || sourceFile);
function findRightmostToken(n: Node): Node {
if (isToken(n) || n.kind === SyntaxKind.JsxText) {
if (isToken(n)) {
return n;
}
@@ -761,7 +761,7 @@ namespace ts {
}
function find(n: Node): Node {
if (isToken(n) || n.kind === SyntaxKind.JsxText) {
if (isToken(n)) {
return n;
}
@@ -1339,7 +1339,7 @@ namespace ts {
const options: TranspileOptions = {
fileName: "config.js",
compilerOptions: {
target: ScriptTarget.ES6,
target: ScriptTarget.ES2015,
removeComments: true
},
reportDiagnostics: true
@@ -58,7 +58,7 @@ export function delint(sourceFile: ts.SourceFile) {
const fileNames: string[] = process.argv.slice(2);
fileNames.forEach(fileName => {
// Parse a file
let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true);
let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES2015, /*setParentNodes */ true);
// delint it
delint(sourceFile);
@@ -113,7 +113,7 @@ exports.delint = delint;
var fileNames = process.argv.slice(2);
fileNames.forEach(function (fileName) {
// Parse a file
var sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true);
var sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES2015, /*setParentNodes */ true);
// delint it
delint(sourceFile);
});
@@ -4,7 +4,7 @@ tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(10,11): error TS2304: Cann
==== tests/cases/conformance/Symbols/ES5SymbolProperty2.ts (2 errors) ====
module M {
var Symbol;
var Symbol: any;
export class C {
[Symbol.iterator]() { }
@@ -1,6 +1,6 @@
//// [ES5SymbolProperty2.ts]
module M {
var Symbol;
var Symbol: any;
export class C {
[Symbol.iterator]() { }

Some files were not shown because too many files have changed in this diff Show More