Merge branch 'master' into add-undefined-to-default-valued-parameters

This commit is contained in:
Nathan Shively-Sanders
2016-12-07 16:12:25 -08:00
974 changed files with 110461 additions and 69999 deletions
+77 -7
View File
@@ -1,32 +1,38 @@
Alexander <alexander@kuvaev.me># Alexander Kuvaev
AbubakerB <abubaker_bashir@hotmail.com> # Abubaker Bashir
Alexander <alexander@kuvaev.me># Alexander Kuvaev
Adam Freidin <adam.freidin@gmail.com> Adam Freidin <afreidin@adobe.com>
Adi Dahiya <adahiya@palantir.com> Adi Dahiya <adi.dahiya14@gmail.com>
Ahmad Farid <ahfarid@microsoft.com> ahmad-farid <ahfarid@microsoft.com>
Alexander Rusakov <a_s_rusakov@mail.ru>
Alex Eagle <alexeagle@google.com>
Anatoly Ressin <anatoly.ressin@icloud.com>
Anders Hejlsberg <andersh@microsoft.com> unknown <andersh@AndersX1.NOE.Nokia.com> unknown <andersh@andersh-yoga.redmond.corp.microsoft.com>
Andrej Baran <andrej.baran@gmail.com>
Andrew Z Allen <me@andrewzallen.com>
Andy Hanson <anhans@microsoft.com> Andy <anhans@microsoft.com>
Anil Anar <anilanar@hotmail.com>
Anton Tolmachev <myste@mail.ru>
Arnavion <arnavion@gmail.com> # Arnav Singh
Arthur Ozga <aozgaa@umich.edu> Arthur Ozga <t-arthoz@microsoft.com>
Arthur Ozga <aozgaa@umich.edu> Arthur Ozga <t-arthoz@microsoft.com> Arthur Ozga <aozgaa-ms@outlook.com> Arthur Ozga <aozgaa@users.noreply.github.com> Arthur Ozga <arozga@microsoft.com>
Asad Saeeduddin <masaeedu@gmail.com>
Schmavery <avery.schmavery@gmail.com> # Avery Morin
Basarat Ali Syed <basaratali@gmail.com> Basarat Syed <basaratali@gmail.com> basarat <basaratali@gmail.com>
Bill Ticehurst <billti@hotmail.com> Bill Ticehurst <billti@microsoft.com>
Ben Duffield <jebavarde@gmail.com>
Ben Mosher <me@benmosher.com>
Blake Embrey <hello@blakeembrey.com>
Bowden Kelly <wilkelly@microsoft.com>
Brett Mayen <bmayen@midnightsnacks.net>
Bryan Forbes <bryan@reigndropsfall.net>
Caitlin Potter <caitpotter88@gmail.com>
ChrisBubernak <chris.bubernak@gmail.com> unknown <chrbub@chrbub1.redmond.corp.microsoft.com> # Chris Bubernak
Christophe Vidal <kriss@krizalys.com>
Chuck Jazdzewski <chuckj@google.com>
Colby Russell <mr@colbyrussell.com>
Colin Snover <github.com@zetafleet.com>
Cyrus Najmabadi <cyrusn@microsoft.com> CyrusNajmabadi <cyrusn@microsoft.com> unknown <cyrusn@cylap.ntdev.corp.microsoft.com>
Dafrok <o.o@mug.dog> # Dafrok Zhang
Dan Corder <dev@dancorder.com>
Dan Quirk <danquirk@microsoft.com> Dan Quirk <danquirk@users.noreply.github.com> nknown <danquirk@DANQUIRK1.redmond.corp.microsoft.com>
Daniel Rosenwasser <drosen@microsoft.com> Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com> Daniel Rosenwasser <DanielRosenwasser@gmail.com> Daniel Rosenwasser <Daniel.Rosenwasser@microsoft.com> Daniel Rosenwasser <DanielRosenwasser@microsoft.com>
@@ -36,17 +42,22 @@ Denis Nedelyaev <denvned@gmail.com>
Dick van den Brink <d_vandenbrink@outlook.com> unknown <d_vandenbrink@outlook.com> unknown <d_vandenbrink@live.com>
Dirk Baeumer <dirkb@microsoft.com> Dirk Bäumer <dirkb@microsoft.com> # Dirk Bäumer
Dirk Holtwick <dirk.holtwick@gmail.com>
Dom Chen <domchen@users.noreply.github.com>
Doug Ilijev <dilijev@users.noreply.github.com>
Erik Edrosa <erik.edrosa@gmail.com>
erictsangx <erictsangx@gmail.com> # Eric Tsang
Ethan Rubio <ethanrubio@users.noreply.github.com>
Evan Martin <martine@danga.com>
Evan Sebastian <evanlhoini@gmail.com>
Eyas <eyas.sharaiha@gmail.com> # Eyas Sharaiha
Fabian Cook <faybecook@gmail.com>
falsandtru <falsandtru@users.noreply.github.com> # @falsandtru
Frank Wallis <fwallis@outlook.com>
František Žiačik <fziacik@gratex.com> František Žiačik <ziacik@gmail.com>
František Žiacik <fziacik@gratex.com> František Žiacik <ziacik@gmail.com>
Gabe Moothart <gmoothart@gmail.com>
Gabriel Isenberg <gisenberg@gmail.com>
Gilad Peleg <giladp007@gmail.com>
Godfrey Chan <godfreykfc@gmail.com>
Graeme Wicksted <graeme.wicksted@gmail.com>
Guillaume Salles <guillaume.salles@me.com>
Guy Bedford <guybedford@gmail.com> guybedford <guybedford@gmail.com>
@@ -55,6 +66,7 @@ Iain Monro <iain.monro@softwire.com>
Ingvar Stepanyan <me@rreverser.com>
impinball <impinball@gmail.com> # Isiah Meadows
Ivo Gabe de Wolff <ivogabe@ivogabe.nl>
Jakub Młokosiewicz <hckr@users.noreply.github.com>
James Whitney <james@whitney.io>
Jason Freeman <jfreeman@microsoft.com> Jason Freeman <JsonFreeman@users.noreply.github.com>
Jason Killian <jkillian@palantir.com>
@@ -69,11 +81,14 @@ Jonathan Park <jpark@daptiv.com>
Jonathan Turner <jont@microsoft.com> Jonathan Turner <probata@hotmail.com>
Jonathan Toland <toland@dnalot.com>
Jesse Schalken <me@jesseschalken.com>
Josh Abernathy <joshaber@gmail.com> joshaber <joshaber@gmail.com>
Josh Kalderimis <josh.kalderimis@gmail.com>
Josh Soref <jsoref@users.noreply.github.com>
Juan Luis Boya García <ntrrgc@gmail.com>
Julian Williams <julianjw92@gmail.com>
Herrington Darkholme <nonamesheep1@gmail.com>
Justin Bay <justin.bay@outlook.com>
Justin Johansson <thebabellion@gmail.com>
Herrington Darkholme <nonamesheep1@gmail.com> (´·?·`) <HerringtonDarkholme@users.noreply.github.com> # Herrington Darkholme
Kagami Sascha Rosylight <saschanaz@outlook.com> SaschaNaz <saschanaz@outlook.com>
Kanchalai Tanglertsampan <yuisu@microsoft.com> Yui <yuit@users.noreply.github.com>
Kanchalai Tanglertsampan <yuisu@microsoft.com> Yui T <yuisu@microsoft.com>
@@ -82,23 +97,29 @@ Kanchalai Tanglertsampan <yuisu@microsoft.com> Yui <yuisu@microsoft.com>
Kanchalai Tanglertsampan <yuisu@microsoft.com> yui T <yuisu@microsoft.com>
Keith Mashinter <kmashint@yahoo.com> kmashint <kmashint@yahoo.com>
Ken Howard <ken@simplicatedweb.com>
Kevin Lang <klang2012@gmail.com>
kimamula <kenji.imamula@gmail.com> # Kenji Imamula
Kyle Kelley <rgbkrk@gmail.com>
Lorant Pinter <lorant.pinter@prezi.com>
Lucien Greathouse <me@lpghatguy.com>
Lukas Elmer <lukas.elmer@gmail.com> Lukas Elmer <lukas.elmer@renuo.ch>
Martin Vseticka <vseticka.martin@gmail.com> Martin Všeticka <vseticka.martin@gmail.com> MartyIX <vseticka.martin@gmail.com>
gcnew <gcnew@abv.bg> # Marin Marinov
vvakame <vvakame+dev@gmail.com> # Masahiro Wakame
Matt McCutchen <rmccutch@mit.edu>
Max Deepfield <maxdeepfield@absolutefreakout.com>
Micah Zoltu <micah@zoltu.net>
Michael <maykelchiche@gmail.com>
Mohamed Hegazy <mhegazy@microsoft.com>
Nathan Shively-Sanders <nathansa@microsoft.com>
Nathan Yee <ny.nathan.yee@gmail.com>
Nima Zahedi <nima.zahedee@gmail.com>
Noah Chen <nchen@palantir.com>
Noj Vek <nojvek@gmail.com>
mihailik <mihailik@gmail.com> # Oleg Mihailik
Oleksandr Chekhovskyi <oleksandr.chekhovskyi@hansoft.com>
Paul van Brenk <paul.van.brenk@microsoft.com> Paul van Brenk <paul.van.brenk@outlook.com> unknown <paul.van.brenk@microsoft.com> unknown <paul.van.brenk@microsoft.com> unknown <pvanbren@pvbvsproai.redmond.corp.microsoft.com>
Omer Sheikh <ojsheikh@gmail.com>
Oskar Segersva¨rd <oskar.segersvard@widespace.com>
pcan <piero.cangianiello@gmail.com> # Piero Cangianiello
pcbro <2bux89+dk3zspjmuh16o@sharklasers.com> # @pcbro
@@ -109,21 +130,26 @@ progre <djyayutto@gmail.com> # @progre
Prayag Verma <prayag.verma@gmail.com>
Punya Biswal <pbiswal@palantir.com>
Rado Kirov <radokirov@google.com>
Ron Buckton <rbuckton@microsoft.com> Ron Buckton <ron.buckton@microsoft.com>
Ron Buckton <rbuckton@microsoft.com> Ron Buckton <ron.buckton@microsoft.com> rbuckton <rbuckton@chronicles.org>
Rostislav Galimsky <rostgal@gmail.com>
Richard Knoll <riknoll@users.noreply.github.com> Richard Knoll <riknoll@microsoft.com>
Rowan Wyborn <rwyborn@internode.on.net>
Ryan Cavanaugh <RyanCavanaugh@users.noreply.github.com> Ryan Cavanaugh <ryan.cavanaugh@microsoft.com> Ryan Cavanaugh <ryanca@microsoft.com>
Ryohei Ikegami <iofg2100@gmail.com>
Sarangan Rajamanickam <sarajama@microsoft.com>
Sébastien Arod <sebastien.arod@gmail.com>
Sergey Shandar <sergey-shandar@users.noreply.github.com>
Sheetal Nandi <shkamat@microsoft.com>
Shengping Zhong <zhongsp@users.noreply.github.com>
shyyko.serhiy@gmail.com <shyyko.serhiy@gmail.com> # Shyyko Serhiy
Sam El-Husseini <samelh@microsoft.com>
Simon Hürlimann <simon.huerlimann@cyt.ch>
Slawomir Sadziak <slsadzia@microsoft.com>
Solal Pirelli <solal.pirelli@gmail.com>
Stan Thomas <stmsdn@norvil.net>
Stanislav Sysoev <d4rkr00t@gmail.com>
Steve Lucco <steveluc@users.noreply.github.com> steveluc <steveluc@microsoft.com>
Sudheesh Singanamalla <sudheesh1995@outlook.com>
Tarik <tarik@pushmote.com> # Tarik Ozket
Tetsuharu OHZEKI <saneyuki.snyk@gmail.com> # Tetsuharu Ohzeki
Tien Nguyen <tihoanh@microsoft.com> tien <hoanhtien@users.noreply.github.com> unknown <tihoanh@microsoft.com> #Tien Hoanhtien
@@ -133,6 +159,7 @@ Tingan Ho <tingan87@gmail.com>
togru <v3nomzxgt8@gmail.com> # togru
Tomas Grubliauskas <tgrubliauskas@gmail.com>
ToddThomson <achilles@telus.net> # Todd Thomson
Torben Fitschen <torben.fitschen@mayflower.de>
TruongSinh Tran-Nguyen <i@truongsinh.pro>
vilicvane <i@vilic.info> # Vilic Vane
Vladimir Matveev <vladima@microsoft.com> vladima <vladima@microsoft.com> v2m <desco.by@gmail.com>
@@ -140,7 +167,50 @@ Wesley Wigham <t-weswig@microsoft.com> Wesley Wigham <wwigham@gmail.com>
York Yao <plantain-00@users.noreply.github.com> york yao <yaoao12306@outlook.com> yaoyao <yaoyao12306@163.com>
Yuichi Nukiyama <oscar.wilde84@hotmail.co.jp> YuichiNukiyama <oscar.wilde84@hotmail.co.jp>
Zev Spitz <shivisi@etrog.net.il>
Zhengbo Li <zhengbli@microsoft.com> zhengbli <zhengbli@microsoft.com> Zhengbo Li <Zhengbo Li> Zhengbo Li <zhengbli@mirosoft.com> tinza123 <li.zhengbo@outlook.com> unknown <zhengbli@zhengblit430.redmond.corp.microsoft.com> Zhengbo Li <Zhengbo Li>
Zhengbo Li <zhengbli@microsoft.com> zhengbli <zhengbli@microsoft.com> Zhengbo Li <Zhengbo Li> Zhengbo Li <zhengbli@mirosoft.com> tinza123 <li.zhengbo@outlook.com> unknown <zhengbli@zhengblit430.redmond.corp.microsoft.com> Zhengbo Li <Zhengbo Li> zhengbli <zhengli@microsoft.com>
zhongsp <patrick.zhongsp@gmail.com> # Patrick Zhong
T18970237136 <T18970237136@users.noreply.github.com> # @T18970237136
JBerger <JBerger@melco.com>
JBerger <JBerger@melco.com>
bootstraponline <code@bootstraponline.com> # @bootstraponline
yortus <yortus@gmail.com> # @yortus
András Parditka <andraaspar@gmail.com>
Anton Khlynovskiy <subzey@gmail.com>
Charly POLY <cpoly55@gmail.com>
Cotton Hou <himcotton@gmail.com>
Ethan Resnick <ethan.resnick@gmail.com>
Marius Schulz <marius.schulz@me.com>
Mattias Buelens <mattias.buelens@gmail.com>
Myles Megyesi <mylesmegyesi@users.noreply.github.com>
Tim Lancina <tim@ionic.io>
Aaron Holmes <aaron@aaronholmes.net> Aaron Holmes <aholmes@bltomato.com>
Akshar Patel <akshar.patel.47@gmail.com>
Ali Sabzevari <alisabzevari@gmail.com>
Aliaksandr Radzivanovich <aradzivanovich@gmail.com>
BuildTools <FranklinWhale@users.noreply.github.com> # Franklin Tse
ChogyDan <danielhollocher@gmail.com> # Daniel Hollocher
Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com> Daniel Rosenwasser <drosen@microsoft.com>
David Kmenta <david.kmenta@lmc.eu>
E020873 <nicolas.henry-partner@arcelormittal.com> # Nicolas Henry
Elisée Maurer <elisee@sparklinlabs.com>
Emilio García-Pumarino <emili.tfe@gmail.com> dashaus <emili.tfe@gmail.com>
Guilherme Oenning <me@goenning.net>
Herrington Darkholme <nonamesheep1@gmail.com>
Ivo Gabe de Wolff <ivogabe@ivogabe.nl>
Joey Wilson <joey.wilson.a@gmail.com>
Jonathon Smith <failing@crashdive.co.uk>
Juan Luis Boya García <ntrrgc@gmail.com>
Kagami Sascha Rosylight <saschanaz@outlook.com>
Lucien Greathouse <me@lpghatguy.com>
Martin Vseticka <vseticka.martin@gmail.com>
Mattias Buelens <mattias.buelens@opentelly.com>
Michael Bromley <michael@michaelbromley.co.uk>
Paul Jolly <paul@myitcv.org.uk>
Perry Jiang <jiangperry@gmail.com>
Peter Burns <rictic@google.com>
Robert Coie <rac@intrigue.com>
Thomas Loubiou <t.loubiou@systonic.fr>
Tim Perry <tim.perry@softwire.com>
Vidar Tonaas Fauske <vidartf@gmail.com>
Viktor Zozulyak <zozulyakviktor@gmail.com>
rix <rix@rixs-MacBook-Pro.local> # Richard Sentino
rohitverma007 <rohitverma@live.ca> # Rohit Verma
+64 -1
View File
@@ -1,14 +1,23 @@
TypeScript is authored by:
* Aaron Holmes
* Abubaker Bashir
* Adam Freidin
* Adi Dahiya
* Ahmad Farid
* Akshar Patel
* Alex Eagle
* Alexander Kuvaev
* Alexander Rusakov
* Ali Sabzevari
* Aliaksandr Radzivanovich
* Anatoly Ressin
* Anders Hejlsberg
* Andrej Baran
* Andrew Z Allen
* András Parditka
* Andy Hanson
* Anil Anar
* Anton Khlynovskiy
* Anton Tolmachev
* Arnav Singh
* Arthur Ozga
@@ -16,38 +25,56 @@ TypeScript is authored by:
* Avery Morin
* Basarat Ali Syed
* Ben Duffield
* Ben Mosher
* Bill Ticehurst
* Blake Embrey
* @bootstraponline
* Bowden Kelly
* Brett Mayen
* Bryan Forbes
* Caitlin Potter
* Charly POLY
* Chris Bubernak
* Christophe Vidal
* Chuck Jazdzewski
* Colby Russell
* Colin Snover
* Cotton Hou
* Cyrus Najmabadi
* Dafrok Zhang
* Dan Corder
* Dan Quirk
* Daniel Hollocher
* Daniel Rosenwasser
* David Kmenta
* David Li
* David Souther
* Denis Nedelyaev
* Dick van den Brink
* Dirk Bäumer
* Dirk Holtwick
* Dom Chen
* Doug Ilijev
* Elisée Maurer
* Emilio García-Pumarino
* Eric Tsang
* Erik Edrosa
* Ethan Resnick
* Ethan Rubio
* Evan Martin
* Evan Sebastian
* Eyas Sharaiha
* Fabian Cook
* @falsandtru
* Frank Wallis
* František Žiačik
* Franklin Tse
* František Žiacik
* Gabe Moothart
* Gabriel Isenberg
* Gilad Peleg
* Godfrey Chan
* Graeme Wicksted
* Guilherme Oenning
* Guillaume Salles
* Guy Bedford
* Harald Niesche
@@ -56,6 +83,7 @@ TypeScript is authored by:
* Ingvar Stepanyan
* Isiah Meadows
* Ivo Gabe de Wolff
* Jakub Młokosiewicz
* James Whitney
* Jason Freeman
* Jason Killian
@@ -65,41 +93,61 @@ TypeScript is authored by:
* Jeffrey Morlan
* Jesse Schalken
* Jiri Tobisek
* Joey Wilson
* Johannes Rieken
* John Vilk
* Jonathan Bond-Caron
* Jonathan Park
* Jonathan Toland
* Jonathan Turner
* Jonathon Smith
* Josh Abernathy
* Josh Kalderimis
* Josh Soref
* Juan Luis Boya García
* Julian Williams
* Justin Bay
* Justin Johansson
* Kagami Sascha Rosylight
* Kanchalai Tanglertsampan
* Keith Mashinter
* Ken Howard
* Kenji Imamula
* Kevin Lang
* Kyle Kelley
* Lorant Pinter
* Lucien Greathouse
* Lukas Elmer
* Marin Marinov
* Marius Schulz
* Martin Vseticka
* Masahiro Wakame
* Matt McCutchen
* Mattias Buelens
* Mattias Buelens
* Max Deepfield
* Micah Zoltu
* Michael
* Michael Bromley
* Mohamed Hegazy
* Myles Megyesi
* Nathan Shively-Sanders
* Nathan Yee
* Nicolas Henry
* Nima Zahedi
* Noah Chen
* Noj Vek
* Oleg Mihailik
* Oleksandr Chekhovskyi
* Omer Sheikh
* Oskar Segersva¨rd
* Patrick Zhong
* Paul Jolly
* Paul van Brenk
* @pcbro
* Pedro Maltez
* Perry Jiang
* Peter Burns
* Philip Bulley
* Piero Cangianiello
* @piloopin
@@ -108,34 +156,49 @@ TypeScript is authored by:
* Punya Biswal
* Rado Kirov
* Richard Knoll
* Richard Sentino
* Robert Coie
* Rohit Verma
* Ron Buckton
* Rostislav Galimsky
* Rowan Wyborn
* Ryan Cavanaugh
* Ryohei Ikegami
* Sam El-Husseini
* Sarangan Rajamanickam
* Sergey Shandar
* Sheetal Nandi
* Shengping Zhong
* Shyyko Serhiy
* Simon Hürlimann
* Slawomir Sadziak
* Solal Pirelli
* Stan Thomas
* Stanislav Sysoev
* Steve Lucco
* Sudheesh Singanamalla
* Sébastien Arod
* @T18970237136
* Tarik Ozket
* Tetsuharu Ohzeki
* Thomas Loubiou
* Tien Hoanhtien
* Tim Lancina
* Tim Perry
* Tim Viiding-Spader
* Tingan Ho
* Todd Thomson
* togru
* Tomas Grubliauskas
* Torben Fitschen
* TruongSinh Tran-Nguyen
* Vidar Tonaas Fauske
* Viktor Zozulyak
* Vilic Vane
* Vladimir Matveev
* Wesley Wigham
* York Yao
* @yortus
* Yuichi Nukiyama
* Zev Spitz
* Zhengbo Li
+4 -3
View File
@@ -128,7 +128,8 @@ const es2016LibrarySourceMap = es2016LibrarySource.map(function(source) {
const es2017LibrarySource = [
"es2017.object.d.ts",
"es2017.sharedmemory.d.ts"
"es2017.sharedmemory.d.ts",
"es2017.string.d.ts",
];
const es2017LibrarySourceMap = es2017LibrarySource.map(function(source) {
@@ -176,7 +177,7 @@ for (const i in libraryTargets) {
const configureNightlyJs = path.join(scriptsDirectory, "configureNightly.js");
const configureNightlyTs = path.join(scriptsDirectory, "configureNightly.ts");
const packageJson = "package.json";
const programTs = path.join(compilerDirectory, "program.ts");
const versionFile = path.join(compilerDirectory, "core.ts");
function needsUpdate(source: string | string[], dest: string | string[]): boolean {
if (typeof source === "string" && typeof dest === "string") {
@@ -284,7 +285,7 @@ gulp.task(configureNightlyJs, false, [], () => {
// Nightly management tasks
gulp.task("configure-nightly", "Runs scripts/configureNightly.ts to prepare a build for nightly publishing", [configureNightlyJs], (done) => {
exec(host, [configureNightlyJs, packageJson, programTs], done, done);
exec(host, [configureNightlyJs, packageJson, versionFile], done, done);
});
gulp.task("publish-nightly", "Runs `npm publish --tag next` to create a new nightly build on npm", ["LKG"], () => {
return runSequence("clean", "useDebugMode", "runtests", (done) => {
+15 -12
View File
@@ -71,6 +71,7 @@ var compilerSources = [
"transformers/destructuring.ts",
"transformers/ts.ts",
"transformers/jsx.ts",
"transformers/esnext.ts",
"transformers/es2017.ts",
"transformers/es2016.ts",
"transformers/es2015.ts",
@@ -107,6 +108,7 @@ var servicesSources = [
"transformers/destructuring.ts",
"transformers/ts.ts",
"transformers/jsx.ts",
"transformers/esnext.ts",
"transformers/es2017.ts",
"transformers/es2016.ts",
"transformers/es2015.ts",
@@ -171,6 +173,7 @@ var servicesSources = [
var serverCoreSources = [
"types.d.ts",
"shared.ts",
"utilities.ts",
"scriptVersionCache.ts",
"typingsCache.ts",
@@ -193,6 +196,7 @@ var cancellationTokenSources = [
var typingsInstallerSources = [
"../types.d.ts",
"../shared.ts",
"typingsInstaller.ts",
"nodeTypingsInstaller.ts"
].map(function (f) {
@@ -252,7 +256,7 @@ var harnessSources = harnessCoreSources.concat([
"commandLineParsing.ts",
"configurationExtension.ts",
"convertCompilerOptionsFromJson.ts",
"convertTypingOptionsFromJson.ts",
"convertTypeAcquisitionFromJson.ts",
"tsserverProjectSystem.ts",
"compileOnSave.ts",
"typingsInstaller.ts",
@@ -299,7 +303,8 @@ var es2016LibrarySourceMap = es2016LibrarySource.map(function (source) {
var es2017LibrarySource = [
"es2017.object.d.ts",
"es2017.sharedmemory.d.ts"
"es2017.sharedmemory.d.ts",
"es2017.string.d.ts",
];
var es2017LibrarySourceMap = es2017LibrarySource.map(function (source) {
@@ -588,7 +593,7 @@ task("generate-diagnostics", [diagnosticInfoMapTs]);
var configureNightlyJs = path.join(scriptsDirectory, "configureNightly.js");
var configureNightlyTs = path.join(scriptsDirectory, "configureNightly.ts");
var packageJson = "package.json";
var programTs = path.join(compilerDirectory, "program.ts");
var versionFile = path.join(compilerDirectory, "core.ts");
file(configureNightlyTs);
@@ -604,7 +609,7 @@ task("setDebugMode", function () {
});
task("configure-nightly", [configureNightlyJs], function () {
var cmd = host + " " + configureNightlyJs + " " + packageJson + " " + programTs;
var cmd = host + " " + configureNightlyJs + " " + packageJson + " " + versionFile;
console.log(cmd);
exec(cmd);
}, { async: true });
@@ -635,7 +640,7 @@ task("importDefinitelyTypedTests", [importDefinitelyTypedTestsJs], function () {
// Local target to build the compiler and services
var tscFile = path.join(builtLocalDirectory, compilerFilename);
compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false);
compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false, { noMapRoot: true });
var servicesFile = path.join(builtLocalDirectory, "typescriptServices.js");
var servicesFileInBrowserTest = path.join(builtLocalDirectory, "typescriptServicesInBrowserTest.js");
@@ -925,7 +930,7 @@ function runConsoleTests(defaultReporter, runInParallel) {
}
if (tests && tests.toLocaleLowerCase() === "rwc") {
testTimeout = 400000;
testTimeout = 800000;
}
colors = process.env.colors || process.env.color;
@@ -1081,12 +1086,10 @@ task("tests-debug", ["setDebugMode", "tests"]);
// Makes the test results the new baseline
desc("Makes the most recent test results the new baseline, overwriting the old baseline");
task("baseline-accept", function () {
acceptBaseline("");
acceptBaseline(localBaseline, refBaseline);
});
function acceptBaseline(containerFolder) {
var sourceFolder = path.join(localBaseline, containerFolder);
var targetFolder = path.join(refBaseline, containerFolder);
function acceptBaseline(sourceFolder, targetFolder) {
console.log('Accept baselines from ' + sourceFolder + ' to ' + targetFolder);
var files = fs.readdirSync(sourceFolder);
var deleteEnding = '.delete';
@@ -1110,12 +1113,12 @@ function acceptBaseline(containerFolder) {
desc("Makes the most recent rwc test results the new baseline, overwriting the old baseline");
task("baseline-accept-rwc", function () {
acceptBaseline("rwc");
acceptBaseline(localRwcBaseline, refRwcBaseline);
});
desc("Makes the most recent test262 test results the new baseline, overwriting the old baseline");
task("baseline-accept-test262", function () {
acceptBaseline("test262");
acceptBaseline(localTest262Baseline, refTest262Baseline);
});
+2 -2
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:** 2.0.3 / nightly (2.1.0-dev.201xxxxx)
**TypeScript Version:** 2.1.1 / nightly (2.2.0-dev.201xxxxx)
**Code**
@@ -13,4 +13,4 @@
**Expected behavior:**
**Actual behavior:**
**Actual behavior:**
-2
View File
@@ -39,5 +39,3 @@ function createCancellationToken(args) {
};
}
module.exports = createCancellationToken;
//# sourceMappingURL=cancellationToken.js.map
+14 -10
View File
@@ -5836,6 +5836,7 @@ interface CSSStyleDeclaration {
writingMode: string | null;
zIndex: string | null;
zoom: string | null;
resize: string | null;
getPropertyPriority(propertyName: string): string;
getPropertyValue(propertyName: string): string;
item(index: number): string;
@@ -5905,6 +5906,7 @@ declare var CanvasGradient: {
}
interface CanvasPattern {
setTransform(matrix: SVGMatrix): void;
}
declare var CanvasPattern: {
@@ -6330,7 +6332,7 @@ interface DataTransfer {
effectAllowed: string;
readonly files: FileList;
readonly items: DataTransferItemList;
readonly types: DOMStringList;
readonly types: string[];
clearData(format?: string): boolean;
getData(format: string): string;
setData(format: string, data: string): boolean;
@@ -12759,7 +12761,7 @@ interface MouseEvent extends UIEvent {
readonly x: number;
readonly y: number;
getModifierState(keyArg: string): boolean;
initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void;
initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void;
}
declare var MouseEvent: {
@@ -12872,6 +12874,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte
readonly plugins: PluginArray;
readonly pointerEnabled: boolean;
readonly webdriver: boolean;
readonly hardwareConcurrency: number;
getGamepads(): Gamepad[];
javaEnabled(): boolean;
msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void;
@@ -12889,18 +12892,18 @@ interface Node extends EventTarget {
readonly attributes: NamedNodeMap;
readonly baseURI: string | null;
readonly childNodes: NodeList;
readonly firstChild: Node;
readonly lastChild: Node;
readonly firstChild: Node | null;
readonly lastChild: Node | null;
readonly localName: string | null;
readonly namespaceURI: string | null;
readonly nextSibling: Node;
readonly nextSibling: Node | null;
readonly nodeName: string;
readonly nodeType: number;
nodeValue: string | null;
readonly ownerDocument: Document;
readonly parentElement: HTMLElement;
readonly parentNode: Node;
readonly previousSibling: Node;
readonly parentElement: HTMLElement | null;
readonly parentNode: Node | null;
readonly previousSibling: Node | null;
textContent: string | null;
appendChild(newChild: Node): Node;
cloneNode(deep?: boolean): Node;
@@ -17010,7 +17013,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
readonly devicePixelRatio: number;
readonly doNotTrack: string;
readonly document: Document;
event: Event;
event: Event | undefined;
readonly external: External;
readonly frameElement: Element;
readonly frames: Window;
@@ -17312,6 +17315,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly upload: XMLHttpRequestUpload;
withCredentials: boolean;
msCaching?: string;
readonly responseURL: string;
abort(): void;
getAllResponseHeaders(): string;
getResponseHeader(header: string): string | null;
@@ -18458,7 +18462,7 @@ declare var defaultStatus: string;
declare var devicePixelRatio: number;
declare var doNotTrack: string;
declare var document: Document;
declare var event: Event;
declare var event: Event | undefined;
declare var external: External;
declare var frameElement: Element;
declare var frames: Window;
+14 -10
View File
@@ -1699,6 +1699,7 @@ interface CSSStyleDeclaration {
writingMode: string | null;
zIndex: string | null;
zoom: string | null;
resize: string | null;
getPropertyPriority(propertyName: string): string;
getPropertyValue(propertyName: string): string;
item(index: number): string;
@@ -1768,6 +1769,7 @@ declare var CanvasGradient: {
}
interface CanvasPattern {
setTransform(matrix: SVGMatrix): void;
}
declare var CanvasPattern: {
@@ -2193,7 +2195,7 @@ interface DataTransfer {
effectAllowed: string;
readonly files: FileList;
readonly items: DataTransferItemList;
readonly types: DOMStringList;
readonly types: string[];
clearData(format?: string): boolean;
getData(format: string): string;
setData(format: string, data: string): boolean;
@@ -8622,7 +8624,7 @@ interface MouseEvent extends UIEvent {
readonly x: number;
readonly y: number;
getModifierState(keyArg: string): boolean;
initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void;
initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void;
}
declare var MouseEvent: {
@@ -8735,6 +8737,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte
readonly plugins: PluginArray;
readonly pointerEnabled: boolean;
readonly webdriver: boolean;
readonly hardwareConcurrency: number;
getGamepads(): Gamepad[];
javaEnabled(): boolean;
msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void;
@@ -8752,18 +8755,18 @@ interface Node extends EventTarget {
readonly attributes: NamedNodeMap;
readonly baseURI: string | null;
readonly childNodes: NodeList;
readonly firstChild: Node;
readonly lastChild: Node;
readonly firstChild: Node | null;
readonly lastChild: Node | null;
readonly localName: string | null;
readonly namespaceURI: string | null;
readonly nextSibling: Node;
readonly nextSibling: Node | null;
readonly nodeName: string;
readonly nodeType: number;
nodeValue: string | null;
readonly ownerDocument: Document;
readonly parentElement: HTMLElement;
readonly parentNode: Node;
readonly previousSibling: Node;
readonly parentElement: HTMLElement | null;
readonly parentNode: Node | null;
readonly previousSibling: Node | null;
textContent: string | null;
appendChild(newChild: Node): Node;
cloneNode(deep?: boolean): Node;
@@ -12873,7 +12876,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
readonly devicePixelRatio: number;
readonly doNotTrack: string;
readonly document: Document;
event: Event;
event: Event | undefined;
readonly external: External;
readonly frameElement: Element;
readonly frames: Window;
@@ -13175,6 +13178,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly upload: XMLHttpRequestUpload;
withCredentials: boolean;
msCaching?: string;
readonly responseURL: string;
abort(): void;
getAllResponseHeaders(): string;
getResponseHeader(header: string): string | null;
@@ -14321,7 +14325,7 @@ declare var defaultStatus: string;
declare var devicePixelRatio: number;
declare var doNotTrack: string;
declare var document: Document;
declare var event: Event;
declare var event: Event | undefined;
declare var external: External;
declare var frameElement: Element;
declare var frames: Window;
+4 -4
View File
@@ -225,13 +225,13 @@ interface NumberConstructor {
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: number): boolean;
isFinite(value: any): value is number;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: number): boolean;
isInteger(value: any): value is number;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
@@ -239,13 +239,13 @@ interface NumberConstructor {
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: number): boolean;
isNaN(value: any): value is number;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: number): boolean;
isSafeInteger(value: any): value is number;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
+3 -3
View File
@@ -19,7 +19,7 @@ and limitations under the License.
interface ProxyHandler<T> {
getPrototypeOf? (target: T): any;
getPrototypeOf? (target: T): {} | null;
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
preventExtensions? (target: T): boolean;
@@ -32,11 +32,11 @@ interface ProxyHandler<T> {
enumerate? (target: T): PropertyKey[];
ownKeys? (target: T): PropertyKey[];
apply? (target: T, thisArg: any, argArray?: any): any;
construct? (target: T, thisArg: any, argArray?: any): any;
construct? (target: T, argArray: any, newTarget?: any): {};
}
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;
declare var Proxy: ProxyConstructor;
+2 -1
View File
@@ -20,4 +20,5 @@ and limitations under the License.
/// <reference path="lib.es2016.d.ts" />
/// <reference path="lib.es2017.object.d.ts" />
/// <reference path="lib.es2017.sharedmemory.d.ts" />
/// <reference path="lib.es2017.sharedmemory.d.ts" />
/// <reference path="lib.es2017.string.d.ts" />
+2 -2
View File
@@ -29,6 +29,6 @@ interface ObjectConstructor {
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries<T>(o: { [s: string]: T }): [string, T][];
entries<T extends { [key: string]: any }, K extends keyof T>(o: T): [keyof T, T[K]][];
entries(o: any): [string, any][];
}
}
+47
View File
@@ -0,0 +1,47 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface String {
/**
* Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length.
* The padding is applied from the start (left) of the current string.
*
* @param maxLength The length of the resulting string once the current string has been padded.
* If this parameter is smaller than the current string's length, the current string will be returned as it is.
*
* @param fillString The string to pad the current string with.
* If this string is too long, it will be truncated and the left-most part will be applied.
* The default value for this parameter is " " (U+0020).
*/
padStart(maxLength: number, fillString?: string): string;
/**
* Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length.
* The padding is applied from the end (right) of the current string.
*
* @param maxLength The length of the resulting string once the current string has been padded.
* If this parameter is smaller than the current string's length, the current string will be returned as it is.
*
* @param fillString The string to pad the current string with.
* If this string is too long, it will be truncated and the left-most part will be applied.
* The default value for this parameter is " " (U+0020).
*/
padEnd(maxLength: number, fillString?: string): string;
}
+22 -17
View File
@@ -4362,13 +4362,13 @@ interface NumberConstructor {
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: number): boolean;
isFinite(value: any): value is number;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: number): boolean;
isInteger(value: any): value is number;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
@@ -4376,13 +4376,13 @@ interface NumberConstructor {
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: number): boolean;
isNaN(value: any): value is number;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: number): boolean;
isSafeInteger(value: any): value is number;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
@@ -5471,7 +5471,7 @@ interface PromiseConstructor {
declare var Promise: PromiseConstructor;
interface ProxyHandler<T> {
getPrototypeOf? (target: T): any;
getPrototypeOf? (target: T): {} | null;
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
preventExtensions? (target: T): boolean;
@@ -5484,14 +5484,15 @@ interface ProxyHandler<T> {
enumerate? (target: T): PropertyKey[];
ownKeys? (target: T): PropertyKey[];
apply? (target: T, thisArg: any, argArray?: any): any;
construct? (target: T, thisArg: any, argArray?: any): any;
construct? (target: T, argArray: any, newTarget?: any): {};
}
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;
declare var Proxy: ProxyConstructor;
declare namespace Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
@@ -7555,6 +7556,7 @@ interface CSSStyleDeclaration {
writingMode: string | null;
zIndex: string | null;
zoom: string | null;
resize: string | null;
getPropertyPriority(propertyName: string): string;
getPropertyValue(propertyName: string): string;
item(index: number): string;
@@ -7624,6 +7626,7 @@ declare var CanvasGradient: {
}
interface CanvasPattern {
setTransform(matrix: SVGMatrix): void;
}
declare var CanvasPattern: {
@@ -8049,7 +8052,7 @@ interface DataTransfer {
effectAllowed: string;
readonly files: FileList;
readonly items: DataTransferItemList;
readonly types: DOMStringList;
readonly types: string[];
clearData(format?: string): boolean;
getData(format: string): string;
setData(format: string, data: string): boolean;
@@ -14478,7 +14481,7 @@ interface MouseEvent extends UIEvent {
readonly x: number;
readonly y: number;
getModifierState(keyArg: string): boolean;
initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void;
initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void;
}
declare var MouseEvent: {
@@ -14591,6 +14594,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte
readonly plugins: PluginArray;
readonly pointerEnabled: boolean;
readonly webdriver: boolean;
readonly hardwareConcurrency: number;
getGamepads(): Gamepad[];
javaEnabled(): boolean;
msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void;
@@ -14608,18 +14612,18 @@ interface Node extends EventTarget {
readonly attributes: NamedNodeMap;
readonly baseURI: string | null;
readonly childNodes: NodeList;
readonly firstChild: Node;
readonly lastChild: Node;
readonly firstChild: Node | null;
readonly lastChild: Node | null;
readonly localName: string | null;
readonly namespaceURI: string | null;
readonly nextSibling: Node;
readonly nextSibling: Node | null;
readonly nodeName: string;
readonly nodeType: number;
nodeValue: string | null;
readonly ownerDocument: Document;
readonly parentElement: HTMLElement;
readonly parentNode: Node;
readonly previousSibling: Node;
readonly parentElement: HTMLElement | null;
readonly parentNode: Node | null;
readonly previousSibling: Node | null;
textContent: string | null;
appendChild(newChild: Node): Node;
cloneNode(deep?: boolean): Node;
@@ -18729,7 +18733,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
readonly devicePixelRatio: number;
readonly doNotTrack: string;
readonly document: Document;
event: Event;
event: Event | undefined;
readonly external: External;
readonly frameElement: Element;
readonly frames: Window;
@@ -19031,6 +19035,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly upload: XMLHttpRequestUpload;
withCredentials: boolean;
msCaching?: string;
readonly responseURL: string;
abort(): void;
getAllResponseHeaders(): string;
getResponseHeader(header: string): string | null;
@@ -20177,7 +20182,7 @@ declare var defaultStatus: string;
declare var devicePixelRatio: number;
declare var doNotTrack: string;
declare var document: Document;
declare var event: Event;
declare var event: Event | undefined;
declare var external: External;
declare var frameElement: Element;
declare var frames: Window;
+2
View File
@@ -760,6 +760,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly upload: XMLHttpRequestUpload;
withCredentials: boolean;
msCaching?: string;
readonly responseURL: string;
abort(): void;
getAllResponseHeaders(): string;
getResponseHeader(header: string): string | null;
@@ -922,6 +923,7 @@ declare var WorkerLocation: {
}
interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine {
readonly hardwareConcurrency: number;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
+168 -205
View File
@@ -59,7 +59,7 @@ declare namespace ts.server.protocol {
/**
* One of "request", "response", or "event"
*/
type: string;
type: "request" | "response" | "event";
}
/**
* Client-initiated request message
@@ -653,7 +653,7 @@ declare namespace ts.server.protocol {
/**
* Script kind of the file
*/
scriptKind?: ScriptKind;
scriptKind?: ScriptKindName | ts.ScriptKind;
/**
* Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript)
*/
@@ -684,37 +684,17 @@ declare namespace ts.server.protocol {
*/
typingOptions?: TypingOptions;
}
/**
* For external projects, some of the project settings are sent together with
* compiler settings.
*/
interface ExternalProjectCompilerOptions extends CompilerOptions {
interface CompileOnSaveMixin {
/**
* If compile on save is enabled for the project
*/
compileOnSave?: boolean;
}
/**
* Contains information about current project version
* For external projects, some of the project settings are sent together with
* compiler settings.
*/
interface ProjectVersionInfo {
/**
* Project name
*/
projectName: string;
/**
* true if project is inferred or false if project is external or configured
*/
isInferred: boolean;
/**
* Project version
*/
version: number;
/**
* Current set of compiler options for project
*/
options: CompilerOptions;
}
type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin;
/**
* Represents a set of changes that happen in project
*/
@@ -728,36 +708,6 @@ declare namespace ts.server.protocol {
*/
removed: string[];
}
/**
* Describes set of files in the project.
* info might be omitted in case of inferred projects
* if files is set - then this is the entire set of files in the project
* if changes is set - then this is the set of changes that should be applied to existing project
* otherwise - assume that nothing is changed
*/
interface ProjectFiles {
/**
* Information abount project verison
*/
info?: ProjectVersionInfo;
/**
* List of files in project (might be omitted if current state of project can be computed using only information from 'changes')
*/
files?: string[];
/**
* Set of changes in project (omitted if the entire set of files in project should be replaced)
*/
changes?: ProjectChanges;
}
/**
* Combines project information with project level errors.
*/
interface ProjectFilesWithDiagnostics extends ProjectFiles {
/**
* List of errors in project
*/
projectErrors: DiagnosticWithLinePosition[];
}
/**
* Information found in a configure request.
*/
@@ -803,8 +753,9 @@ declare namespace ts.server.protocol {
* Used to specify the script kind of the file explicitly. It could be one of the following:
* "TS", "JS", "TSX", "JSX"
*/
scriptKindName?: "TS" | "JS" | "TSX" | "JSX";
scriptKindName?: ScriptKindName;
}
type ScriptKindName = "TS" | "JS" | "TSX" | "JSX";
/**
* Open request; value of command field is "open". Notify the
* server that the client has file open. The server will not
@@ -878,15 +829,6 @@ declare namespace ts.server.protocol {
*/
interface CloseExternalProjectResponse extends Response {
}
/**
* Arguments to SynchronizeProjectListRequest
*/
interface SynchronizeProjectListRequestArgs {
/**
* List of last known projects
*/
knownProjects: protocol.ProjectVersionInfo[];
}
/**
* Request to set compiler options for inferred projects.
* External projects are opened / closed explicitly.
@@ -1669,12 +1611,158 @@ declare namespace ts.server.protocol {
spans: TextSpan[];
childItems?: NavigationTree[];
}
type TelemetryEventName = "telemetry";
interface TelemetryEvent extends Event {
event: TelemetryEventName;
body: TelemetryEventBody;
}
interface TelemetryEventBody {
telemetryEventName: string;
payload: any;
}
type TypingsInstalledTelemetryEventName = "typingsInstalled";
interface TypingsInstalledTelemetryEventBody extends TelemetryEventBody {
telemetryEventName: TypingsInstalledTelemetryEventName;
payload: TypingsInstalledTelemetryEventPayload;
}
interface TypingsInstalledTelemetryEventPayload {
/**
* Comma separated list of installed typing packages
*/
installedPackages: string;
/**
* true if install request succeeded, otherwise - false
*/
installSuccess: boolean;
}
interface NavBarResponse extends Response {
body?: NavigationBarItem[];
}
interface NavTreeResponse extends Response {
body?: NavigationTree;
}
namespace IndentStyle {
type None = "None";
type Block = "Block";
type Smart = "Smart";
}
type IndentStyle = IndentStyle.None | IndentStyle.Block | IndentStyle.Smart;
interface EditorSettings {
baseIndentSize?: number;
indentSize?: number;
tabSize?: number;
newLineCharacter?: string;
convertTabsToSpaces?: boolean;
indentStyle?: IndentStyle | ts.IndentStyle;
}
interface FormatCodeSettings extends EditorSettings {
insertSpaceAfterCommaDelimiter?: boolean;
insertSpaceAfterSemicolonInForStatements?: boolean;
insertSpaceBeforeAndAfterBinaryOperators?: boolean;
insertSpaceAfterKeywordsInControlFlowStatements?: boolean;
insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean;
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean;
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean;
placeOpenBraceOnNewLineForFunctions?: boolean;
placeOpenBraceOnNewLineForControlBlocks?: boolean;
}
interface CompilerOptions {
allowJs?: boolean;
allowSyntheticDefaultImports?: boolean;
allowUnreachableCode?: boolean;
allowUnusedLabels?: boolean;
baseUrl?: string;
charset?: string;
declaration?: boolean;
declarationDir?: string;
disableSizeLimit?: boolean;
emitBOM?: boolean;
emitDecoratorMetadata?: boolean;
experimentalDecorators?: boolean;
forceConsistentCasingInFileNames?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
isolatedModules?: boolean;
jsx?: JsxEmit | ts.JsxEmit;
lib?: string[];
locale?: string;
mapRoot?: string;
maxNodeModuleJsDepth?: number;
module?: ModuleKind | ts.ModuleKind;
moduleResolution?: ModuleResolutionKind | ts.ModuleResolutionKind;
newLine?: NewLineKind | ts.NewLineKind;
noEmit?: boolean;
noEmitHelpers?: boolean;
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noFallthroughCasesInSwitch?: boolean;
noImplicitAny?: boolean;
noImplicitReturns?: boolean;
noImplicitThis?: boolean;
noUnusedLocals?: boolean;
noUnusedParameters?: boolean;
noImplicitUseStrict?: boolean;
noLib?: boolean;
noResolve?: boolean;
out?: string;
outDir?: string;
outFile?: string;
paths?: MapLike<string[]>;
preserveConstEnums?: boolean;
project?: string;
reactNamespace?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
skipLibCheck?: boolean;
skipDefaultLibCheck?: boolean;
sourceMap?: boolean;
sourceRoot?: string;
strictNullChecks?: boolean;
suppressExcessPropertyErrors?: boolean;
suppressImplicitAnyIndexErrors?: boolean;
target?: ScriptTarget | ts.ScriptTarget;
traceResolution?: boolean;
types?: string[];
/** Paths used to used to compute primary types search locations */
typeRoots?: string[];
[option: string]: CompilerOptionsValue | undefined;
}
namespace JsxEmit {
type None = "None";
type Preserve = "Preserve";
type React = "React";
}
type JsxEmit = JsxEmit.None | JsxEmit.Preserve | JsxEmit.React;
namespace ModuleKind {
type None = "None";
type CommonJS = "CommonJS";
type AMD = "AMD";
type UMD = "UMD";
type System = "System";
type ES6 = "ES6";
type ES2015 = "ES2015";
}
type ModuleKind = ModuleKind.None | ModuleKind.CommonJS | ModuleKind.AMD | ModuleKind.UMD | ModuleKind.System | ModuleKind.ES6 | ModuleKind.ES2015;
namespace ModuleResolutionKind {
type Classic = "Classic";
type Node = "Node";
}
type ModuleResolutionKind = ModuleResolutionKind.Classic | ModuleResolutionKind.Node;
namespace NewLineKind {
type Crlf = "Crlf";
type Lf = "Lf";
}
type NewLineKind = NewLineKind.Crlf | NewLineKind.Lf;
namespace ScriptTarget {
type ES3 = "ES3";
type ES5 = "ES5";
type ES6 = "ES6";
type ES2015 = "ES2015";
}
type ScriptTarget = ScriptTarget.ES3 | ScriptTarget.ES5 | ScriptTarget.ES6 | ScriptTarget.ES2015;
}
declare namespace ts.server.protocol {
@@ -1695,29 +1783,6 @@ declare namespace ts.server.protocol {
position: number;
}
interface EditorSettings {
baseIndentSize?: number;
indentSize?: number;
tabSize?: number;
newLineCharacter?: string;
convertTabsToSpaces?: boolean;
indentStyle?: IndentStyle;
}
enum IndentStyle {
None = 0,
Block = 1,
Smart = 2,
}
enum ScriptKind {
Unknown = 0,
JS = 1,
JSX = 2,
TS = 3,
TSX = 4,
}
interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
@@ -1725,124 +1790,22 @@ declare namespace ts.server.protocol {
[option: string]: string[] | boolean | undefined;
}
interface CompilerOptions {
allowJs?: boolean;
allowSyntheticDefaultImports?: boolean;
allowUnreachableCode?: boolean;
allowUnusedLabels?: boolean;
alwaysStrict?: boolean;
baseUrl?: string;
charset?: string;
declaration?: boolean;
declarationDir?: string;
disableSizeLimit?: boolean;
emitBOM?: boolean;
emitDecoratorMetadata?: boolean;
experimentalDecorators?: boolean;
forceConsistentCasingInFileNames?: boolean;
importHelpers?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
isolatedModules?: boolean;
jsx?: JsxEmit;
lib?: string[];
locale?: string;
mapRoot?: string;
maxNodeModuleJsDepth?: number;
module?: ModuleKind;
moduleResolution?: ModuleResolutionKind;
newLine?: NewLineKind;
noEmit?: boolean;
noEmitHelpers?: boolean;
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noFallthroughCasesInSwitch?: boolean;
noImplicitAny?: boolean;
noImplicitReturns?: boolean;
noImplicitThis?: boolean;
noUnusedLocals?: boolean;
noUnusedParameters?: boolean;
noImplicitUseStrict?: boolean;
noLib?: boolean;
noResolve?: boolean;
out?: string;
outDir?: string;
outFile?: string;
paths?: MapLike<string[]>;
preserveConstEnums?: boolean;
project?: string;
reactNamespace?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
skipLibCheck?: boolean;
skipDefaultLibCheck?: boolean;
sourceMap?: boolean;
sourceRoot?: string;
strictNullChecks?: boolean;
suppressExcessPropertyErrors?: boolean;
suppressImplicitAnyIndexErrors?: boolean;
target?: ScriptTarget;
traceResolution?: boolean;
types?: string[];
/** Paths used to used to compute primary types search locations */
typeRoots?: string[];
[option: string]: CompilerOptionsValue | undefined;
}
enum JsxEmit {
None = 0,
Preserve = 1,
React = 2,
}
enum ModuleKind {
None = 0,
CommonJS = 1,
AMD = 2,
UMD = 3,
System = 4,
ES6 = 5,
ES2015 = 5,
}
enum ModuleResolutionKind {
Classic = 1,
NodeJs = 2,
}
enum NewLineKind {
CarriageReturnLineFeed = 0,
LineFeed = 1,
}
interface MapLike<T> {
[index: string]: T;
}
enum ScriptTarget {
ES3 = 0,
ES5 = 1,
ES6 = 2,
ES2015 = 2,
Latest = 2,
}
type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]>;
interface FormatCodeSettings extends EditorSettings {
insertSpaceAfterCommaDelimiter?: boolean;
insertSpaceAfterSemicolonInForStatements?: boolean;
insertSpaceBeforeAndAfterBinaryOperators?: boolean;
insertSpaceAfterKeywordsInControlFlowStatements?: boolean;
insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean;
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean;
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean;
insertSpaceAfterTypeAssertion?: boolean;
placeOpenBraceOnNewLineForFunctions?: boolean;
placeOpenBraceOnNewLineForControlBlocks?: boolean;
}
}
}
declare namespace ts {
// these types are empty stubs for types from services and should not be used directly
export type ScriptKind = never;
export type IndentStyle = never;
export type JsxEmit = never;
export type ModuleKind = never;
export type ModuleResolutionKind = never;
export type NewLineKind = never;
export type ScriptTarget = never;
}
import protocol = ts.server.protocol;
export = protocol;
export as namespace protocol;
+8486 -7770
View File
File diff suppressed because it is too large Load Diff
+15250 -14407
View File
File diff suppressed because it is too large Load Diff
+8577 -1127
View File
File diff suppressed because one or more lines are too long
+15163 -14382
View File
File diff suppressed because it is too large Load Diff
+323 -213
View File
@@ -163,170 +163,177 @@ declare namespace ts {
DeclareKeyword = 123,
GetKeyword = 124,
IsKeyword = 125,
ModuleKeyword = 126,
NamespaceKeyword = 127,
NeverKeyword = 128,
ReadonlyKeyword = 129,
RequireKeyword = 130,
NumberKeyword = 131,
SetKeyword = 132,
StringKeyword = 133,
SymbolKeyword = 134,
TypeKeyword = 135,
UndefinedKeyword = 136,
FromKeyword = 137,
GlobalKeyword = 138,
OfKeyword = 139,
QualifiedName = 140,
ComputedPropertyName = 141,
TypeParameter = 142,
Parameter = 143,
Decorator = 144,
PropertySignature = 145,
PropertyDeclaration = 146,
MethodSignature = 147,
MethodDeclaration = 148,
Constructor = 149,
GetAccessor = 150,
SetAccessor = 151,
CallSignature = 152,
ConstructSignature = 153,
IndexSignature = 154,
TypePredicate = 155,
TypeReference = 156,
FunctionType = 157,
ConstructorType = 158,
TypeQuery = 159,
TypeLiteral = 160,
ArrayType = 161,
TupleType = 162,
UnionType = 163,
IntersectionType = 164,
ParenthesizedType = 165,
ThisType = 166,
LiteralType = 167,
ObjectBindingPattern = 168,
ArrayBindingPattern = 169,
BindingElement = 170,
ArrayLiteralExpression = 171,
ObjectLiteralExpression = 172,
PropertyAccessExpression = 173,
ElementAccessExpression = 174,
CallExpression = 175,
NewExpression = 176,
TaggedTemplateExpression = 177,
TypeAssertionExpression = 178,
ParenthesizedExpression = 179,
FunctionExpression = 180,
ArrowFunction = 181,
DeleteExpression = 182,
TypeOfExpression = 183,
VoidExpression = 184,
AwaitExpression = 185,
PrefixUnaryExpression = 186,
PostfixUnaryExpression = 187,
BinaryExpression = 188,
ConditionalExpression = 189,
TemplateExpression = 190,
YieldExpression = 191,
SpreadElementExpression = 192,
ClassExpression = 193,
OmittedExpression = 194,
ExpressionWithTypeArguments = 195,
AsExpression = 196,
NonNullExpression = 197,
TemplateSpan = 198,
SemicolonClassElement = 199,
Block = 200,
VariableStatement = 201,
EmptyStatement = 202,
ExpressionStatement = 203,
IfStatement = 204,
DoStatement = 205,
WhileStatement = 206,
ForStatement = 207,
ForInStatement = 208,
ForOfStatement = 209,
ContinueStatement = 210,
BreakStatement = 211,
ReturnStatement = 212,
WithStatement = 213,
SwitchStatement = 214,
LabeledStatement = 215,
ThrowStatement = 216,
TryStatement = 217,
DebuggerStatement = 218,
VariableDeclaration = 219,
VariableDeclarationList = 220,
FunctionDeclaration = 221,
ClassDeclaration = 222,
InterfaceDeclaration = 223,
TypeAliasDeclaration = 224,
EnumDeclaration = 225,
ModuleDeclaration = 226,
ModuleBlock = 227,
CaseBlock = 228,
NamespaceExportDeclaration = 229,
ImportEqualsDeclaration = 230,
ImportDeclaration = 231,
ImportClause = 232,
NamespaceImport = 233,
NamedImports = 234,
ImportSpecifier = 235,
ExportAssignment = 236,
ExportDeclaration = 237,
NamedExports = 238,
ExportSpecifier = 239,
MissingDeclaration = 240,
ExternalModuleReference = 241,
JsxElement = 242,
JsxSelfClosingElement = 243,
JsxOpeningElement = 244,
JsxClosingElement = 245,
JsxAttribute = 246,
JsxSpreadAttribute = 247,
JsxExpression = 248,
CaseClause = 249,
DefaultClause = 250,
HeritageClause = 251,
CatchClause = 252,
PropertyAssignment = 253,
ShorthandPropertyAssignment = 254,
EnumMember = 255,
SourceFile = 256,
JSDocTypeExpression = 257,
JSDocAllType = 258,
JSDocUnknownType = 259,
JSDocArrayType = 260,
JSDocUnionType = 261,
JSDocTupleType = 262,
JSDocNullableType = 263,
JSDocNonNullableType = 264,
JSDocRecordType = 265,
JSDocRecordMember = 266,
JSDocTypeReference = 267,
JSDocOptionalType = 268,
JSDocFunctionType = 269,
JSDocVariadicType = 270,
JSDocConstructorType = 271,
JSDocThisType = 272,
JSDocComment = 273,
JSDocTag = 274,
JSDocParameterTag = 275,
JSDocReturnTag = 276,
JSDocTypeTag = 277,
JSDocTemplateTag = 278,
JSDocTypedefTag = 279,
JSDocPropertyTag = 280,
JSDocTypeLiteral = 281,
JSDocLiteralType = 282,
JSDocNullKeyword = 283,
JSDocUndefinedKeyword = 284,
JSDocNeverKeyword = 285,
SyntaxList = 286,
NotEmittedStatement = 287,
PartiallyEmittedExpression = 288,
Count = 289,
KeyOfKeyword = 126,
ModuleKeyword = 127,
NamespaceKeyword = 128,
NeverKeyword = 129,
ReadonlyKeyword = 130,
RequireKeyword = 131,
NumberKeyword = 132,
SetKeyword = 133,
StringKeyword = 134,
SymbolKeyword = 135,
TypeKeyword = 136,
UndefinedKeyword = 137,
FromKeyword = 138,
GlobalKeyword = 139,
OfKeyword = 140,
QualifiedName = 141,
ComputedPropertyName = 142,
TypeParameter = 143,
Parameter = 144,
Decorator = 145,
PropertySignature = 146,
PropertyDeclaration = 147,
MethodSignature = 148,
MethodDeclaration = 149,
Constructor = 150,
GetAccessor = 151,
SetAccessor = 152,
CallSignature = 153,
ConstructSignature = 154,
IndexSignature = 155,
TypePredicate = 156,
TypeReference = 157,
FunctionType = 158,
ConstructorType = 159,
TypeQuery = 160,
TypeLiteral = 161,
ArrayType = 162,
TupleType = 163,
UnionType = 164,
IntersectionType = 165,
ParenthesizedType = 166,
ThisType = 167,
TypeOperator = 168,
IndexedAccessType = 169,
MappedType = 170,
LiteralType = 171,
ObjectBindingPattern = 172,
ArrayBindingPattern = 173,
BindingElement = 174,
ArrayLiteralExpression = 175,
ObjectLiteralExpression = 176,
PropertyAccessExpression = 177,
ElementAccessExpression = 178,
CallExpression = 179,
NewExpression = 180,
TaggedTemplateExpression = 181,
TypeAssertionExpression = 182,
ParenthesizedExpression = 183,
FunctionExpression = 184,
ArrowFunction = 185,
DeleteExpression = 186,
TypeOfExpression = 187,
VoidExpression = 188,
AwaitExpression = 189,
PrefixUnaryExpression = 190,
PostfixUnaryExpression = 191,
BinaryExpression = 192,
ConditionalExpression = 193,
TemplateExpression = 194,
YieldExpression = 195,
SpreadElement = 196,
ClassExpression = 197,
OmittedExpression = 198,
ExpressionWithTypeArguments = 199,
AsExpression = 200,
NonNullExpression = 201,
TemplateSpan = 202,
SemicolonClassElement = 203,
Block = 204,
VariableStatement = 205,
EmptyStatement = 206,
ExpressionStatement = 207,
IfStatement = 208,
DoStatement = 209,
WhileStatement = 210,
ForStatement = 211,
ForInStatement = 212,
ForOfStatement = 213,
ContinueStatement = 214,
BreakStatement = 215,
ReturnStatement = 216,
WithStatement = 217,
SwitchStatement = 218,
LabeledStatement = 219,
ThrowStatement = 220,
TryStatement = 221,
DebuggerStatement = 222,
VariableDeclaration = 223,
VariableDeclarationList = 224,
FunctionDeclaration = 225,
ClassDeclaration = 226,
InterfaceDeclaration = 227,
TypeAliasDeclaration = 228,
EnumDeclaration = 229,
ModuleDeclaration = 230,
ModuleBlock = 231,
CaseBlock = 232,
NamespaceExportDeclaration = 233,
ImportEqualsDeclaration = 234,
ImportDeclaration = 235,
ImportClause = 236,
NamespaceImport = 237,
NamedImports = 238,
ImportSpecifier = 239,
ExportAssignment = 240,
ExportDeclaration = 241,
NamedExports = 242,
ExportSpecifier = 243,
MissingDeclaration = 244,
ExternalModuleReference = 245,
JsxElement = 246,
JsxSelfClosingElement = 247,
JsxOpeningElement = 248,
JsxClosingElement = 249,
JsxAttribute = 250,
JsxSpreadAttribute = 251,
JsxExpression = 252,
CaseClause = 253,
DefaultClause = 254,
HeritageClause = 255,
CatchClause = 256,
PropertyAssignment = 257,
ShorthandPropertyAssignment = 258,
SpreadAssignment = 259,
EnumMember = 260,
SourceFile = 261,
JSDocTypeExpression = 262,
JSDocAllType = 263,
JSDocUnknownType = 264,
JSDocArrayType = 265,
JSDocUnionType = 266,
JSDocTupleType = 267,
JSDocNullableType = 268,
JSDocNonNullableType = 269,
JSDocRecordType = 270,
JSDocRecordMember = 271,
JSDocTypeReference = 272,
JSDocOptionalType = 273,
JSDocFunctionType = 274,
JSDocVariadicType = 275,
JSDocConstructorType = 276,
JSDocThisType = 277,
JSDocComment = 278,
JSDocTag = 279,
JSDocParameterTag = 280,
JSDocReturnTag = 281,
JSDocTypeTag = 282,
JSDocTemplateTag = 283,
JSDocTypedefTag = 284,
JSDocPropertyTag = 285,
JSDocTypeLiteral = 286,
JSDocLiteralType = 287,
JSDocNullKeyword = 288,
JSDocUndefinedKeyword = 289,
JSDocNeverKeyword = 290,
SyntaxList = 291,
NotEmittedStatement = 292,
PartiallyEmittedExpression = 293,
MergeDeclarationMarker = 294,
EndOfDeclarationMarker = 295,
Count = 296,
FirstAssignment = 57,
LastAssignment = 69,
FirstCompoundAssignment = 58,
@@ -334,15 +341,15 @@ declare namespace ts {
FirstReservedWord = 71,
LastReservedWord = 106,
FirstKeyword = 71,
LastKeyword = 139,
LastKeyword = 140,
FirstFutureReservedWord = 107,
LastFutureReservedWord = 115,
FirstTypeNode = 155,
LastTypeNode = 167,
FirstTypeNode = 156,
LastTypeNode = 171,
FirstPunctuation = 16,
LastPunctuation = 69,
FirstToken = 0,
LastToken = 139,
LastToken = 140,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
@@ -351,11 +358,11 @@ declare namespace ts {
LastTemplateToken = 15,
FirstBinaryOperator = 26,
LastBinaryOperator = 69,
FirstNode = 140,
FirstJSDocNode = 257,
LastJSDocNode = 282,
FirstJSDocTagNode = 273,
LastJSDocTagNode = 285,
FirstNode = 141,
FirstJSDocNode = 262,
LastJSDocNode = 287,
FirstJSDocTagNode = 278,
LastJSDocTagNode = 290,
}
enum NodeFlags {
None = 0,
@@ -373,21 +380,22 @@ declare namespace ts {
HasDecorators = 2048,
HasParamDecorators = 4096,
HasAsyncFunctions = 8192,
HasJsxSpreadAttributes = 16384,
DisallowInContext = 32768,
YieldContext = 65536,
DecoratorContext = 131072,
AwaitContext = 262144,
ThisNodeHasError = 524288,
JavaScriptFile = 1048576,
ThisNodeOrAnySubNodesHasError = 2097152,
HasAggregatedChildData = 4194304,
HasSpreadAttribute = 16384,
HasRestAttribute = 32768,
DisallowInContext = 65536,
YieldContext = 131072,
DecoratorContext = 262144,
AwaitContext = 524288,
ThisNodeHasError = 1048576,
JavaScriptFile = 2097152,
ThisNodeOrAnySubNodesHasError = 4194304,
HasAggregatedChildData = 8388608,
BlockScoped = 3,
ReachabilityCheckFlags = 384,
EmitHelperFlags = 31744,
ReachabilityAndEmitFlags = 32128,
ContextFlags = 1540096,
TypeExcludesFlags = 327680,
EmitHelperFlags = 64512,
ReachabilityAndEmitFlags = 64896,
ContextFlags = 3080192,
TypeExcludesFlags = 655360,
}
enum ModifierFlags {
None = 0,
@@ -407,6 +415,7 @@ declare namespace ts {
ParameterPropertyModifier = 92,
NonPublicAccessibilityModifier = 24,
TypeScriptModifier = 2270,
ExportDefault = 513,
}
enum JsxFlags {
None = 0,
@@ -437,12 +446,14 @@ declare namespace ts {
type EqualsGreaterThanToken = Token<SyntaxKind.EqualsGreaterThanToken>;
type EndOfFileToken = Token<SyntaxKind.EndOfFileToken>;
type AtToken = Token<SyntaxKind.AtToken>;
type ReadonlyToken = Token<SyntaxKind.ReadonlyKeyword>;
type Modifier = Token<SyntaxKind.AbstractKeyword> | Token<SyntaxKind.AsyncKeyword> | Token<SyntaxKind.ConstKeyword> | Token<SyntaxKind.DeclareKeyword> | Token<SyntaxKind.DefaultKeyword> | Token<SyntaxKind.ExportKeyword> | Token<SyntaxKind.PublicKeyword> | Token<SyntaxKind.PrivateKeyword> | Token<SyntaxKind.ProtectedKeyword> | Token<SyntaxKind.ReadonlyKeyword> | Token<SyntaxKind.StaticKeyword>;
type ModifiersArray = NodeArray<Modifier>;
interface Identifier extends PrimaryExpression {
kind: SyntaxKind.Identifier;
text: string;
originalKeywordKind?: SyntaxKind;
isInJSDocNamespace?: boolean;
}
interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
@@ -533,7 +544,7 @@ declare namespace ts {
_objectLiteralBrandBrand: any;
name?: PropertyName;
}
type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration;
type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration | SpreadAssignment;
interface PropertyAssignment extends ObjectLiteralElement {
kind: SyntaxKind.PropertyAssignment;
name: PropertyName;
@@ -547,6 +558,10 @@ declare namespace ts {
equalsToken?: Token<SyntaxKind.EqualsToken>;
objectAssignmentInitializer?: Expression;
}
interface SpreadAssignment extends ObjectLiteralElement {
kind: SyntaxKind.SpreadAssignment;
expression: Expression;
}
interface VariableLikeDeclaration extends Declaration {
propertyName?: PropertyName;
dotDotDotToken?: DotDotDotToken;
@@ -677,6 +692,23 @@ declare namespace ts {
kind: SyntaxKind.ParenthesizedType;
type: TypeNode;
}
interface TypeOperatorNode extends TypeNode {
kind: SyntaxKind.TypeOperator;
operator: SyntaxKind.KeyOfKeyword;
type: TypeNode;
}
interface IndexedAccessTypeNode extends TypeNode {
kind: SyntaxKind.IndexedAccessType;
objectType: TypeNode;
indexType: TypeNode;
}
interface MappedTypeNode extends TypeNode, Declaration {
kind: SyntaxKind.MappedType;
readonlyToken?: ReadonlyToken;
typeParameter: TypeParameterDeclaration;
questionToken?: QuestionToken;
type?: TypeNode;
}
interface LiteralTypeNode extends TypeNode {
kind: SyntaxKind.LiteralType;
literal: Expression;
@@ -709,9 +741,6 @@ declare namespace ts {
operand: LeftHandSideExpression;
operator: PostfixUnaryOperator;
}
interface PostfixExpression extends UnaryExpression {
_postfixExpressionBrand: any;
}
interface LeftHandSideExpression extends IncrementExpression {
_leftHandSideExpressionBrand: any;
}
@@ -780,6 +809,17 @@ declare namespace ts {
operatorToken: BinaryOperatorToken;
right: Expression;
}
interface AssignmentExpression extends BinaryExpression {
left: LeftHandSideExpression;
operatorToken: Token<SyntaxKind.EqualsToken>;
}
interface ObjectDestructuringAssignment extends AssignmentExpression {
left: ObjectLiteralExpression;
}
interface ArrayDestructuringAssignment extends AssignmentExpression {
left: ArrayLiteralExpression;
}
type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment;
interface ConditionalExpression extends Expression {
kind: SyntaxKind.ConditionalExpression;
condition: Expression;
@@ -846,8 +886,8 @@ declare namespace ts {
kind: SyntaxKind.ArrayLiteralExpression;
elements: NodeArray<Expression>;
}
interface SpreadElementExpression extends Expression {
kind: SyntaxKind.SpreadElementExpression;
interface SpreadElement extends Expression {
kind: SyntaxKind.SpreadElement;
expression: Expression;
}
/**
@@ -1141,12 +1181,16 @@ declare namespace ts {
interface ModuleDeclaration extends DeclarationStatement {
kind: SyntaxKind.ModuleDeclaration;
name: Identifier | LiteralExpression;
body?: ModuleBlock | NamespaceDeclaration;
body?: ModuleBlock | NamespaceDeclaration | JSDocNamespaceDeclaration | Identifier;
}
interface NamespaceDeclaration extends ModuleDeclaration {
name: Identifier;
body: ModuleBlock | NamespaceDeclaration;
}
interface JSDocNamespaceDeclaration extends ModuleDeclaration {
name: Identifier;
body: JSDocNamespaceDeclaration | Identifier;
}
interface ModuleBlock extends Node, Statement {
kind: SyntaxKind.ModuleBlock;
statements: NodeArray<Statement>;
@@ -1318,6 +1362,7 @@ declare namespace ts {
}
interface JSDocTypedefTag extends JSDocTag, Declaration {
kind: SyntaxKind.JSDocTypedefTag;
fullName?: JSDocNamespaceDeclaration | Identifier;
name?: Identifier;
typeExpression?: JSDocTypeExpression;
jsDocTypeLiteral?: JSDocTypeLiteral;
@@ -1708,14 +1753,11 @@ declare namespace ts {
Null = 4096,
Never = 8192,
TypeParameter = 16384,
Class = 32768,
Interface = 65536,
Reference = 131072,
Tuple = 262144,
Union = 524288,
Intersection = 1048576,
Anonymous = 2097152,
Instantiated = 4194304,
Object = 32768,
Union = 65536,
Intersection = 131072,
Index = 262144,
IndexedAccess = 524288,
Literal = 480,
StringOrNumberLiteral = 96,
PossiblyFalsy = 7406,
@@ -1723,12 +1765,11 @@ declare namespace ts {
NumberLike = 340,
BooleanLike = 136,
EnumLike = 272,
ObjectType = 2588672,
UnionOrIntersection = 1572864,
StructuredType = 4161536,
StructuredOrTypeParameter = 4177920,
Narrowable = 4178943,
NotUnionOrUnit = 2589185,
UnionOrIntersection = 196608,
StructuredType = 229376,
StructuredOrTypeParameter = 507904,
Narrowable = 1033215,
NotUnionOrUnit = 33281,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
interface Type {
@@ -1749,8 +1790,21 @@ declare namespace ts {
interface EnumLiteralType extends LiteralType {
baseType: EnumType & UnionType;
}
enum ObjectFlags {
Class = 1,
Interface = 2,
Reference = 4,
Tuple = 8,
Anonymous = 16,
Mapped = 32,
Instantiated = 64,
ObjectLiteral = 128,
EvolvingArray = 256,
ObjectLiteralPatternWithComputedProperties = 512,
ClassOrInterface = 3,
}
interface ObjectType extends Type {
isObjectLiteralPatternWithComputedProperties?: boolean;
objectFlags: ObjectFlags;
}
interface InterfaceType extends ObjectType {
typeParameters: TypeParameter[];
@@ -1778,9 +1832,21 @@ declare namespace ts {
}
interface IntersectionType extends UnionOrIntersectionType {
}
type StructuredType = ObjectType | UnionType | IntersectionType;
interface EvolvingArrayType extends ObjectType {
elementType: Type;
finalArrayType?: Type;
}
interface TypeParameter extends Type {
constraint: Type;
}
interface IndexType extends Type {
type: TypeParameter;
}
interface IndexedAccessType extends Type {
objectType: Type;
indexType: TypeParameter;
}
enum SignatureKind {
Call = 0,
Construct = 1,
@@ -1882,6 +1948,7 @@ declare namespace ts {
preserveConstEnums?: boolean;
project?: string;
reactNamespace?: string;
jsxFactory?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -1912,6 +1979,7 @@ declare namespace ts {
packageNameToTypingLocation: Map<string>;
typingOptions: TypingOptions;
compilerOptions: CompilerOptions;
unresolvedImports: ReadonlyArray<string>;
}
enum ModuleKind {
None = 0,
@@ -1947,12 +2015,14 @@ declare namespace ts {
ES2015 = 2,
ES2016 = 3,
ES2017 = 4,
Latest = 4,
ESNext = 5,
Latest = 5,
}
enum LanguageVariant {
Standard = 0,
JSX = 1,
}
/** Either a parsed command line or a parsed tsconfig.json */
interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
@@ -1979,12 +2049,45 @@ declare namespace ts {
getCurrentDirectory?(): string;
getDirectories?(path: string): string[];
}
/**
* Represents the result of module resolution.
* Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off.
* The Program will then filter results based on these flags.
*
* Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred.
*/
interface ResolvedModule {
/** Path of the file the module was resolved to. */
resolvedFileName: string;
/**
* Denotes if 'resolvedFileName' is isExternalLibraryImport and thus should be a proper external module:
* - be a .d.ts file
* - use top level imports\exports
* - don't use tripleslash references
*/
isExternalLibraryImport?: boolean;
}
/**
* ResolvedModule with an explicitly provided `extension` property.
* Prefer this over `ResolvedModule`.
*/
interface ResolvedModuleFull extends ResolvedModule {
/**
* Extension of resolvedFileName. This must match what's at the end of resolvedFileName.
* This is optional for backwards-compatibility, but will be added if not provided.
*/
extension: Extension;
}
enum Extension {
Ts = 0,
Tsx = 1,
Dts = 2,
Js = 3,
Jsx = 4,
LastTypeScriptExtension = 2,
}
interface ResolvedModuleWithFailedLookupLocations {
resolvedModule: ResolvedModule;
resolvedModule: ResolvedModuleFull | undefined;
failedLookupLocations: string[];
}
interface ResolvedTypeReferenceDirective {
@@ -2042,7 +2145,11 @@ declare namespace ts {
readFile(path: string, encoding?: string): string;
getFileSize?(path: string): number;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
/**
* @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that
* use native OS file watching
*/
watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
@@ -2057,6 +2164,8 @@ declare namespace ts {
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any;
clearTimeout?(timeoutId: any): void;
}
interface FileWatcher {
close(): void;
@@ -2159,6 +2268,7 @@ declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName;
function isExternalModule(file: SourceFile): boolean;
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
@@ -2172,7 +2282,7 @@ declare namespace ts {
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
* is assumed to be the same as root directory of the project.
*/
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
/**
* Given a set of options, returns the set of type directive names
* that should be included for this program automatically.
@@ -2188,7 +2298,7 @@ declare namespace ts {
}
declare namespace ts {
/** The version of the TypeScript compiler release */
const version = "2.1.0";
const version = "2.2.0";
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
+11985 -9262
View File
File diff suppressed because it is too large Load Diff
+323 -213
View File
@@ -163,170 +163,177 @@ declare namespace ts {
DeclareKeyword = 123,
GetKeyword = 124,
IsKeyword = 125,
ModuleKeyword = 126,
NamespaceKeyword = 127,
NeverKeyword = 128,
ReadonlyKeyword = 129,
RequireKeyword = 130,
NumberKeyword = 131,
SetKeyword = 132,
StringKeyword = 133,
SymbolKeyword = 134,
TypeKeyword = 135,
UndefinedKeyword = 136,
FromKeyword = 137,
GlobalKeyword = 138,
OfKeyword = 139,
QualifiedName = 140,
ComputedPropertyName = 141,
TypeParameter = 142,
Parameter = 143,
Decorator = 144,
PropertySignature = 145,
PropertyDeclaration = 146,
MethodSignature = 147,
MethodDeclaration = 148,
Constructor = 149,
GetAccessor = 150,
SetAccessor = 151,
CallSignature = 152,
ConstructSignature = 153,
IndexSignature = 154,
TypePredicate = 155,
TypeReference = 156,
FunctionType = 157,
ConstructorType = 158,
TypeQuery = 159,
TypeLiteral = 160,
ArrayType = 161,
TupleType = 162,
UnionType = 163,
IntersectionType = 164,
ParenthesizedType = 165,
ThisType = 166,
LiteralType = 167,
ObjectBindingPattern = 168,
ArrayBindingPattern = 169,
BindingElement = 170,
ArrayLiteralExpression = 171,
ObjectLiteralExpression = 172,
PropertyAccessExpression = 173,
ElementAccessExpression = 174,
CallExpression = 175,
NewExpression = 176,
TaggedTemplateExpression = 177,
TypeAssertionExpression = 178,
ParenthesizedExpression = 179,
FunctionExpression = 180,
ArrowFunction = 181,
DeleteExpression = 182,
TypeOfExpression = 183,
VoidExpression = 184,
AwaitExpression = 185,
PrefixUnaryExpression = 186,
PostfixUnaryExpression = 187,
BinaryExpression = 188,
ConditionalExpression = 189,
TemplateExpression = 190,
YieldExpression = 191,
SpreadElementExpression = 192,
ClassExpression = 193,
OmittedExpression = 194,
ExpressionWithTypeArguments = 195,
AsExpression = 196,
NonNullExpression = 197,
TemplateSpan = 198,
SemicolonClassElement = 199,
Block = 200,
VariableStatement = 201,
EmptyStatement = 202,
ExpressionStatement = 203,
IfStatement = 204,
DoStatement = 205,
WhileStatement = 206,
ForStatement = 207,
ForInStatement = 208,
ForOfStatement = 209,
ContinueStatement = 210,
BreakStatement = 211,
ReturnStatement = 212,
WithStatement = 213,
SwitchStatement = 214,
LabeledStatement = 215,
ThrowStatement = 216,
TryStatement = 217,
DebuggerStatement = 218,
VariableDeclaration = 219,
VariableDeclarationList = 220,
FunctionDeclaration = 221,
ClassDeclaration = 222,
InterfaceDeclaration = 223,
TypeAliasDeclaration = 224,
EnumDeclaration = 225,
ModuleDeclaration = 226,
ModuleBlock = 227,
CaseBlock = 228,
NamespaceExportDeclaration = 229,
ImportEqualsDeclaration = 230,
ImportDeclaration = 231,
ImportClause = 232,
NamespaceImport = 233,
NamedImports = 234,
ImportSpecifier = 235,
ExportAssignment = 236,
ExportDeclaration = 237,
NamedExports = 238,
ExportSpecifier = 239,
MissingDeclaration = 240,
ExternalModuleReference = 241,
JsxElement = 242,
JsxSelfClosingElement = 243,
JsxOpeningElement = 244,
JsxClosingElement = 245,
JsxAttribute = 246,
JsxSpreadAttribute = 247,
JsxExpression = 248,
CaseClause = 249,
DefaultClause = 250,
HeritageClause = 251,
CatchClause = 252,
PropertyAssignment = 253,
ShorthandPropertyAssignment = 254,
EnumMember = 255,
SourceFile = 256,
JSDocTypeExpression = 257,
JSDocAllType = 258,
JSDocUnknownType = 259,
JSDocArrayType = 260,
JSDocUnionType = 261,
JSDocTupleType = 262,
JSDocNullableType = 263,
JSDocNonNullableType = 264,
JSDocRecordType = 265,
JSDocRecordMember = 266,
JSDocTypeReference = 267,
JSDocOptionalType = 268,
JSDocFunctionType = 269,
JSDocVariadicType = 270,
JSDocConstructorType = 271,
JSDocThisType = 272,
JSDocComment = 273,
JSDocTag = 274,
JSDocParameterTag = 275,
JSDocReturnTag = 276,
JSDocTypeTag = 277,
JSDocTemplateTag = 278,
JSDocTypedefTag = 279,
JSDocPropertyTag = 280,
JSDocTypeLiteral = 281,
JSDocLiteralType = 282,
JSDocNullKeyword = 283,
JSDocUndefinedKeyword = 284,
JSDocNeverKeyword = 285,
SyntaxList = 286,
NotEmittedStatement = 287,
PartiallyEmittedExpression = 288,
Count = 289,
KeyOfKeyword = 126,
ModuleKeyword = 127,
NamespaceKeyword = 128,
NeverKeyword = 129,
ReadonlyKeyword = 130,
RequireKeyword = 131,
NumberKeyword = 132,
SetKeyword = 133,
StringKeyword = 134,
SymbolKeyword = 135,
TypeKeyword = 136,
UndefinedKeyword = 137,
FromKeyword = 138,
GlobalKeyword = 139,
OfKeyword = 140,
QualifiedName = 141,
ComputedPropertyName = 142,
TypeParameter = 143,
Parameter = 144,
Decorator = 145,
PropertySignature = 146,
PropertyDeclaration = 147,
MethodSignature = 148,
MethodDeclaration = 149,
Constructor = 150,
GetAccessor = 151,
SetAccessor = 152,
CallSignature = 153,
ConstructSignature = 154,
IndexSignature = 155,
TypePredicate = 156,
TypeReference = 157,
FunctionType = 158,
ConstructorType = 159,
TypeQuery = 160,
TypeLiteral = 161,
ArrayType = 162,
TupleType = 163,
UnionType = 164,
IntersectionType = 165,
ParenthesizedType = 166,
ThisType = 167,
TypeOperator = 168,
IndexedAccessType = 169,
MappedType = 170,
LiteralType = 171,
ObjectBindingPattern = 172,
ArrayBindingPattern = 173,
BindingElement = 174,
ArrayLiteralExpression = 175,
ObjectLiteralExpression = 176,
PropertyAccessExpression = 177,
ElementAccessExpression = 178,
CallExpression = 179,
NewExpression = 180,
TaggedTemplateExpression = 181,
TypeAssertionExpression = 182,
ParenthesizedExpression = 183,
FunctionExpression = 184,
ArrowFunction = 185,
DeleteExpression = 186,
TypeOfExpression = 187,
VoidExpression = 188,
AwaitExpression = 189,
PrefixUnaryExpression = 190,
PostfixUnaryExpression = 191,
BinaryExpression = 192,
ConditionalExpression = 193,
TemplateExpression = 194,
YieldExpression = 195,
SpreadElement = 196,
ClassExpression = 197,
OmittedExpression = 198,
ExpressionWithTypeArguments = 199,
AsExpression = 200,
NonNullExpression = 201,
TemplateSpan = 202,
SemicolonClassElement = 203,
Block = 204,
VariableStatement = 205,
EmptyStatement = 206,
ExpressionStatement = 207,
IfStatement = 208,
DoStatement = 209,
WhileStatement = 210,
ForStatement = 211,
ForInStatement = 212,
ForOfStatement = 213,
ContinueStatement = 214,
BreakStatement = 215,
ReturnStatement = 216,
WithStatement = 217,
SwitchStatement = 218,
LabeledStatement = 219,
ThrowStatement = 220,
TryStatement = 221,
DebuggerStatement = 222,
VariableDeclaration = 223,
VariableDeclarationList = 224,
FunctionDeclaration = 225,
ClassDeclaration = 226,
InterfaceDeclaration = 227,
TypeAliasDeclaration = 228,
EnumDeclaration = 229,
ModuleDeclaration = 230,
ModuleBlock = 231,
CaseBlock = 232,
NamespaceExportDeclaration = 233,
ImportEqualsDeclaration = 234,
ImportDeclaration = 235,
ImportClause = 236,
NamespaceImport = 237,
NamedImports = 238,
ImportSpecifier = 239,
ExportAssignment = 240,
ExportDeclaration = 241,
NamedExports = 242,
ExportSpecifier = 243,
MissingDeclaration = 244,
ExternalModuleReference = 245,
JsxElement = 246,
JsxSelfClosingElement = 247,
JsxOpeningElement = 248,
JsxClosingElement = 249,
JsxAttribute = 250,
JsxSpreadAttribute = 251,
JsxExpression = 252,
CaseClause = 253,
DefaultClause = 254,
HeritageClause = 255,
CatchClause = 256,
PropertyAssignment = 257,
ShorthandPropertyAssignment = 258,
SpreadAssignment = 259,
EnumMember = 260,
SourceFile = 261,
JSDocTypeExpression = 262,
JSDocAllType = 263,
JSDocUnknownType = 264,
JSDocArrayType = 265,
JSDocUnionType = 266,
JSDocTupleType = 267,
JSDocNullableType = 268,
JSDocNonNullableType = 269,
JSDocRecordType = 270,
JSDocRecordMember = 271,
JSDocTypeReference = 272,
JSDocOptionalType = 273,
JSDocFunctionType = 274,
JSDocVariadicType = 275,
JSDocConstructorType = 276,
JSDocThisType = 277,
JSDocComment = 278,
JSDocTag = 279,
JSDocParameterTag = 280,
JSDocReturnTag = 281,
JSDocTypeTag = 282,
JSDocTemplateTag = 283,
JSDocTypedefTag = 284,
JSDocPropertyTag = 285,
JSDocTypeLiteral = 286,
JSDocLiteralType = 287,
JSDocNullKeyword = 288,
JSDocUndefinedKeyword = 289,
JSDocNeverKeyword = 290,
SyntaxList = 291,
NotEmittedStatement = 292,
PartiallyEmittedExpression = 293,
MergeDeclarationMarker = 294,
EndOfDeclarationMarker = 295,
Count = 296,
FirstAssignment = 57,
LastAssignment = 69,
FirstCompoundAssignment = 58,
@@ -334,15 +341,15 @@ declare namespace ts {
FirstReservedWord = 71,
LastReservedWord = 106,
FirstKeyword = 71,
LastKeyword = 139,
LastKeyword = 140,
FirstFutureReservedWord = 107,
LastFutureReservedWord = 115,
FirstTypeNode = 155,
LastTypeNode = 167,
FirstTypeNode = 156,
LastTypeNode = 171,
FirstPunctuation = 16,
LastPunctuation = 69,
FirstToken = 0,
LastToken = 139,
LastToken = 140,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
@@ -351,11 +358,11 @@ declare namespace ts {
LastTemplateToken = 15,
FirstBinaryOperator = 26,
LastBinaryOperator = 69,
FirstNode = 140,
FirstJSDocNode = 257,
LastJSDocNode = 282,
FirstJSDocTagNode = 273,
LastJSDocTagNode = 285,
FirstNode = 141,
FirstJSDocNode = 262,
LastJSDocNode = 287,
FirstJSDocTagNode = 278,
LastJSDocTagNode = 290,
}
enum NodeFlags {
None = 0,
@@ -373,21 +380,22 @@ declare namespace ts {
HasDecorators = 2048,
HasParamDecorators = 4096,
HasAsyncFunctions = 8192,
HasJsxSpreadAttributes = 16384,
DisallowInContext = 32768,
YieldContext = 65536,
DecoratorContext = 131072,
AwaitContext = 262144,
ThisNodeHasError = 524288,
JavaScriptFile = 1048576,
ThisNodeOrAnySubNodesHasError = 2097152,
HasAggregatedChildData = 4194304,
HasSpreadAttribute = 16384,
HasRestAttribute = 32768,
DisallowInContext = 65536,
YieldContext = 131072,
DecoratorContext = 262144,
AwaitContext = 524288,
ThisNodeHasError = 1048576,
JavaScriptFile = 2097152,
ThisNodeOrAnySubNodesHasError = 4194304,
HasAggregatedChildData = 8388608,
BlockScoped = 3,
ReachabilityCheckFlags = 384,
EmitHelperFlags = 31744,
ReachabilityAndEmitFlags = 32128,
ContextFlags = 1540096,
TypeExcludesFlags = 327680,
EmitHelperFlags = 64512,
ReachabilityAndEmitFlags = 64896,
ContextFlags = 3080192,
TypeExcludesFlags = 655360,
}
enum ModifierFlags {
None = 0,
@@ -407,6 +415,7 @@ declare namespace ts {
ParameterPropertyModifier = 92,
NonPublicAccessibilityModifier = 24,
TypeScriptModifier = 2270,
ExportDefault = 513,
}
enum JsxFlags {
None = 0,
@@ -437,12 +446,14 @@ declare namespace ts {
type EqualsGreaterThanToken = Token<SyntaxKind.EqualsGreaterThanToken>;
type EndOfFileToken = Token<SyntaxKind.EndOfFileToken>;
type AtToken = Token<SyntaxKind.AtToken>;
type ReadonlyToken = Token<SyntaxKind.ReadonlyKeyword>;
type Modifier = Token<SyntaxKind.AbstractKeyword> | Token<SyntaxKind.AsyncKeyword> | Token<SyntaxKind.ConstKeyword> | Token<SyntaxKind.DeclareKeyword> | Token<SyntaxKind.DefaultKeyword> | Token<SyntaxKind.ExportKeyword> | Token<SyntaxKind.PublicKeyword> | Token<SyntaxKind.PrivateKeyword> | Token<SyntaxKind.ProtectedKeyword> | Token<SyntaxKind.ReadonlyKeyword> | Token<SyntaxKind.StaticKeyword>;
type ModifiersArray = NodeArray<Modifier>;
interface Identifier extends PrimaryExpression {
kind: SyntaxKind.Identifier;
text: string;
originalKeywordKind?: SyntaxKind;
isInJSDocNamespace?: boolean;
}
interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
@@ -533,7 +544,7 @@ declare namespace ts {
_objectLiteralBrandBrand: any;
name?: PropertyName;
}
type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration;
type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration | SpreadAssignment;
interface PropertyAssignment extends ObjectLiteralElement {
kind: SyntaxKind.PropertyAssignment;
name: PropertyName;
@@ -547,6 +558,10 @@ declare namespace ts {
equalsToken?: Token<SyntaxKind.EqualsToken>;
objectAssignmentInitializer?: Expression;
}
interface SpreadAssignment extends ObjectLiteralElement {
kind: SyntaxKind.SpreadAssignment;
expression: Expression;
}
interface VariableLikeDeclaration extends Declaration {
propertyName?: PropertyName;
dotDotDotToken?: DotDotDotToken;
@@ -677,6 +692,23 @@ declare namespace ts {
kind: SyntaxKind.ParenthesizedType;
type: TypeNode;
}
interface TypeOperatorNode extends TypeNode {
kind: SyntaxKind.TypeOperator;
operator: SyntaxKind.KeyOfKeyword;
type: TypeNode;
}
interface IndexedAccessTypeNode extends TypeNode {
kind: SyntaxKind.IndexedAccessType;
objectType: TypeNode;
indexType: TypeNode;
}
interface MappedTypeNode extends TypeNode, Declaration {
kind: SyntaxKind.MappedType;
readonlyToken?: ReadonlyToken;
typeParameter: TypeParameterDeclaration;
questionToken?: QuestionToken;
type?: TypeNode;
}
interface LiteralTypeNode extends TypeNode {
kind: SyntaxKind.LiteralType;
literal: Expression;
@@ -709,9 +741,6 @@ declare namespace ts {
operand: LeftHandSideExpression;
operator: PostfixUnaryOperator;
}
interface PostfixExpression extends UnaryExpression {
_postfixExpressionBrand: any;
}
interface LeftHandSideExpression extends IncrementExpression {
_leftHandSideExpressionBrand: any;
}
@@ -780,6 +809,17 @@ declare namespace ts {
operatorToken: BinaryOperatorToken;
right: Expression;
}
interface AssignmentExpression extends BinaryExpression {
left: LeftHandSideExpression;
operatorToken: Token<SyntaxKind.EqualsToken>;
}
interface ObjectDestructuringAssignment extends AssignmentExpression {
left: ObjectLiteralExpression;
}
interface ArrayDestructuringAssignment extends AssignmentExpression {
left: ArrayLiteralExpression;
}
type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment;
interface ConditionalExpression extends Expression {
kind: SyntaxKind.ConditionalExpression;
condition: Expression;
@@ -846,8 +886,8 @@ declare namespace ts {
kind: SyntaxKind.ArrayLiteralExpression;
elements: NodeArray<Expression>;
}
interface SpreadElementExpression extends Expression {
kind: SyntaxKind.SpreadElementExpression;
interface SpreadElement extends Expression {
kind: SyntaxKind.SpreadElement;
expression: Expression;
}
/**
@@ -1141,12 +1181,16 @@ declare namespace ts {
interface ModuleDeclaration extends DeclarationStatement {
kind: SyntaxKind.ModuleDeclaration;
name: Identifier | LiteralExpression;
body?: ModuleBlock | NamespaceDeclaration;
body?: ModuleBlock | NamespaceDeclaration | JSDocNamespaceDeclaration | Identifier;
}
interface NamespaceDeclaration extends ModuleDeclaration {
name: Identifier;
body: ModuleBlock | NamespaceDeclaration;
}
interface JSDocNamespaceDeclaration extends ModuleDeclaration {
name: Identifier;
body: JSDocNamespaceDeclaration | Identifier;
}
interface ModuleBlock extends Node, Statement {
kind: SyntaxKind.ModuleBlock;
statements: NodeArray<Statement>;
@@ -1318,6 +1362,7 @@ declare namespace ts {
}
interface JSDocTypedefTag extends JSDocTag, Declaration {
kind: SyntaxKind.JSDocTypedefTag;
fullName?: JSDocNamespaceDeclaration | Identifier;
name?: Identifier;
typeExpression?: JSDocTypeExpression;
jsDocTypeLiteral?: JSDocTypeLiteral;
@@ -1708,14 +1753,11 @@ declare namespace ts {
Null = 4096,
Never = 8192,
TypeParameter = 16384,
Class = 32768,
Interface = 65536,
Reference = 131072,
Tuple = 262144,
Union = 524288,
Intersection = 1048576,
Anonymous = 2097152,
Instantiated = 4194304,
Object = 32768,
Union = 65536,
Intersection = 131072,
Index = 262144,
IndexedAccess = 524288,
Literal = 480,
StringOrNumberLiteral = 96,
PossiblyFalsy = 7406,
@@ -1723,12 +1765,11 @@ declare namespace ts {
NumberLike = 340,
BooleanLike = 136,
EnumLike = 272,
ObjectType = 2588672,
UnionOrIntersection = 1572864,
StructuredType = 4161536,
StructuredOrTypeParameter = 4177920,
Narrowable = 4178943,
NotUnionOrUnit = 2589185,
UnionOrIntersection = 196608,
StructuredType = 229376,
StructuredOrTypeParameter = 507904,
Narrowable = 1033215,
NotUnionOrUnit = 33281,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
interface Type {
@@ -1749,8 +1790,21 @@ declare namespace ts {
interface EnumLiteralType extends LiteralType {
baseType: EnumType & UnionType;
}
enum ObjectFlags {
Class = 1,
Interface = 2,
Reference = 4,
Tuple = 8,
Anonymous = 16,
Mapped = 32,
Instantiated = 64,
ObjectLiteral = 128,
EvolvingArray = 256,
ObjectLiteralPatternWithComputedProperties = 512,
ClassOrInterface = 3,
}
interface ObjectType extends Type {
isObjectLiteralPatternWithComputedProperties?: boolean;
objectFlags: ObjectFlags;
}
interface InterfaceType extends ObjectType {
typeParameters: TypeParameter[];
@@ -1778,9 +1832,21 @@ declare namespace ts {
}
interface IntersectionType extends UnionOrIntersectionType {
}
type StructuredType = ObjectType | UnionType | IntersectionType;
interface EvolvingArrayType extends ObjectType {
elementType: Type;
finalArrayType?: Type;
}
interface TypeParameter extends Type {
constraint: Type;
}
interface IndexType extends Type {
type: TypeParameter;
}
interface IndexedAccessType extends Type {
objectType: Type;
indexType: TypeParameter;
}
enum SignatureKind {
Call = 0,
Construct = 1,
@@ -1882,6 +1948,7 @@ declare namespace ts {
preserveConstEnums?: boolean;
project?: string;
reactNamespace?: string;
jsxFactory?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -1912,6 +1979,7 @@ declare namespace ts {
packageNameToTypingLocation: Map<string>;
typingOptions: TypingOptions;
compilerOptions: CompilerOptions;
unresolvedImports: ReadonlyArray<string>;
}
enum ModuleKind {
None = 0,
@@ -1947,12 +2015,14 @@ declare namespace ts {
ES2015 = 2,
ES2016 = 3,
ES2017 = 4,
Latest = 4,
ESNext = 5,
Latest = 5,
}
enum LanguageVariant {
Standard = 0,
JSX = 1,
}
/** Either a parsed command line or a parsed tsconfig.json */
interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
@@ -1979,12 +2049,45 @@ declare namespace ts {
getCurrentDirectory?(): string;
getDirectories?(path: string): string[];
}
/**
* Represents the result of module resolution.
* Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off.
* The Program will then filter results based on these flags.
*
* Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred.
*/
interface ResolvedModule {
/** Path of the file the module was resolved to. */
resolvedFileName: string;
/**
* Denotes if 'resolvedFileName' is isExternalLibraryImport and thus should be a proper external module:
* - be a .d.ts file
* - use top level imports\exports
* - don't use tripleslash references
*/
isExternalLibraryImport?: boolean;
}
/**
* ResolvedModule with an explicitly provided `extension` property.
* Prefer this over `ResolvedModule`.
*/
interface ResolvedModuleFull extends ResolvedModule {
/**
* Extension of resolvedFileName. This must match what's at the end of resolvedFileName.
* This is optional for backwards-compatibility, but will be added if not provided.
*/
extension: Extension;
}
enum Extension {
Ts = 0,
Tsx = 1,
Dts = 2,
Js = 3,
Jsx = 4,
LastTypeScriptExtension = 2,
}
interface ResolvedModuleWithFailedLookupLocations {
resolvedModule: ResolvedModule;
resolvedModule: ResolvedModuleFull | undefined;
failedLookupLocations: string[];
}
interface ResolvedTypeReferenceDirective {
@@ -2042,7 +2145,11 @@ declare namespace ts {
readFile(path: string, encoding?: string): string;
getFileSize?(path: string): number;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
/**
* @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that
* use native OS file watching
*/
watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
@@ -2057,6 +2164,8 @@ declare namespace ts {
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any;
clearTimeout?(timeoutId: any): void;
}
interface FileWatcher {
close(): void;
@@ -2159,6 +2268,7 @@ declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName;
function isExternalModule(file: SourceFile): boolean;
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
@@ -2172,7 +2282,7 @@ declare namespace ts {
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
* is assumed to be the same as root directory of the project.
*/
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
/**
* Given a set of options, returns the set of type directive names
* that should be included for this program automatically.
@@ -2188,7 +2298,7 @@ declare namespace ts {
}
declare namespace ts {
/** The version of the TypeScript compiler release */
const version = "2.1.0";
const version = "2.2.0";
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
+11985 -9262
View File
File diff suppressed because it is too large Load Diff
+756 -1380
View File
File diff suppressed because it is too large Load Diff
+2 -3
View File
@@ -2,7 +2,7 @@
"name": "typescript",
"author": "Microsoft Corp.",
"homepage": "http://typescriptlang.org/",
"version": "2.1.0",
"version": "2.2.0",
"license": "Apache-2.0",
"description": "TypeScript is a language for application scale JavaScript development",
"keywords": [
@@ -75,8 +75,7 @@
"through2": "latest",
"travis-fold": "latest",
"ts-node": "latest",
"tsd": "latest",
"tslint": "4.0.0-dev.0",
"tslint": "next",
"typescript": "next"
},
"scripts": {
+13 -9
View File
@@ -1,26 +1,29 @@
var Linter = require("tslint");
var tslint = require("tslint");
var fs = require("fs");
function getLinterOptions() {
return {
configuration: require("../tslint.json"),
formatter: "prose",
formattersDirectory: undefined,
rulesDirectory: "built/local/tslint"
};
}
function lintFileContents(options, path, contents) {
var ll = new Linter(path, contents, options);
return ll.lint();
function getLinterConfiguration() {
return require("../tslint.json");
}
function lintFileAsync(options, path, cb) {
function lintFileContents(options, configuration, path, contents) {
var ll = new tslint.Linter(options);
ll.lint(path, contents, configuration);
return ll.getResult();
}
function lintFileAsync(options, configuration, path, cb) {
fs.readFile(path, "utf8", function (err, contents) {
if (err) {
return cb(err);
}
var result = lintFileContents(options, path, contents);
var result = lintFileContents(options, configuration, path, contents);
cb(undefined, result);
});
}
@@ -30,7 +33,8 @@ process.on("message", function (data) {
case "file":
var target = data.name;
var lintOptions = getLinterOptions();
lintFileAsync(lintOptions, target, function (err, result) {
var lintConfiguration = getLinterConfiguration();
lintFileAsync(lintOptions, lintConfiguration, target, function (err, result) {
if (err) {
process.send({ kind: "error", error: err.toString() });
return;
+1 -1
View File
@@ -1,4 +1,4 @@
import * as Lint from "tslint/lib/lint";
import * as Lint from "tslint/lib";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
+1 -1
View File
@@ -1,4 +1,4 @@
import * as Lint from "tslint/lib/lint";
import * as Lint from "tslint/lib";
import * as ts from "typescript";
const OPTION_CATCH = "check-catch";
+1 -1
View File
@@ -1,4 +1,4 @@
import * as Lint from "tslint/lib/lint";
import * as Lint from "tslint/lib";
import * as ts from "typescript";
+1 -1
View File
@@ -1,4 +1,4 @@
import * as Lint from "tslint/lib/lint";
import * as Lint from "tslint/lib";
import * as ts from "typescript";
@@ -1,4 +1,4 @@
import * as Lint from "tslint/lib/lint";
import * as Lint from "tslint/lib";
import * as ts from "typescript";
@@ -1,4 +1,4 @@
import * as Lint from "tslint/lib/lint";
import * as Lint from "tslint/lib";
import * as ts from "typescript";
+1 -1
View File
@@ -1,4 +1,4 @@
import * as Lint from "tslint/lib/lint";
import * as Lint from "tslint/lib";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
+1 -1
View File
@@ -1,4 +1,4 @@
import * as Lint from "tslint/lib/lint";
import * as Lint from "tslint/lib";
import * as ts from "typescript";
+229 -67
View File
@@ -234,8 +234,8 @@ namespace ts {
if (node.name.kind === SyntaxKind.ComputedPropertyName) {
const nameExpression = (<ComputedPropertyName>node.name).expression;
// treat computed property names where expression is string/numeric literal as just string/numeric literal
if (isStringOrNumericLiteral(nameExpression.kind)) {
return (<LiteralExpression>nameExpression).text;
if (isStringOrNumericLiteral(nameExpression)) {
return nameExpression.text;
}
Debug.assert(isWellKnownSymbolSyntactically(nameExpression));
@@ -518,7 +518,6 @@ namespace ts {
hasExplicitReturn = false;
bindChildren(node);
// Reset all reachability check related flags on node (for incremental scenarios)
// Reset all emit helper flags on node (for incremental scenarios)
node.flags &= ~NodeFlags.ReachabilityAndEmitFlags;
if (!(currentFlow.flags & FlowFlags.Unreachable) && containerFlags & ContainerFlags.IsFunctionLike && nodeIsPresent((<FunctionLikeDeclaration>node).body)) {
node.flags |= NodeFlags.HasImplicitReturn;
@@ -560,6 +559,7 @@ namespace ts {
skipTransformFlagAggregation = true;
bindChildrenWorker(node);
skipTransformFlagAggregation = false;
subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
}
else {
const savedSubtreeTransformFlags = subtreeTransformFlags;
@@ -569,15 +569,40 @@ namespace ts {
}
}
function bindEach(nodes: NodeArray<Node>) {
if (nodes === undefined) {
return;
}
if (skipTransformFlagAggregation) {
forEach(nodes, bind);
}
else {
const savedSubtreeTransformFlags = subtreeTransformFlags;
subtreeTransformFlags = TransformFlags.None;
let nodeArrayFlags = TransformFlags.None;
for (const node of nodes) {
bind(node);
nodeArrayFlags |= node.transformFlags & ~TransformFlags.HasComputedFlags;
}
nodes.transformFlags = nodeArrayFlags | TransformFlags.HasComputedFlags;
subtreeTransformFlags |= savedSubtreeTransformFlags;
}
}
function bindEachChild(node: Node) {
forEachChild(node, bind, bindEach);
}
function bindChildrenWorker(node: Node): void {
// Binding of JsDocComment should be done before the current block scope container changes.
// because the scope of JsDocComment should not be affected by whether the current node is a
// container or not.
if (isInJavaScriptFile(node) && node.jsDocComments) {
forEach(node.jsDocComments, bind);
if (isInJavaScriptFile(node) && node.jsDoc) {
forEach(node.jsDoc, bind);
}
if (checkUnreachable(node)) {
forEachChild(node, bind);
bindEachChild(node);
return;
}
switch (node.kind) {
@@ -642,7 +667,7 @@ namespace ts {
bindCallExpressionFlow(<CallExpression>node);
break;
default:
forEachChild(node, bind);
bindEachChild(node);
break;
}
}
@@ -895,8 +920,8 @@ namespace ts {
const enclosingLabeledStatement = node.parent.kind === SyntaxKind.LabeledStatement
? lastOrUndefined(activeLabels)
: undefined;
// if do statement is wrapped in labeled statement then target labels for break/continue with or without
// label should be the same
// if do statement is wrapped in labeled statement then target labels for break/continue with or without
// label should be the same
const preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel();
const postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel();
addAntecedent(preDoLabel, currentFlow);
@@ -975,7 +1000,7 @@ namespace ts {
return undefined;
}
function bindbreakOrContinueFlow(node: BreakOrContinueStatement, breakTarget: FlowLabel, continueTarget: FlowLabel) {
function bindBreakOrContinueFlow(node: BreakOrContinueStatement, breakTarget: FlowLabel, continueTarget: FlowLabel) {
const flowLabel = node.kind === SyntaxKind.BreakStatement ? breakTarget : continueTarget;
if (flowLabel) {
addAntecedent(flowLabel, currentFlow);
@@ -989,11 +1014,11 @@ namespace ts {
const activeLabel = findActiveLabel(node.label.text);
if (activeLabel) {
activeLabel.referenced = true;
bindbreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
}
}
else {
bindbreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
}
}
@@ -1061,6 +1086,8 @@ namespace ts {
}
function bindCaseBlock(node: CaseBlock): void {
const savedSubtreeTransformFlags = subtreeTransformFlags;
subtreeTransformFlags = 0;
const clauses = node.clauses;
let fallthroughFlow = unreachableFlow;
for (let i = 0; i < clauses.length; i++) {
@@ -1080,6 +1107,8 @@ namespace ts {
errorOnFirstToken(clause, Diagnostics.Fallthrough_case_in_switch);
}
}
clauses.transformFlags = subtreeTransformFlags | TransformFlags.HasComputedFlags;
subtreeTransformFlags |= savedSubtreeTransformFlags;
}
function bindCaseClause(node: CaseClause): void {
@@ -1087,7 +1116,7 @@ namespace ts {
currentFlow = preSwitchCaseFlow;
bind(node.expression);
currentFlow = saveCurrentFlow;
forEach(node.statements, bind);
bindEach(node.statements);
}
function pushActiveLabel(name: string, breakTarget: FlowLabel, continueTarget: FlowLabel): ActiveLabel {
@@ -1138,8 +1167,8 @@ namespace ts {
}
else if (node.kind === SyntaxKind.ArrayLiteralExpression) {
for (const e of (<ArrayLiteralExpression>node).elements) {
if (e.kind === SyntaxKind.SpreadElementExpression) {
bindAssignmentTargetFlow((<SpreadElementExpression>e).expression);
if (e.kind === SyntaxKind.SpreadElement) {
bindAssignmentTargetFlow((<SpreadElement>e).expression);
}
else {
bindDestructuringTargetFlow(e);
@@ -1154,6 +1183,9 @@ namespace ts {
else if (p.kind === SyntaxKind.ShorthandPropertyAssignment) {
bindAssignmentTargetFlow((<ShorthandPropertyAssignment>p).name);
}
else if (p.kind === SyntaxKind.SpreadAssignment) {
bindAssignmentTargetFlow((<SpreadAssignment>p).expression);
}
}
}
}
@@ -1176,12 +1208,12 @@ namespace ts {
const saveTrueTarget = currentTrueTarget;
currentTrueTarget = currentFalseTarget;
currentFalseTarget = saveTrueTarget;
forEachChild(node, bind);
bindEachChild(node);
currentFalseTarget = currentTrueTarget;
currentTrueTarget = saveTrueTarget;
}
else {
forEachChild(node, bind);
bindEachChild(node);
if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) {
bindAssignmentTargetFlow(node.operand);
}
@@ -1189,7 +1221,7 @@ namespace ts {
}
function bindPostfixUnaryExpressionFlow(node: PostfixUnaryExpression) {
forEachChild(node, bind);
bindEachChild(node);
if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) {
bindAssignmentTargetFlow(node.operand);
}
@@ -1208,7 +1240,7 @@ namespace ts {
}
}
else {
forEachChild(node, bind);
bindEachChild(node);
if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) {
bindAssignmentTargetFlow(node.left);
if (operator === SyntaxKind.EqualsToken && node.left.kind === SyntaxKind.ElementAccessExpression) {
@@ -1222,7 +1254,7 @@ namespace ts {
}
function bindDeleteExpressionFlow(node: DeleteExpression) {
forEachChild(node, bind);
bindEachChild(node);
if (node.expression.kind === SyntaxKind.PropertyAccessExpression) {
bindAssignmentTargetFlow(node.expression);
}
@@ -1234,9 +1266,11 @@ namespace ts {
const postExpressionLabel = createBranchLabel();
bindCondition(node.condition, trueLabel, falseLabel);
currentFlow = finishFlowLabel(trueLabel);
bind(node.questionToken);
bind(node.whenTrue);
addAntecedent(postExpressionLabel, currentFlow);
currentFlow = finishFlowLabel(falseLabel);
bind(node.colonToken);
bind(node.whenFalse);
addAntecedent(postExpressionLabel, currentFlow);
currentFlow = finishFlowLabel(postExpressionLabel);
@@ -1245,7 +1279,7 @@ namespace ts {
function bindInitializedVariableFlow(node: VariableDeclaration | ArrayBindingElement) {
const name = !isOmittedExpression(node) ? node.name : undefined;
if (isBindingPattern(name)) {
for (const child of name.elements) {
for (const child of <ArrayBindingElement[]>name.elements) {
bindInitializedVariableFlow(child);
}
}
@@ -1255,7 +1289,7 @@ namespace ts {
}
function bindVariableDeclarationFlow(node: VariableDeclaration) {
forEachChild(node, bind);
bindEachChild(node);
if (node.initializer || node.parent.parent.kind === SyntaxKind.ForInStatement || node.parent.parent.kind === SyntaxKind.ForOfStatement) {
bindInitializedVariableFlow(node);
}
@@ -1270,12 +1304,12 @@ namespace ts {
expr = (<ParenthesizedExpression>expr).expression;
}
if (expr.kind === SyntaxKind.FunctionExpression || expr.kind === SyntaxKind.ArrowFunction) {
forEach(node.typeArguments, bind);
forEach(node.arguments, bind);
bindEach(node.typeArguments);
bindEach(node.arguments);
bind(node.expression);
}
else {
forEachChild(node, bind);
bindEachChild(node);
}
if (node.expression.kind === SyntaxKind.PropertyAccessExpression) {
const propertyAccess = <PropertyAccessExpression>node.expression;
@@ -1302,6 +1336,7 @@ namespace ts {
case SyntaxKind.JSDocFunctionType:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.MappedType:
return ContainerFlags.IsContainer | ContainerFlags.HasLocals;
case SyntaxKind.SourceFile:
@@ -1421,6 +1456,7 @@ namespace ts {
case SyntaxKind.ArrowFunction:
case SyntaxKind.JSDocFunctionType:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.MappedType:
// All the children of these container types are never visible through another
// symbol (i.e. through another symbol's 'exports' or 'members'). Instead,
// they're only accessed 'lexically' (i.e. from code that exists underneath
@@ -1547,7 +1583,7 @@ namespace ts {
const seen = createMap<ElementKind>();
for (const prop of node.properties) {
if (prop.name.kind !== SyntaxKind.Identifier) {
if (prop.kind === SyntaxKind.SpreadAssignment || prop.name.kind !== SyntaxKind.Identifier) {
continue;
}
@@ -1926,8 +1962,20 @@ namespace ts {
case SyntaxKind.EnumMember:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes);
case SyntaxKind.SpreadAssignment:
case SyntaxKind.JsxSpreadAttribute:
emitFlags |= NodeFlags.HasJsxSpreadAttributes;
let root = container;
let hasRest = false;
while (root.parent) {
if (root.kind === SyntaxKind.ObjectLiteralExpression &&
root.parent.kind === SyntaxKind.BinaryExpression &&
(root.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken &&
(root.parent as BinaryExpression).left === root) {
hasRest = true;
break;
}
root = root.parent;
}
return;
case SyntaxKind.CallSignature:
@@ -1955,9 +2003,10 @@ namespace ts {
case SyntaxKind.JSDocFunctionType:
return bindFunctionOrConstructorType(<SignatureDeclaration>node);
case SyntaxKind.TypeLiteral:
case SyntaxKind.MappedType:
case SyntaxKind.JSDocTypeLiteral:
case SyntaxKind.JSDocRecordType:
return bindAnonymousDeclaration(<TypeLiteralNode>node, SymbolFlags.TypeLiteral, "__type");
return bindAnonymousDeclaration(<Declaration>node, SymbolFlags.TypeLiteral, "__type");
case SyntaxKind.ObjectLiteralExpression:
return bindObjectLiteralExpression(<ObjectLiteralExpression>node);
case SyntaxKind.FunctionExpression:
@@ -2182,15 +2231,6 @@ namespace ts {
}
function bindClassLikeDeclaration(node: ClassLikeDeclaration) {
if (!isDeclarationFile(file) && !isInAmbientContext(node)) {
if (getClassExtendsHeritageClauseElement(node) !== undefined) {
emitFlags |= NodeFlags.HasClassExtends;
}
if (nodeIsDecorated(node)) {
emitFlags |= NodeFlags.HasDecorators;
}
}
if (node.kind === SyntaxKind.ClassDeclaration) {
bindBlockScopedDeclaration(node, SymbolFlags.Class, SymbolFlags.ClassExcludes);
}
@@ -2260,12 +2300,6 @@ namespace ts {
}
function bindParameter(node: ParameterDeclaration) {
if (!isDeclarationFile(file) &&
!isInAmbientContext(node) &&
nodeIsDecorated(node)) {
emitFlags |= (NodeFlags.HasDecorators | NodeFlags.HasParamDecorators);
}
if (inStrictMode) {
// It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
// strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
@@ -2323,9 +2357,6 @@ namespace ts {
if (isAsyncFunctionLike(node)) {
emitFlags |= NodeFlags.HasAsyncFunctions;
}
if (nodeIsDecorated(node)) {
emitFlags |= NodeFlags.HasDecorators;
}
}
if (currentFlow && isObjectLiteralOrClassExpressionMethod(node)) {
@@ -2492,9 +2523,9 @@ namespace ts {
transformFlags |= TransformFlags.AssertTypeScript;
}
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression
if (subtreeFlags & TransformFlags.ContainsSpread
|| isSuperOrSuperProperty(expression, expressionKind)) {
// If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6
// If the this node contains a SpreadExpression, or is a super call, then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES2015;
}
@@ -2523,7 +2554,7 @@ namespace ts {
if (node.typeArguments) {
transformFlags |= TransformFlags.AssertTypeScript;
}
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) {
if (subtreeFlags & TransformFlags.ContainsSpread) {
// If the this node contains a SpreadElementExpression then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES2015;
@@ -2532,16 +2563,18 @@ namespace ts {
return transformFlags & ~TransformFlags.ArrayLiteralOrCallOrNewExcludes;
}
function computeBinaryExpression(node: BinaryExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const operatorTokenKind = node.operatorToken.kind;
const leftKind = node.left.kind;
if (operatorTokenKind === SyntaxKind.EqualsToken
&& (leftKind === SyntaxKind.ObjectLiteralExpression
|| leftKind === SyntaxKind.ArrayLiteralExpression)) {
// Destructuring assignments are ES6 syntax.
if (operatorTokenKind === SyntaxKind.EqualsToken && leftKind === SyntaxKind.ObjectLiteralExpression) {
// Destructuring object assignments with are ES2015 syntax
// and possibly ESNext if they contain rest
transformFlags |= TransformFlags.AssertESNext | TransformFlags.AssertES2015 | TransformFlags.AssertDestructuringAssignment;
}
else if (operatorTokenKind === SyntaxKind.EqualsToken && leftKind === SyntaxKind.ArrayLiteralExpression) {
// Destructuring assignments are ES2015 syntax.
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.AssertDestructuringAssignment;
}
else if (operatorTokenKind === SyntaxKind.AsteriskAsteriskToken
@@ -2575,6 +2608,11 @@ namespace ts {
transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsParameterPropertyAssignments;
}
// parameters with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
// 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) {
@@ -2693,7 +2731,7 @@ namespace ts {
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
return transformFlags & ~TransformFlags.CatchClauseExcludes;
}
function computeExpressionWithTypeArguments(node: ExpressionWithTypeArguments, subtreeFlags: TransformFlags) {
@@ -2720,6 +2758,11 @@ namespace ts {
transformFlags |= TransformFlags.AssertTypeScript;
}
// function declarations with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.ConstructorExcludes;
}
@@ -2738,6 +2781,11 @@ namespace ts {
transformFlags |= TransformFlags.AssertTypeScript;
}
// function declarations with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
// An async method declaration is ES2017 syntax.
if (hasModifier(node, ModifierFlags.Async)) {
transformFlags |= TransformFlags.AssertES2017;
@@ -2764,6 +2812,11 @@ namespace ts {
transformFlags |= TransformFlags.AssertTypeScript;
}
// function declarations with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.MethodOrAccessorExcludes;
}
@@ -2808,6 +2861,11 @@ namespace ts {
transformFlags |= TransformFlags.AssertES2017;
}
// function declarations with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
// 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.
@@ -2845,6 +2903,12 @@ namespace ts {
transformFlags |= TransformFlags.AssertES2017;
}
// function expressions with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
// 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.
@@ -2882,6 +2946,11 @@ namespace ts {
transformFlags |= TransformFlags.AssertES2017;
}
// arrow functions with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
// If an ArrowFunction contains a lexical this, its container must capture the lexical this.
if (subtreeFlags & TransformFlags.ContainsLexicalThis) {
transformFlags |= TransformFlags.ContainsCapturedLexicalThis;
@@ -2908,11 +2977,11 @@ namespace ts {
function computeVariableDeclaration(node: VariableDeclaration, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const nameKind = node.name.kind;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
// A VariableDeclaration with a binding pattern is ES6 syntax.
if (nameKind === SyntaxKind.ObjectBindingPattern || nameKind === SyntaxKind.ArrayBindingPattern) {
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
// A VariableDeclaration containing ObjectRest is ESNext syntax
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
// Type annotations are TypeScript syntax.
@@ -3052,6 +3121,10 @@ namespace ts {
transformFlags |= TransformFlags.AssertJsx;
break;
case SyntaxKind.ForOfStatement:
// for-of might be ESNext if it has a rest destructuring
transformFlags |= TransformFlags.AssertESNext;
// FALLTHROUGH
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.TemplateHead:
case SyntaxKind.TemplateMiddle:
@@ -3059,7 +3132,6 @@ namespace ts {
case SyntaxKind.TemplateExpression:
case SyntaxKind.TaggedTemplateExpression:
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.ForOfStatement:
case SyntaxKind.StaticKeyword:
// These nodes are ES6 syntax.
transformFlags |= TransformFlags.AssertES2015;
@@ -3099,6 +3171,7 @@ namespace ts {
case SyntaxKind.ThisType:
case SyntaxKind.TypeOperator:
case SyntaxKind.IndexedAccessType:
case SyntaxKind.MappedType:
case SyntaxKind.LiteralType:
// Types and signatures are TypeScript syntax, and exclude all other facts.
transformFlags = TransformFlags.AssertTypeScript;
@@ -3123,9 +3196,12 @@ namespace ts {
}
break;
case SyntaxKind.SpreadElementExpression:
// This node is ES6 syntax, but is handled by a containing node.
transformFlags |= TransformFlags.ContainsSpreadElementExpression;
case SyntaxKind.SpreadElement:
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsSpread;
break;
case SyntaxKind.SpreadAssignment:
transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectSpread;
break;
case SyntaxKind.SuperKeyword:
@@ -3139,9 +3215,23 @@ namespace ts {
break;
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
// These nodes are ES6 syntax.
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
if (subtreeFlags & TransformFlags.ContainsRest) {
transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectRest;
}
excludeFlags = TransformFlags.BindingPatternExcludes;
break;
case SyntaxKind.ArrayBindingPattern:
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
excludeFlags = TransformFlags.BindingPatternExcludes;
break;
case SyntaxKind.BindingElement:
transformFlags |= TransformFlags.AssertES2015;
if ((<BindingElement>node).dotDotDotToken) {
transformFlags |= TransformFlags.ContainsRest;
}
break;
case SyntaxKind.Decorator:
@@ -3163,13 +3253,19 @@ namespace ts {
transformFlags |= TransformFlags.ContainsLexicalThis;
}
if (subtreeFlags & TransformFlags.ContainsObjectSpread) {
// If an ObjectLiteralExpression contains a spread element, then it
// is an ES next node.
transformFlags |= TransformFlags.AssertESNext;
}
break;
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.NewExpression:
excludeFlags = TransformFlags.ArrayLiteralOrCallOrNewExcludes;
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) {
// If the this node contains a SpreadElementExpression, then it is an ES6
if (subtreeFlags & TransformFlags.ContainsSpread) {
// If the this node contains a SpreadExpression, then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES2015;
}
@@ -3204,4 +3300,70 @@ namespace ts {
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~excludeFlags;
}
/**
* Gets the transform flags to exclude when unioning the transform flags of a subtree.
*
* NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`.
* For performance reasons, `computeTransformFlagsForNode` uses local constant values rather
* than calling this function.
*/
/* @internal */
export function getTransformFlagsSubtreeExclusions(kind: SyntaxKind) {
if (kind >= SyntaxKind.FirstTypeNode && kind <= SyntaxKind.LastTypeNode) {
return TransformFlags.TypeExcludes;
}
switch (kind) {
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.ArrayLiteralExpression:
return TransformFlags.ArrayLiteralOrCallOrNewExcludes;
case SyntaxKind.ModuleDeclaration:
return TransformFlags.ModuleExcludes;
case SyntaxKind.Parameter:
return TransformFlags.ParameterExcludes;
case SyntaxKind.ArrowFunction:
return TransformFlags.ArrowFunctionExcludes;
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
return TransformFlags.FunctionExcludes;
case SyntaxKind.VariableDeclarationList:
return TransformFlags.VariableDeclarationListExcludes;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
return TransformFlags.ClassExcludes;
case SyntaxKind.Constructor:
return TransformFlags.ConstructorExcludes;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return TransformFlags.MethodOrAccessorExcludes;
case SyntaxKind.AnyKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.NeverKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.TypeParameter:
case SyntaxKind.PropertySignature:
case SyntaxKind.MethodSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
return TransformFlags.TypeExcludes;
case SyntaxKind.ObjectLiteralExpression:
return TransformFlags.ObjectLiteralExcludes;
case SyntaxKind.CatchClause:
return TransformFlags.CatchClauseExcludes;
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
return TransformFlags.BindingPatternExcludes;
default:
return TransformFlags.NodeExcludes;
}
}
}
+1203 -451
View File
File diff suppressed because it is too large Load Diff
+50 -24
View File
@@ -77,6 +77,11 @@ namespace ts {
type: "string",
description: Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit
},
{
name: "jsxFactory",
type: "string",
description: Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
},
{
name: "listFiles",
type: "boolean",
@@ -265,8 +270,9 @@ namespace ts {
"es2015": ScriptTarget.ES2015,
"es2016": ScriptTarget.ES2016,
"es2017": ScriptTarget.ES2017,
"esnext": ScriptTarget.ESNext,
}),
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015,
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT,
paramType: Diagnostics.VERSION,
},
{
@@ -428,7 +434,8 @@ namespace ts {
"es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts",
"es2016.array.include": "lib.es2016.array.include.d.ts",
"es2017.object": "lib.es2017.object.d.ts",
"es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts"
"es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts",
"es2017.string": "lib.es2017.string.d.ts",
}),
},
description: Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon
@@ -455,11 +462,18 @@ namespace ts {
];
/* @internal */
export let typingOptionDeclarations: CommandLineOption[] = [
export let typeAcquisitionDeclarations: CommandLineOption[] = [
{
/* @deprecated typingOptions.enableAutoDiscovery
* Use typeAcquisition.enable instead.
*/
name: "enableAutoDiscovery",
type: "boolean",
},
{
name: "enable",
type: "boolean",
},
{
name: "include",
type: "list",
@@ -494,6 +508,20 @@ namespace ts {
let optionNameMapCache: OptionNameMap;
/* @internal */
export function convertEnableAutoDiscoveryToEnable(typeAcquisition: TypeAcquisition): TypeAcquisition {
// Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
const result: TypeAcquisition = {
enable: typeAcquisition.enableAutoDiscovery,
include: typeAcquisition.include || [],
exclude: typeAcquisition.exclude || []
};
return result;
}
return typeAcquisition;
}
/* @internal */
export function getOptionNameMap(): OptionNameMap {
if (optionNameMapCache) {
@@ -521,14 +549,7 @@ namespace ts {
/* @internal */
export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) {
const key = trimString((value || "")).toLowerCase();
const map = opt.type;
if (key in map) {
return map[key];
}
else {
errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
}
return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
}
/* @internal */
@@ -828,7 +849,7 @@ namespace ts {
return {
options: {},
fileNames: [],
typingOptions: {},
typeAcquisition: {},
raw: json,
errors: [createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))],
wildcardDirectories: {}
@@ -836,7 +857,10 @@ namespace ts {
}
let options: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName);
const typingOptions: TypingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName);
// typingOptions has been deprecated and is only supported for backward compatibility purposes.
// It should be removed in future releases - use typeAcquisition instead.
const jsonOptions = json["typeAcquisition"] || json["typingOptions"];
const typeAcquisition: TypeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
if (json["extends"]) {
let [include, exclude, files, baseOptions]: [string[], string[], string[], CompilerOptions] = [undefined, undefined, undefined, {}];
@@ -867,7 +891,7 @@ namespace ts {
return {
options,
fileNames,
typingOptions,
typeAcquisition,
raw: json,
errors,
wildcardDirectories,
@@ -877,7 +901,7 @@ namespace ts {
function tryExtendsName(extendedConfig: string): [string[], string[], string[], CompilerOptions] {
// If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future)
if (!(isRootedDiskPath(extendedConfig) || startsWith(normalizeSlashes(extendedConfig), "./") || startsWith(normalizeSlashes(extendedConfig), "../"))) {
errors.push(createCompilerDiagnostic(Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted));
errors.push(createCompilerDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig));
return;
}
let extendedConfigPath = toPath(extendedConfig, basePath, getCanonicalFileName);
@@ -944,8 +968,8 @@ namespace ts {
errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
}
else {
// By default, exclude common package folders and the outDir
excludeSpecs = ["node_modules", "bower_components", "jspm_packages"];
// If no includes were specified, exclude common package folders and the outDir
excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"];
const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"];
if (outDir) {
@@ -989,9 +1013,9 @@ namespace ts {
return { options, errors };
}
export function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: TypingOptions, errors: Diagnostic[] } {
export function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: TypeAcquisition, errors: Diagnostic[] } {
const errors: Diagnostic[] = [];
const options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
const options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
return { options, errors };
}
@@ -1005,16 +1029,18 @@ namespace ts {
return options;
}
function convertTypingOptionsFromJsonWorker(jsonOptions: any,
basePath: string, errors: Diagnostic[], configFileName?: string): TypingOptions {
function convertTypeAcquisitionFromJsonWorker(jsonOptions: any,
basePath: string, errors: Diagnostic[], configFileName?: string): TypeAcquisition {
const options: TypeAcquisition = { enable: getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
const typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
convertOptionsFromJson(typeAcquisitionDeclarations, typeAcquisition, basePath, options, Diagnostics.Unknown_type_acquisition_option_0, errors);
const options: TypingOptions = { enableAutoDiscovery: getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
convertOptionsFromJson(typingOptionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_typing_option_0, errors);
return options;
}
function convertOptionsFromJson(optionDeclarations: CommandLineOption[], jsonOptions: any, basePath: string,
defaultOptions: CompilerOptions | TypingOptions, diagnosticMessage: DiagnosticMessage, errors: Diagnostic[]) {
defaultOptions: CompilerOptions | TypeAcquisition, diagnosticMessage: DiagnosticMessage, errors: Diagnostic[]) {
if (!jsonOptions) {
return;
+61 -3
View File
@@ -1,6 +1,11 @@
/// <reference path="types.ts"/>
/// <reference path="performance.ts" />
namespace ts {
/** The version of the TypeScript compiler release */
export const version = "2.2.0";
}
/* @internal */
namespace ts {
/**
@@ -566,7 +571,7 @@ namespace ts {
*/
export function append<T>(to: T[] | undefined, value: T | undefined): T[] | undefined {
if (value === undefined) return to;
if (to === undefined) to = [];
if (to === undefined) return [value];
to.push(value);
return to;
}
@@ -587,6 +592,16 @@ namespace ts {
return to;
}
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
export function stableSort<T>(array: T[], comparer: (x: T, y: T) => Comparison = compareValues) {
return array
.map((_, i) => i) // create array of indices
.sort((x, y) => comparer(array[x], array[y]) || compareValues(x, y)) // sort indices by value then position
.map(i => array[i]); // get sorted array
}
export function rangeEquals<T>(array1: T[], array2: T[], pos: number, end: number) {
while (pos < end) {
if (array1[pos] !== array2[pos]) {
@@ -811,6 +826,13 @@ namespace ts {
}
}
export function appendProperty<T>(map: Map<T>, key: string | number, value: T): Map<T> {
if (key === undefined || value === undefined) return map;
if (map === undefined) map = createMap<T>();
map[key] = value;
return map;
}
export function assign<T1 extends MapLike<{}>, T2, T3>(t: T1, arg1: T2, arg2: T3): T1 & T2 & T3;
export function assign<T1 extends MapLike<{}>, T2>(t: T1, arg1: T2): T1 & T2;
export function assign<T1 extends MapLike<{}>>(t: T1, ...args: any[]): any;
@@ -1127,6 +1149,18 @@ namespace ts {
};
}
export function createCompilerDiagnosticFromMessageChain(chain: DiagnosticMessageChain): Diagnostic {
return {
file: undefined,
start: undefined,
length: undefined,
code: chain.code,
category: chain.category,
messageText: chain.next ? chain : chain.messageText
};
}
export function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage, ...args: any[]): DiagnosticMessageChain;
export function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage): DiagnosticMessageChain {
let text = getLocaleSpecificMessage(message);
@@ -1357,6 +1391,14 @@ namespace ts {
getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES2015 ? ModuleKind.ES2015 : ModuleKind.CommonJS;
}
export function getEmitModuleResolutionKind(compilerOptions: CompilerOptions) {
let moduleResolution = compilerOptions.moduleResolution;
if (moduleResolution === undefined) {
moduleResolution = getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
}
return moduleResolution;
}
/* @internal */
export function hasZeroOrOneAsteriskCharacter(str: string): boolean {
let seenAsterisk = false;
@@ -2075,6 +2117,17 @@ namespace ts {
}
/** Remove an item from an array, moving everything to its right one space left. */
export function orderedRemoveItem<T>(array: T[], item: T): boolean {
for (let i = 0; i < array.length; i++) {
if (array[i] === item) {
orderedRemoveItemAt(array, i);
return true;
}
}
return false;
}
/** Remove an item by index from an array, moving everything to its right one space left. */
export function orderedRemoveItemAt<T>(array: T[], index: number): void {
// This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
for (let i = index; i < array.length - 1; i++) {
@@ -2198,6 +2251,13 @@ namespace ts {
* Path must have a valid extension.
*/
export function extensionFromPath(path: string): Extension {
const ext = tryGetExtensionFromPath(path);
if (ext !== undefined) {
return ext;
}
Debug.fail(`File ${path} has unknown extension.`);
}
export function tryGetExtensionFromPath(path: string): Extension | undefined {
if (fileExtensionIs(path, ".d.ts")) {
return Extension.Dts;
}
@@ -2213,7 +2273,5 @@ namespace ts {
if (fileExtensionIs(path, ".jsx")) {
return Extension.Jsx;
}
Debug.fail(`File ${path} has unknown extension.`);
return Extension.Js;
}
}
+46 -4
View File
@@ -194,6 +194,7 @@ namespace ts {
writer.writeSpace = writer.write;
writer.writeStringLiteral = writer.writeLiteral;
writer.writeParameter = writer.write;
writer.writeProperty = writer.write;
writer.writeSymbol = writer.write;
setWriter(writer);
}
@@ -371,7 +372,7 @@ namespace ts {
function writeJsDocComments(declaration: Node) {
if (declaration) {
const jsDocComments = getJsDocCommentsFromText(declaration, currentText);
const jsDocComments = getJSDocCommentRanges(declaration, currentText);
emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments);
// jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space
emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeCommentRange);
@@ -416,7 +417,9 @@ namespace ts {
case SyntaxKind.TypeOperator:
return emitTypeOperator(<TypeOperatorNode>type);
case SyntaxKind.IndexedAccessType:
return emitPropertyAccessType(<IndexedAccessTypeNode>type);
return emitIndexedAccessType(<IndexedAccessTypeNode>type);
case SyntaxKind.MappedType:
return emitMappedType(<MappedTypeNode>type);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return emitSignatureDeclarationWithJsDocComments(<FunctionOrConstructorTypeNode>type);
@@ -516,13 +519,39 @@ namespace ts {
emitType(type.type);
}
function emitPropertyAccessType(node: IndexedAccessTypeNode) {
function emitIndexedAccessType(node: IndexedAccessTypeNode) {
emitType(node.objectType);
write("[");
emitType(node.indexType);
write("]");
}
function emitMappedType(node: MappedTypeNode) {
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
write("{");
writeLine();
increaseIndent();
if (node.readonlyToken) {
write("readonly ");
}
write("[");
writeEntityName(node.typeParameter.name);
write(" in ");
emitType(node.typeParameter.constraint);
write("]");
if (node.questionToken) {
write("?");
}
write(": ");
emitType(node.type);
write(";");
writeLine();
decreaseIndent();
write("}");
enclosingDeclaration = prevEnclosingDeclaration;
}
function emitTypeLiteral(type: TypeLiteralNode) {
write("{");
if (type.members.length) {
@@ -1009,6 +1038,10 @@ namespace ts {
diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
break;
case SyntaxKind.TypeAliasDeclaration:
diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
break;
default:
Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
}
@@ -1115,7 +1148,10 @@ namespace ts {
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
emitHeritageClause(getInterfaceBaseTypeNodes(node), /*isImplementsList*/ false);
const interfaceExtendsTypes = filter(getInterfaceBaseTypeNodes(node), base => isEntityNameExpression(base.expression));
if (interfaceExtendsTypes && interfaceExtendsTypes.length) {
emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false);
}
write(" {");
writeLine();
increaseIndent();
@@ -1590,6 +1626,12 @@ namespace ts {
Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
case SyntaxKind.IndexSignature:
// Interfaces cannot have parameter types that cannot be named
return symbolAccessibilityResult.errorModuleName ?
Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
if (hasModifier(node.parent, ModifierFlags.Static)) {
+81 -5
View File
@@ -851,6 +851,10 @@
"category": "Error",
"code": 1317
},
"An abstract accessor cannot have an implementation.": {
"category": "Error",
"code": 1318
},
"Duplicate identifier '{0}'.": {
"category": "Error",
"code": 2300
@@ -1023,6 +1027,10 @@
"category": "Error",
"code": 2342
},
"This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'.": {
"category": "Error",
"code": 2343
},
"Type '{0}' does not satisfy the constraint '{1}'.": {
"category": "Error",
"code": 2344
@@ -1063,6 +1071,10 @@
"category": "Error",
"code": 2353
},
"This syntax requires an imported helper but module '{0}' cannot be found.": {
"category": "Error",
"code": 2354
},
"A function whose declared type is neither 'void' nor 'any' must return a value.": {
"category": "Error",
"code": 2355
@@ -1455,7 +1467,7 @@
"category": "Error",
"code": 2461
},
"A rest element must be last in an array destructuring pattern": {
"A rest element must be last in a destructuring pattern": {
"category": "Error",
"code": 2462
},
@@ -1731,7 +1743,7 @@
"category": "Error",
"code": 2535
},
"Type '{0}' is not constrained to 'keyof {1}'.": {
"Type '{0}' cannot be used to index type '{1}'.": {
"category": "Error",
"code": 2536
},
@@ -1983,6 +1995,22 @@
"category": "Error",
"code": 2697
},
"Spread types may only be created from object types.": {
"category": "Error",
"code": 2698
},
"Rest types may only be created from object types.": {
"category": "Error",
"code": 2700
},
"The target of an object rest assignment must be a variable or a property access.": {
"category": "Error",
"code": 2701
},
"'{0}' only refers to a type, but is being used as a namespace here.": {
"category": "Error",
"code": 2702
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
@@ -2264,10 +2292,22 @@
"category": "Error",
"code": 4082
},
"Type parameter '{0}' of exported type alias has or is using private name '{1}'.": {
"category": "Error",
"code": 4083
},
"Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict.": {
"category": "Message",
"code": 4090
},
"Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'.": {
"category": "Error",
"code": 4091
},
"Parameter '{0}' of index signature from exported interface has or is using private name '{1}'.": {
"category": "Error",
"code": 4092
},
"The current host does not support the '{0}' option.": {
"category": "Error",
@@ -2381,6 +2421,10 @@
"category": "Error",
"code": 5066
},
"Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name.": {
"category": "Error",
"code": 5067
},
"Concatenate and emit output to single file.": {
"category": "Message",
"code": 6001
@@ -2429,7 +2473,7 @@
"category": "Message",
"code": 6012
},
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'": {
"Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'": {
"category": "Message",
"code": 6015
},
@@ -2897,6 +2941,10 @@
"category": "Message",
"code": 6145
},
"Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'.": {
"category": "Message",
"code": 6146
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005
@@ -3069,6 +3117,10 @@
"category": "Error",
"code": 9003
},
"Language service is disabled.": {
"category": "Error",
"code": 9004
},
"JSX attributes must only be assigned a non-empty 'expression'.": {
"category": "Error",
"code": 17000
@@ -3109,16 +3161,20 @@
"category": "Error",
"code": 17009
},
"Unknown typing option '{0}'.": {
"Unknown type acquisition option '{0}'.": {
"category": "Error",
"code": 17010
},
"'super' must be called before accessing a property of 'super' in the constructor of a derived class.": {
"category": "Error",
"code": 17011
},
"Circularity detected while resolving configuration: {0}": {
"category": "Error",
"code": 18000
},
"The path in an 'extends' options must be relative or rooted.": {
"A path in an 'extends' option must be relative or rooted, but '{0}' is not.": {
"category": "Error",
"code": 18001
},
@@ -3158,5 +3214,25 @@
"Implement inherited abstract class": {
"category": "Message",
"code": 90007
},
"Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig": {
"category": "Error",
"code": 90009
},
"Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated.": {
"category": "Error",
"code": 90010
},
"Import {0} from {1}": {
"category": "Message",
"code": 90013
},
"Change {0} to {1}": {
"category": "Message",
"code": 90014
},
"Add {0} to existing import declaration from {1}": {
"category": "Message",
"code": 90015
}
}
+92 -267
View File
@@ -20,174 +20,6 @@ namespace ts {
export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean): EmitResult {
const delimiters = createDelimiterMap();
const brackets = createBracketsMap();
// emit output for the __extends helper function
const extendsHelper = `
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};`;
// Emit output for the __assign helper function.
// This is typically used for JSX spread attributes,
// and can be used for object literal spread properties.
const assignHelper = `
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};`;
// emit output for the __decorate helper function
const decorateHelper = `
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};`;
// emit output for the __metadata helper function
const metadataHelper = `
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};`;
// emit output for the __param helper function
const paramHelper = `
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};`;
// emit output for the __awaiter helper function
const awaiterHelper = `
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 step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
};`;
// The __generator helper is used by down-level transformations to emulate the runtime
// semantics of an ES2015 generator function. When called, this helper returns an
// object that implements the Iterator protocol, in that it has `next`, `return`, and
// `throw` methods that step through the generator when invoked.
//
// parameters:
// thisArg The value to use as the `this` binding for the transformed generator body.
// body A function that acts as the transformed generator body.
//
// variables:
// _ Persistent state for the generator that is shared between the helper and the
// generator body. The state object has the following members:
// sent() - A method that returns or throws the current completion value.
// label - The next point at which to resume evaluation of the generator body.
// trys - A stack of protected regions (try/catch/finally blocks).
// ops - A stack of pending instructions when inside of a finally block.
// f A value indicating whether the generator is executing.
// y An iterator to delegate for a yield*.
// t A temporary variable that holds one of the following values (note that these
// cases do not overlap):
// - The completion value when resuming from a `yield` or `yield*`.
// - The error value for a catch block.
// - The current protected region (array of try/catch/finally/end labels).
// - The verb (`next`, `throw`, or `return` method) to delegate to the expression
// of a `yield*`.
// - The result of evaluating the verb delegated to the expression of a `yield*`.
//
// functions:
// verb(n) Creates a bound callback to the `step` function for opcode `n`.
// step(op) Evaluates opcodes in a generator body until execution is suspended or
// completed.
//
// The __generator helper understands a limited set of instructions:
// 0: next(value?) - Start or resume the generator with the specified value.
// 1: throw(error) - Resume the generator with an exception. If the generator is
// suspended inside of one or more protected regions, evaluates
// any intervening finally blocks between the current label and
// the nearest catch block or function boundary. If uncaught, the
// exception is thrown to the caller.
// 2: return(value?) - Resume the generator as if with a return. If the generator is
// suspended inside of one or more protected regions, evaluates any
// intervening finally blocks.
// 3: break(label) - Jump to the specified label. If the label is outside of the
// current protected region, evaluates any intervening finally
// blocks.
// 4: yield(value?) - Yield execution to the caller with an optional value. When
// resumed, the generator will continue at the next label.
// 5: yield*(value) - Delegates evaluation to the supplied iterator. When
// delegation completes, the generator will continue at the next
// label.
// 6: catch(error) - Handles an exception thrown from within the generator body. If
// the current label is inside of one or more protected regions,
// evaluates any intervening finally blocks between the current
// label and the nearest catch block or function boundary. If
// uncaught, the exception is thrown to the caller.
// 7: endfinally - Ends a finally block, resuming the last instruction prior to
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
const generatorHelper = `
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;
return { next: verb(0), "throw": verb(1), "return": verb(2) };
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};`;
// emit output for the __export helper function
const exportStarHelper = `
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}`;
// emit output for the UMD helper function.
const umdHelper = `
(function (dependencies, factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(dependencies, factory);
}
})`;
const superHelper = `
const _super = name => super[name];`;
const advancedSuperHelper = `
const _super = (function (geti, seti) {
const cache = Object.create(null);
return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });
})(name => super[name], (name, value) => super[name] = value);`;
const compilerOptions = host.getCompilerOptions();
const languageVersion = getEmitScriptTarget(compilerOptions);
const moduleKind = getEmitModuleKind(compilerOptions);
@@ -224,11 +56,7 @@ const _super = (function (geti, seti) {
let currentSourceFile: SourceFile;
let currentText: string;
let currentFileIdentifiers: Map<string>;
let extendsEmitted: boolean;
let assignEmitted: boolean;
let decorateEmitted: boolean;
let paramEmitted: boolean;
let awaiterEmitted: boolean;
let bundledHelpers: Map<boolean>;
let isOwnFileEmit: boolean;
let emitSkipped = false;
@@ -293,12 +121,13 @@ const _super = (function (geti, seti) {
nodeIdToGeneratedName = [];
autoGeneratedIdToGeneratedName = [];
generatedNameSet = createMap<string>();
bundledHelpers = isBundledEmit ? createMap<boolean>() : undefined;
isOwnFileEmit = !isBundledEmit;
// Emit helpers from all the files
if (isBundledEmit && moduleKind) {
for (const sourceFile of sourceFiles) {
emitEmitHelpers(sourceFile);
emitHelpers(sourceFile, /*isBundle*/ true);
}
}
@@ -314,7 +143,7 @@ const _super = (function (geti, seti) {
// Write the source map
if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) {
writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false);
writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles);
}
// Record source map data for the test harness.
@@ -323,7 +152,7 @@ const _super = (function (geti, seti) {
}
// Write the output file
writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM);
writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles);
// Reset state
sourceMap.reset();
@@ -333,11 +162,6 @@ const _super = (function (geti, seti) {
tempFlags = TempFlags.Auto;
currentSourceFile = undefined;
currentText = undefined;
extendsEmitted = false;
assignEmitted = false;
decorateEmitted = false;
paramEmitted = false;
awaiterEmitted = false;
isOwnFileEmit = false;
}
@@ -597,7 +421,9 @@ const _super = (function (geti, seti) {
case SyntaxKind.TypeOperator:
return emitTypeOperator(<TypeOperatorNode>node);
case SyntaxKind.IndexedAccessType:
return emitPropertyAccessType(<IndexedAccessTypeNode>node);
return emitIndexedAccessType(<IndexedAccessTypeNode>node);
case SyntaxKind.MappedType:
return emitMappedType(<MappedTypeNode>node);
case SyntaxKind.LiteralType:
return emitLiteralType(<LiteralTypeNode>node);
@@ -732,6 +558,8 @@ const _super = (function (geti, seti) {
return emitPropertyAssignment(<PropertyAssignment>node);
case SyntaxKind.ShorthandPropertyAssignment:
return emitShorthandPropertyAssignment(<ShorthandPropertyAssignment>node);
case SyntaxKind.SpreadAssignment:
return emitSpreadAssignment(node as SpreadAssignment);
// Enum
case SyntaxKind.EnumMember:
@@ -822,8 +650,8 @@ const _super = (function (geti, seti) {
return emitTemplateExpression(<TemplateExpression>node);
case SyntaxKind.YieldExpression:
return emitYieldExpression(<YieldExpression>node);
case SyntaxKind.SpreadElementExpression:
return emitSpreadElementExpression(<SpreadElementExpression>node);
case SyntaxKind.SpreadElement:
return emitSpreadExpression(<SpreadElement>node);
case SyntaxKind.ClassExpression:
return emitClassExpression(<ClassExpression>node);
case SyntaxKind.OmittedExpression:
@@ -842,6 +670,8 @@ const _super = (function (geti, seti) {
// Transformation nodes
case SyntaxKind.PartiallyEmittedExpression:
return emitPartiallyEmittedExpression(<PartiallyEmittedExpression>node);
case SyntaxKind.RawExpression:
return writeLines((<RawExpression>node).text);
}
}
@@ -879,12 +709,7 @@ const _super = (function (geti, seti) {
//
function emitIdentifier(node: Identifier) {
if (getEmitFlags(node) & EmitFlags.UMDDefine) {
writeLines(umdHelper);
}
else {
write(getTextOfNode(node, /*includeTrivia*/ false));
}
write(getTextOfNode(node, /*includeTrivia*/ false));
}
//
@@ -1098,13 +923,36 @@ const _super = (function (geti, seti) {
emit(node.type);
}
function emitPropertyAccessType(node: IndexedAccessTypeNode) {
function emitIndexedAccessType(node: IndexedAccessTypeNode) {
emit(node.objectType);
write("[");
emit(node.indexType);
write("]");
}
function emitMappedType(node: MappedTypeNode) {
write("{");
writeLine();
increaseIndent();
if (node.readonlyToken) {
write("readonly ");
}
write("[");
emit(node.typeParameter.name);
write(" in ");
emit(node.typeParameter.constraint);
write("]");
if (node.questionToken) {
write("?");
}
write(": ");
emit(node.type);
write(";");
writeLine();
decreaseIndent();
write("}");
}
function emitLiteralType(node: LiteralTypeNode) {
emitExpression(node.literal);
}
@@ -1374,7 +1222,7 @@ const _super = (function (geti, seti) {
emitExpressionWithPrefix(" ", node.expression);
}
function emitSpreadElementExpression(node: SpreadElementExpression) {
function emitSpreadExpression(node: SpreadElement) {
write("...");
emitExpression(node.expression);
}
@@ -2102,6 +1950,13 @@ const _super = (function (geti, seti) {
}
}
function emitSpreadAssignment(node: SpreadAssignment) {
if (node.expression) {
write("...");
emitExpression(node.expression);
}
}
//
// Enum
//
@@ -2158,85 +2013,39 @@ const _super = (function (geti, seti) {
return statements.length;
}
function emitHelpers(node: Node) {
const emitFlags = getEmitFlags(node);
let helpersEmitted = false;
if (emitFlags & EmitFlags.EmitEmitHelpers) {
helpersEmitted = emitEmitHelpers(currentSourceFile);
}
if (emitFlags & EmitFlags.EmitExportStar) {
writeLines(exportStarHelper);
helpersEmitted = true;
}
if (emitFlags & EmitFlags.EmitSuperHelper) {
writeLines(superHelper);
helpersEmitted = true;
}
if (emitFlags & EmitFlags.EmitAdvancedSuperHelper) {
writeLines(advancedSuperHelper);
helpersEmitted = true;
}
return helpersEmitted;
}
function emitEmitHelpers(node: SourceFile) {
// Only emit helpers if the user did not say otherwise.
if (compilerOptions.noEmitHelpers) {
return false;
}
// Don't emit helpers if we can import them.
if (compilerOptions.importHelpers
&& (isExternalModule(node) || compilerOptions.isolatedModules)) {
return false;
}
function emitHelpers(node: Node, isBundle?: boolean) {
const sourceFile = isSourceFile(node) ? node : currentSourceFile;
const shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && getExternalHelpersModuleName(sourceFile) !== undefined);
const shouldBundle = isSourceFile(node) && !isOwnFileEmit;
let helpersEmitted = false;
const helpers = getEmitHelpers(node);
if (helpers) {
for (const helper of stableSort(helpers, compareEmitHelpers)) {
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
// option is set.
if (shouldSkip) continue;
// Only Emit __extends function when target ES5.
// For target ES6 and above, we can emit classDeclaration as is.
if ((languageVersion < ScriptTarget.ES2015) && (!extendsEmitted && node.flags & NodeFlags.HasClassExtends)) {
writeLines(extendsHelper);
extendsEmitted = true;
helpersEmitted = true;
}
// Skip the helper if it can be bundled but hasn't already been emitted and we
// are emitting a bundled module.
if (shouldBundle) {
if (bundledHelpers[helper.name]) {
continue;
}
if (compilerOptions.jsx !== JsxEmit.Preserve && !assignEmitted && (node.flags & NodeFlags.HasJsxSpreadAttributes)) {
writeLines(assignHelper);
assignEmitted = true;
}
bundledHelpers[helper.name] = true;
}
}
else if (isBundle) {
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
if (!decorateEmitted && node.flags & NodeFlags.HasDecorators) {
writeLines(decorateHelper);
if (compilerOptions.emitDecoratorMetadata) {
writeLines(metadataHelper);
writeLines(helper.text);
helpersEmitted = true;
}
decorateEmitted = true;
helpersEmitted = true;
}
if (!paramEmitted && node.flags & NodeFlags.HasParamDecorators) {
writeLines(paramHelper);
paramEmitted = true;
helpersEmitted = true;
}
// 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.ES2015) {
writeLines(generatorHelper);
}
awaiterEmitted = true;
helpersEmitted = true;
}
if (helpersEmitted) {
@@ -2247,9 +2056,10 @@ const _super = (function (geti, seti) {
}
function writeLines(text: string): void {
const lines = text.split(/\r\n|\r|\n/g);
const lines = text.split(/\r\n?|\n/g);
const indentation = guessIndentation(lines);
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const line = indentation ? lines[i].slice(indentation) : lines[i];
if (line.length) {
if (i > 0) {
writeLine();
@@ -2259,6 +2069,21 @@ const _super = (function (geti, seti) {
}
}
function guessIndentation(lines: string[]) {
let indentation: number;
for (const line of lines) {
for (let i = 0; i < line.length && (indentation === undefined || i < indentation); i++) {
if (!isWhiteSpace(line.charCodeAt(i))) {
if (indentation === undefined || i < indentation) {
indentation = i;
break;
}
}
}
}
return indentation;
}
//
// Helpers
//
+706 -333
View File
File diff suppressed because it is too large Load Diff
+133 -128
View File
@@ -14,6 +14,11 @@ namespace ts {
return compilerOptions.traceResolution && host.trace !== undefined;
}
/** Array that is only intended to be pushed to, never read. */
interface Push<T> {
push(value: T): void;
}
/**
* Result of trying to resolve a module.
* At least one of `ts` and `js` should be defined, or the whole thing should be `undefined`.
@@ -56,14 +61,13 @@ namespace ts {
return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName: string): boolean {
export function moduleHasNonRelativeName(moduleName: string): boolean {
return !(isRootedDiskPath(moduleName) || isExternalModuleNameRelative(moduleName));
}
interface ModuleResolutionState {
host: ModuleResolutionHost;
// We only use this subset of the compiler options.
compilerOptions: { rootDirs?: string[], baseUrl?: string, paths?: MapLike<string[]> };
compilerOptions: CompilerOptions;
traceEnabled: boolean;
}
@@ -128,7 +132,9 @@ namespace ts {
currentDirectory = host.getCurrentDirectory();
}
return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host);
if (currentDirectory !== undefined) {
return getDefaultTypeRoots(currentDirectory, host);
}
}
/**
@@ -142,20 +148,12 @@ namespace ts {
}
let typeRoots: string[];
while (true) {
const atTypes = combinePaths(currentDirectory, nodeModulesAtTypes);
forEachAncestorDirectory(currentDirectory, directory => {
const atTypes = combinePaths(directory, nodeModulesAtTypes);
if (host.directoryExists(atTypes)) {
(typeRoots || (typeRoots = [])).push(atTypes);
}
const parent = getDirectoryPath(currentDirectory);
if (parent === currentDirectory) {
break;
}
currentDirectory = parent;
}
});
return typeRoots;
}
const nodeModulesAtTypes = combinePaths("node_modules", "@types");
@@ -195,63 +193,66 @@ namespace ts {
const failedLookupLocations: string[] = [];
// Check primary library paths
if (typeRoots && typeRoots.length) {
let resolved = primaryLookup();
let primary = true;
if (!resolved) {
resolved = secondaryLookup();
primary = false;
}
let resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined;
if (resolved) {
resolved = realpath(resolved, host, traceEnabled);
if (traceEnabled) {
trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary);
}
for (const typeRoot of typeRoots) {
const candidate = combinePaths(typeRoot, typeReferenceDirectiveName);
const candidateDirectory = getDirectoryPath(candidate);
resolvedTypeReferenceDirective = { primary, resolvedFileName: resolved };
}
const resolved = resolvedTypeScriptOnly(
loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations,
!directoryProbablyExists(candidateDirectory, host), moduleResolutionState));
return { resolvedTypeReferenceDirective, failedLookupLocations };
if (resolved) {
if (traceEnabled) {
trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, true);
}
return {
resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolved },
failedLookupLocations
};
function primaryLookup(): string | undefined {
// Check primary library paths
if (typeRoots && typeRoots.length) {
if (traceEnabled) {
trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
}
return forEach(typeRoots, typeRoot => {
const candidate = combinePaths(typeRoot, typeReferenceDirectiveName);
const candidateDirectory = getDirectoryPath(candidate);
return resolvedTypeScriptOnly(
loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations,
!directoryProbablyExists(candidateDirectory, host), moduleResolutionState));
});
}
else {
if (traceEnabled) {
trace(host, Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
}
}
}
else {
if (traceEnabled) {
trace(host, Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
}
}
let resolvedFile: string;
const initialLocationForSecondaryLookup = containingFile && getDirectoryPath(containingFile);
function secondaryLookup(): string | undefined {
let resolvedFile: string;
const initialLocationForSecondaryLookup = containingFile && getDirectoryPath(containingFile);
if (initialLocationForSecondaryLookup !== undefined) {
// check secondary locations
if (traceEnabled) {
trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
}
resolvedFile = resolvedTypeScriptOnly(loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*checkOneLevel*/ false));
if (traceEnabled) {
if (resolvedFile) {
trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false);
if (initialLocationForSecondaryLookup !== undefined) {
// check secondary locations
if (traceEnabled) {
trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
}
else {
resolvedFile = resolvedTypeScriptOnly(loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState));
if (!resolvedFile && traceEnabled) {
trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
}
return resolvedFile;
}
else {
if (traceEnabled) {
trace(host, Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
}
}
}
else {
if (traceEnabled) {
trace(host, Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
}
}
return {
resolvedTypeReferenceDirective: resolvedFile ? { primary: false, resolvedFileName: resolvedFile } : undefined,
failedLookupLocations
};
}
/**
@@ -341,7 +342,7 @@ namespace ts {
* 'typings' entry or file 'index' with some supported extension
* - Classic loader will only try to interpret '/a/b/c' as file.
*/
type ResolutionKindSpecificLoader = (extensions: Extensions, candidate: string, failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState) => Resolved | undefined;
type ResolutionKindSpecificLoader = (extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState) => Resolved | undefined;
/**
* Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
@@ -404,7 +405,7 @@ namespace ts {
* entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
*/
function tryLoadModuleUsingOptionalResolutionSettings(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader,
failedLookupLocations: string[], state: ModuleResolutionState): Resolved | undefined {
failedLookupLocations: Push<string>, state: ModuleResolutionState): Resolved | undefined {
if (moduleHasNonRelativeName(moduleName)) {
return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state);
@@ -415,7 +416,7 @@ namespace ts {
}
function tryLoadModuleUsingRootDirs(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader,
failedLookupLocations: string[], state: ModuleResolutionState): Resolved | undefined {
failedLookupLocations: Push<string>, state: ModuleResolutionState): Resolved | undefined {
if (!state.compilerOptions.rootDirs) {
return undefined;
@@ -491,7 +492,7 @@ namespace ts {
return undefined;
}
function tryLoadModuleUsingBaseUrl(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[], state: ModuleResolutionState): Resolved | undefined {
function tryLoadModuleUsingBaseUrl(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: Push<string>, state: ModuleResolutionState): Resolved | undefined {
if (!state.compilerOptions.baseUrl) {
return undefined;
}
@@ -514,18 +515,21 @@ namespace ts {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
}
for (const subst of state.compilerOptions.paths[matchedPatternText]) {
return forEach(state.compilerOptions.paths[matchedPatternText], subst => {
const path = matchedStar ? subst.replace("*", matchedStar) : subst;
const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, path));
if (state.traceEnabled) {
trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
}
const resolved = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
if (resolved) {
return resolved;
// A path mapping may have a ".ts" extension; in contrast to an import, which should omit it.
const tsExtension = tryGetExtensionFromPath(candidate);
if (tsExtension !== undefined) {
const path = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/false, state);
return path && { path, extension: tsExtension };
}
}
return undefined;
return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
});
}
else {
const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, moduleName));
@@ -548,7 +552,7 @@ namespace ts {
const result = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
if (result) {
const { resolved, isExternalLibraryImport } = result;
return createResolvedModuleWithFailedLookupLocations(resolved && resolvedWithRealpath(resolved, host, traceEnabled), isExternalLibraryImport, failedLookupLocations);
return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations);
}
return { resolvedModule: undefined, failedLookupLocations };
@@ -562,8 +566,9 @@ namespace ts {
if (traceEnabled) {
trace(host, Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
}
const resolved = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, /*checkOneLevel*/ false);
return resolved && { resolved, isExternalLibraryImport: true };
const resolved = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state);
// For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
return resolved && { resolved: { path: realpath(resolved.path, host, traceEnabled), extension: resolved.extension }, isExternalLibraryImport: true };
}
else {
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
@@ -573,19 +578,19 @@ namespace ts {
}
}
function resolvedWithRealpath(resolved: Resolved, host: ModuleResolutionHost, traceEnabled: boolean): Resolved {
function realpath(path: string, host: ModuleResolutionHost, traceEnabled: boolean): string {
if (!host.realpath) {
return resolved;
return path;
}
const real = normalizePath(host.realpath(resolved.path));
const real = normalizePath(host.realpath(path));
if (traceEnabled) {
trace(host, Diagnostics.Resolving_real_path_for_0_result_1, resolved.path, real);
trace(host, Diagnostics.Resolving_real_path_for_0_result_1, path, real);
}
return { path: real, extension: resolved.extension };
return real;
}
function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
}
@@ -604,7 +609,7 @@ namespace ts {
* @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
*/
function loadModuleFromFile(extensions: Extensions, candidate: string, failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
function loadModuleFromFile(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
// First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state);
if (resolvedByAddingExtension) {
@@ -624,7 +629,7 @@ namespace ts {
}
/** Try to return an existing file that adds one of the `extensions` to `candidate`. */
function tryAddingExtensions(candidate: string, extensions: Extensions, failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
function tryAddingExtensions(candidate: string, extensions: Extensions, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
if (!onlyRecordFailures) {
// check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
const directory = getDirectoryPath(candidate);
@@ -649,7 +654,7 @@ namespace ts {
}
/** Return the file if it exists. */
function tryFile(fileName: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined {
function tryFile(fileName: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined {
if (!onlyRecordFailures && state.host.fileExists(fileName)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
@@ -660,12 +665,12 @@ namespace ts {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_does_not_exist, fileName);
}
failedLookupLocation.push(fileName);
failedLookupLocations.push(fileName);
return undefined;
}
}
function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
const packageJsonPath = pathToPackageJson(candidate);
const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
@@ -677,12 +682,12 @@ namespace ts {
if (typesFile) {
const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(typesFile), state.host);
// A package.json "typings" may specify an exact filename, or may choose to omit an extension.
const fromFile = tryFile(typesFile, failedLookupLocation, onlyRecordFailures, state);
const fromFile = tryFile(typesFile, failedLookupLocations, onlyRecordFailures, state);
if (fromFile) {
// Note: this would allow a package.json to specify a ".js" file as typings. Maybe that should be forbidden.
return resolvedFromAnyFile(fromFile);
}
const x = tryAddingExtensions(typesFile, Extensions.TypeScript, failedLookupLocation, onlyRecordFailures, state);
const x = tryAddingExtensions(typesFile, Extensions.TypeScript, failedLookupLocations, onlyRecordFailures, state);
if (x) {
return x;
}
@@ -698,17 +703,17 @@ namespace ts {
trace(state.host, Diagnostics.File_0_does_not_exist, packageJsonPath);
}
// record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
failedLookupLocation.push(packageJsonPath);
failedLookupLocations.push(packageJsonPath);
}
return loadModuleFromFile(extensions, combinePaths(candidate, "index"), failedLookupLocation, !directoryExists, state);
return loadModuleFromFile(extensions, combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state);
}
function pathToPackageJson(directory: string): string {
return combinePaths(directory, "package.json");
}
function loadModuleFromNodeModulesFolder(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): Resolved | undefined {
function loadModuleFromNodeModulesFolder(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push<string>, state: ModuleResolutionState): Resolved | undefined {
const nodeModulesFolder = combinePaths(directory, "node_modules");
const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName));
@@ -717,34 +722,30 @@ namespace ts {
loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
}
function loadModuleFromNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState, checkOneLevel: boolean): Resolved | undefined {
return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, checkOneLevel, /*typesOnly*/ false);
function loadModuleFromNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push<string>, state: ModuleResolutionState): Resolved | undefined {
return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false);
}
function loadModuleFromNodeModulesAtTypes(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): Resolved | undefined {
return loadModuleFromNodeModulesWorker(Extensions.TypeScript, moduleName, directory, failedLookupLocations, state, /*checkOneLevel*/ false, /*typesOnly*/ true);
function loadModuleFromNodeModulesAtTypes(moduleName: string, directory: string, failedLookupLocations: Push<string>, state: ModuleResolutionState): Resolved | undefined {
// Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true);
}
function loadModuleFromNodeModulesWorker(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState, checkOneLevel: boolean, typesOnly: boolean): Resolved | undefined {
directory = normalizeSlashes(directory);
while (true) {
if (getBaseFileName(directory) !== "node_modules") {
const resolved = tryInDirectory();
if (resolved) {
return resolved;
}
function loadModuleFromNodeModulesWorker(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push<string>, state: ModuleResolutionState, typesOnly: boolean): Resolved | undefined {
return forEachAncestorDirectory(normalizeSlashes(directory), ancestorDirectory => {
if (getBaseFileName(ancestorDirectory) !== "node_modules") {
return loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly);
}
});
}
const parentPath = getDirectoryPath(directory);
if (parentPath === directory || checkOneLevel) {
return undefined;
}
directory = parentPath;
/** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */
function loadModuleFromNodeModulesOneLevel(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push<string>, state: ModuleResolutionState, typesOnly = false): Resolved | undefined {
const packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state);
if (packageResult) {
return packageResult;
}
function tryInDirectory(): Resolved | undefined {
const packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state);
return packageResult || loadModuleFromNodeModulesFolder(extensions, combinePaths("@types", moduleName), directory, failedLookupLocations, state);
if (extensions !== Extensions.JavaScript) {
return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, combinePaths("@types", moduleName), directory, failedLookupLocations, state);
}
}
@@ -764,7 +765,11 @@ namespace ts {
}
if (moduleHasNonRelativeName(moduleName)) {
const resolved = loadModuleFromAncestorDirectories(extensions, moduleName, containingDirectory, failedLookupLocations, state);
// Climb up parent directories looking for a module.
const resolved = forEachAncestorDirectory(containingDirectory, directory => {
const searchName = normalizePath(combinePaths(directory, moduleName));
return loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state);
});
if (resolved) {
return resolved;
}
@@ -780,22 +785,6 @@ namespace ts {
}
}
/** Climb up parent directories looking for a module. */
function loadModuleFromAncestorDirectories(extensions: Extensions, moduleName: string, containingDirectory: string, failedLookupLocations: string[], state: ModuleResolutionState): Resolved | undefined {
while (true) {
const searchName = normalizePath(combinePaths(containingDirectory, moduleName));
const referencedSourceFile = loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state);
if (referencedSourceFile) {
return referencedSourceFile;
}
const parentPath = getDirectoryPath(containingDirectory);
if (parentPath === containingDirectory) {
return undefined;
}
containingDirectory = parentPath;
}
}
/**
* LSHost may load a module from a global cache of typings.
* This is the minumum code needed to expose that functionality; the rest is in LSHost.
@@ -808,8 +797,24 @@ namespace ts {
}
const state: ModuleResolutionState = { compilerOptions, host, traceEnabled };
const failedLookupLocations: string[] = [];
const resolved = loadModuleFromNodeModules(Extensions.TypeScript, moduleName, globalCache, failedLookupLocations, state, /*checkOneLevel*/ true) ||
loadModuleFromNodeModules(Extensions.JavaScript, moduleName, globalCache, failedLookupLocations, state, /*checkOneLevel*/ true);
const resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state);
return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations);
}
/** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */
function forEachAncestorDirectory<T>(directory: string, callback: (directory: string) => T | undefined): T | undefined {
while (true) {
const result = callback(directory);
if (result !== undefined) {
return result;
}
const parentPath = getDirectoryPath(directory);
if (parentPath === directory) {
return undefined;
}
directory = parentPath;
}
}
}
+104 -19
View File
@@ -74,6 +74,8 @@ namespace ts {
visitNode(cbNode, (<ShorthandPropertyAssignment>node).questionToken) ||
visitNode(cbNode, (<ShorthandPropertyAssignment>node).equalsToken) ||
visitNode(cbNode, (<ShorthandPropertyAssignment>node).objectAssignmentInitializer);
case SyntaxKind.SpreadAssignment:
return visitNode(cbNode, (<SpreadAssignment>node).expression);
case SyntaxKind.Parameter:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
@@ -139,6 +141,11 @@ namespace ts {
case SyntaxKind.IndexedAccessType:
return visitNode(cbNode, (<IndexedAccessTypeNode>node).objectType) ||
visitNode(cbNode, (<IndexedAccessTypeNode>node).indexType);
case SyntaxKind.MappedType:
return visitNode(cbNode, (<MappedTypeNode>node).readonlyToken) ||
visitNode(cbNode, (<MappedTypeNode>node).typeParameter) ||
visitNode(cbNode, (<MappedTypeNode>node).questionToken) ||
visitNode(cbNode, (<MappedTypeNode>node).type);
case SyntaxKind.LiteralType:
return visitNode(cbNode, (<LiteralTypeNode>node).literal);
case SyntaxKind.ObjectBindingPattern:
@@ -197,8 +204,8 @@ namespace ts {
visitNode(cbNode, (<ConditionalExpression>node).whenTrue) ||
visitNode(cbNode, (<ConditionalExpression>node).colonToken) ||
visitNode(cbNode, (<ConditionalExpression>node).whenFalse);
case SyntaxKind.SpreadElementExpression:
return visitNode(cbNode, (<SpreadElementExpression>node).expression);
case SyntaxKind.SpreadElement:
return visitNode(cbNode, (<SpreadElement>node).expression);
case SyntaxKind.Block:
case SyntaxKind.ModuleBlock:
return visitNodes(cbNodes, (<Block>node).statements);
@@ -411,6 +418,8 @@ namespace ts {
return visitNode(cbNode, (<JSDocReturnTag>node).typeExpression);
case SyntaxKind.JSDocTypeTag:
return visitNode(cbNode, (<JSDocTypeTag>node).typeExpression);
case SyntaxKind.JSDocAugmentsTag:
return visitNode(cbNode, (<JSDocAugmentsTag>node).typeExpression);
case SyntaxKind.JSDocTemplateTag:
return visitNodes(cbNodes, (<JSDocTemplateTag>node).typeParameters);
case SyntaxKind.JSDocTypedefTag:
@@ -438,6 +447,10 @@ namespace ts {
return result;
}
export function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName {
return Parser.parseIsolatedEntityName(text, languageVersion);
}
export function isExternalModule(file: SourceFile): boolean {
return file.externalModuleIndicator !== undefined;
}
@@ -589,6 +602,16 @@ namespace ts {
return result;
}
export function parseIsolatedEntityName(content: string, languageVersion: ScriptTarget): EntityName {
initializeState(content, languageVersion, /*syntaxCursor*/ undefined, ScriptKind.JS);
// Prime the scanner.
nextToken();
const entityName = parseEntityName(/*allowReservedWords*/ true);
const isInvalid = token() === SyntaxKind.EndOfFileToken && !parseDiagnostics.length;
clearState();
return isInvalid ? entityName : undefined;
}
function getLanguageVariant(scriptKind: ScriptKind) {
// .tsx and .jsx files are treated as jsx language variant.
return scriptKind === ScriptKind.TSX || scriptKind === ScriptKind.JSX || scriptKind === ScriptKind.JS ? LanguageVariant.JSX : LanguageVariant.Standard;
@@ -660,7 +683,7 @@ namespace ts {
function addJSDocComment<T extends Node>(node: T): T {
const comments = getJsDocCommentsFromText(node, sourceFile.text);
const comments = getJSDocCommentRanges(node, sourceFile.text);
if (comments) {
for (const comment of comments) {
const jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos);
@@ -668,10 +691,10 @@ namespace ts {
continue;
}
if (!node.jsDocComments) {
node.jsDocComments = [];
if (!node.jsDoc) {
node.jsDoc = [];
}
node.jsDocComments.push(jsDoc);
node.jsDoc.push(jsDoc);
}
}
@@ -698,11 +721,11 @@ namespace ts {
const saveParent = parent;
parent = n;
forEachChild(n, visitNode);
if (n.jsDocComments) {
for (const jsDocComment of n.jsDocComments) {
jsDocComment.parent = n;
parent = jsDocComment;
forEachChild(jsDocComment, visitNode);
if (n.jsDoc) {
for (const jsDoc of n.jsDoc) {
jsDoc.parent = n;
parent = jsDoc;
forEachChild(jsDoc, visitNode);
}
}
parent = saveParent;
@@ -1147,7 +1170,7 @@ namespace ts {
function parsePropertyNameWorker(allowComputedPropertyNames: boolean): PropertyName {
if (token() === SyntaxKind.StringLiteral || token() === SyntaxKind.NumericLiteral) {
return parseLiteralNode(/*internName*/ true);
return <StringLiteral | NumericLiteral>parseLiteralNode(/*internName*/ true);
}
if (allowComputedPropertyNames && token() === SyntaxKind.OpenBracketToken) {
return parseComputedPropertyName();
@@ -1269,9 +1292,11 @@ namespace ts {
// which would be a candidate for improved error reporting.
return token() === SyntaxKind.OpenBracketToken || isLiteralPropertyName();
case ParsingContext.ObjectLiteralMembers:
return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.AsteriskToken || isLiteralPropertyName();
return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.AsteriskToken || token() === SyntaxKind.DotDotDotToken || isLiteralPropertyName();
case ParsingContext.RestProperties:
return isLiteralPropertyName();
case ParsingContext.ObjectBindingElements:
return token() === SyntaxKind.OpenBracketToken || isLiteralPropertyName();
return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.DotDotDotToken || isLiteralPropertyName();
case ParsingContext.HeritageClauseElement:
// If we see { } then only consume it as an expression if it is followed by , or {
// That way we won't consume the body of a class in its heritage clause.
@@ -1398,6 +1423,7 @@ namespace ts {
case ParsingContext.ArrayBindingElements:
return token() === SyntaxKind.CloseBracketToken;
case ParsingContext.Parameters:
case ParsingContext.RestProperties:
// 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:
@@ -1583,6 +1609,9 @@ namespace ts {
case ParsingContext.Parameters:
return isReusableParameter(node);
case ParsingContext.RestProperties:
return false;
// Any other lists we do not care about reusing nodes in. But feel free to add if
// you can do so safely. Danger areas involve nodes that may involve speculative
// parsing. If speculative parsing is involved with the node, then the range the
@@ -1780,6 +1809,7 @@ namespace ts {
case ParsingContext.BlockStatements: return Diagnostics.Declaration_or_statement_expected;
case ParsingContext.SwitchClauses: return Diagnostics.case_or_default_expected;
case ParsingContext.SwitchClauseStatements: return Diagnostics.Statement_expected;
case ParsingContext.RestProperties: // fallthrough
case ParsingContext.TypeMembers: return Diagnostics.Property_or_signature_expected;
case ParsingContext.ClassMembers: return Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
case ParsingContext.EnumMembers: return Diagnostics.Enum_member_expected;
@@ -2399,6 +2429,36 @@ namespace ts {
return members;
}
function isStartOfMappedType() {
nextToken();
if (token() === SyntaxKind.ReadonlyKeyword) {
nextToken();
}
return token() === SyntaxKind.OpenBracketToken && nextTokenIsIdentifier() && nextToken() === SyntaxKind.InKeyword;
}
function parseMappedTypeParameter() {
const node = <TypeParameterDeclaration>createNode(SyntaxKind.TypeParameter);
node.name = parseIdentifier();
parseExpected(SyntaxKind.InKeyword);
node.constraint = parseType();
return finishNode(node);
}
function parseMappedType() {
const node = <MappedTypeNode>createNode(SyntaxKind.MappedType);
parseExpected(SyntaxKind.OpenBraceToken);
node.readonlyToken = parseOptionalToken(SyntaxKind.ReadonlyKeyword);
parseExpected(SyntaxKind.OpenBracketToken);
node.typeParameter = parseMappedTypeParameter();
parseExpected(SyntaxKind.CloseBracketToken);
node.questionToken = parseOptionalToken(SyntaxKind.QuestionToken);
node.type = parseTypeAnnotation();
parseSemicolon();
parseExpected(SyntaxKind.CloseBraceToken);
return finishNode(node);
}
function parseTupleType(): TupleTypeNode {
const node = <TupleTypeNode>createNode(SyntaxKind.TupleType);
node.elementTypes = parseBracketedList(ParsingContext.TupleElementTypes, parseType, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken);
@@ -2472,7 +2532,7 @@ namespace ts {
case SyntaxKind.TypeOfKeyword:
return parseTypeQuery();
case SyntaxKind.OpenBraceToken:
return parseTypeLiteral();
return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
case SyntaxKind.OpenBracketToken:
return parseTupleType();
case SyntaxKind.OpenParenToken:
@@ -2498,6 +2558,8 @@ namespace ts {
case SyntaxKind.OpenBraceToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.LessThanToken:
case SyntaxKind.BarToken:
case SyntaxKind.AmpersandToken:
case SyntaxKind.NewKeyword:
case SyntaxKind.StringLiteral:
case SyntaxKind.NumericLiteral:
@@ -2557,6 +2619,7 @@ namespace ts {
}
function parseUnionOrIntersectionType(kind: SyntaxKind, parseConstituentType: () => TypeNode, operator: SyntaxKind): TypeNode {
parseOptional(operator);
let type = parseConstituentType();
if (token() === operator) {
const types = createNodeArray<TypeNode>([type], type.pos);
@@ -4122,7 +4185,7 @@ namespace ts {
}
function parseSpreadElement(): Expression {
const node = <SpreadElementExpression>createNode(SyntaxKind.SpreadElementExpression);
const node = <SpreadElement>createNode(SyntaxKind.SpreadElement);
parseExpected(SyntaxKind.DotDotDotToken);
node.expression = parseAssignmentExpressionOrHigher();
return finishNode(node);
@@ -4162,6 +4225,12 @@ namespace ts {
function parseObjectLiteralElement(): ObjectLiteralElementLike {
const fullStart = scanner.getStartPos();
const dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken);
if (dotDotDotToken) {
const spreadElement = <SpreadAssignment>createNode(SyntaxKind.SpreadAssignment, fullStart);
spreadElement.expression = parseAssignmentExpressionOrHigher();
return addJSDocComment(finishNode(spreadElement));
}
const decorators = parseDecorators();
const modifiers = parseModifiers();
@@ -4865,6 +4934,7 @@ namespace ts {
function parseObjectBindingElement(): BindingElement {
const node = <BindingElement>createNode(SyntaxKind.BindingElement);
node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken);
const tokenIsIdentifier = isIdentifier();
const propertyName = parsePropertyName();
if (tokenIsIdentifier && token() !== SyntaxKind.ColonToken) {
@@ -5449,7 +5519,7 @@ namespace ts {
node.flags |= NodeFlags.GlobalAugmentation;
}
else {
node.name = parseLiteralNode(/*internName*/ true);
node.name = <StringLiteral>parseLiteralNode(/*internName*/ true);
}
if (token() === SyntaxKind.OpenBraceToken) {
@@ -5809,6 +5879,7 @@ namespace ts {
JsxChildren, // Things between opening and closing JSX tags
ArrayLiteralMembers, // Members in array literal
Parameters, // Parameters in parameter list
RestProperties, // Property names in a rest type list
TypeParameters, // Type parameters in type parameter list
TypeArguments, // Type arguments in type argument list
TupleElementTypes, // Element types in tuple element type list
@@ -6238,6 +6309,7 @@ namespace ts {
}
if (token() === SyntaxKind.NewLineTrivia) {
state = JSDocState.BeginningOfLine;
indent = 0;
nextJSDocToken();
}
while (token() !== SyntaxKind.EndOfFileToken) {
@@ -6359,6 +6431,9 @@ namespace ts {
let tag: JSDocTag;
if (tagName) {
switch (tagName.text) {
case "augments":
tag = parseAugmentsTag(atToken, tagName);
break;
case "param":
tag = parseParamTag(atToken, tagName);
break;
@@ -6575,6 +6650,16 @@ namespace ts {
return finishNode(result);
}
function parseAugmentsTag(atToken: AtToken, tagName: Identifier): JSDocAugmentsTag {
const typeExpression = tryParseTypeExpression();
const result = <JSDocAugmentsTag>createNode(SyntaxKind.JSDocAugmentsTag, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = typeExpression;
return finishNode(result);
}
function parseTypedefTag(atToken: AtToken, tagName: Identifier): JSDocTypedefTag {
const typeExpression = tryParseTypeExpression();
skipWhitespace();
@@ -6887,8 +6972,8 @@ namespace ts {
}
forEachChild(node, visitNode, visitArray);
if (node.jsDocComments) {
for (const jsDocComment of node.jsDocComments) {
if (node.jsDoc) {
for (const jsDocComment of node.jsDoc) {
forEachChild(jsDocComment, visitNode, visitArray);
}
}
+201 -171
View File
@@ -3,10 +3,6 @@
/// <reference path="core.ts" />
namespace ts {
/** The version of the TypeScript compiler release */
export const version = "2.1.0";
const emptyArray: any[] = [];
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName = "tsconfig.json"): string {
@@ -239,11 +235,11 @@ namespace ts {
const { line, character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
const fileName = diagnostic.file.fileName;
const relativeFileName = convertToRelativePath(fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName));
output += `${ relativeFileName }(${ line + 1 },${ character + 1 }): `;
output += `${relativeFileName}(${line + 1},${character + 1}): `;
}
const category = DiagnosticCategory[diagnostic.category].toLowerCase();
output += `${ category } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) }${ host.getNewLine() }`;
output += `${category} TS${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())}${host.getNewLine()}`;
}
return output;
}
@@ -368,7 +364,8 @@ namespace ts {
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 containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
const containingFilename = combinePaths(containingDirectory, "__inferred type names__.ts");
const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
for (let i = 0; i < typeReferences.length; i++) {
processTypeReferenceDirective(typeReferences[i], resolutions[i]);
@@ -420,6 +417,7 @@ namespace ts {
getTypeCount: () => getDiagnosticsProducingTypeChecker().getTypeCount(),
getFileProcessingDiagnostics: () => fileProcessingDiagnostics,
getResolvedTypeReferenceDirectives: () => resolvedTypeReferenceDirectives,
isSourceFileFromExternalLibrary,
dropDiagnosticsProducingTypeChecker
};
@@ -430,13 +428,14 @@ namespace ts {
return program;
function getCommonSourceDirectory() {
if (typeof commonSourceDirectory === "undefined") {
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
if (commonSourceDirectory === undefined) {
const emittedFiles = filterSourceFilesInDirectory(files, isSourceFileFromExternalLibrary);
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
// If a rootDir is specified and is valid use it as the commonSourceDirectory
commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
else {
commonSourceDirectory = computeCommonSourceDirectory(files);
commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
}
if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) {
// Make sure directory path ends with directory separator so this string can directly
@@ -475,7 +474,7 @@ namespace ts {
return resolveModuleNamesWorker(moduleNames, containingFile);
}
// at this point we know that either
// at this point we know that either
// - file has local declarations for ambient modules
// OR
// - old program state is available
@@ -669,7 +668,7 @@ namespace ts {
}
const modifiedFilePaths = modifiedSourceFiles.map(f => f.newFile.path);
// try to verify results of module resolution
// try to verify results of module resolution
for (const { oldFile: oldSourceFile, newFile: newSourceFile } of modifiedSourceFiles) {
const newSourceFilePath = getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory);
if (resolveModuleNamesWorker) {
@@ -722,13 +721,17 @@ namespace ts {
getSourceFile: program.getSourceFile,
getSourceFileByPath: program.getSourceFileByPath,
getSourceFiles: program.getSourceFiles,
isSourceFileFromExternalLibrary: (file: SourceFile) => !!sourceFilesFoundSearchingNodeModules[file.path],
isSourceFileFromExternalLibrary,
writeFile: writeFileCallback || (
(fileName, data, writeByteOrderMark, onError, sourceFiles) => host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles)),
isEmitBlocked,
};
}
function isSourceFileFromExternalLibrary(file: SourceFile): boolean {
return sourceFilesFoundSearchingNodeModules[file.path];
}
function getDiagnosticsProducingTypeChecker() {
return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ true));
}
@@ -903,48 +906,24 @@ namespace ts {
function getJavaScriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] {
return runWithCancellationToken(() => {
const diagnostics: Diagnostic[] = [];
let parent: Node = sourceFile;
walk(sourceFile);
return diagnostics;
function walk(node: Node): boolean {
if (!node) {
return false;
}
function walk(node: Node) {
// Return directly from the case if the given node doesnt want to visit each child
// Otherwise break to visit each child
switch (node.kind) {
case SyntaxKind.ImportEqualsDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.ExportAssignment:
if ((<ExportAssignment>node).isExportEquals) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_a_ts_file));
return true;
switch (parent.kind) {
case SyntaxKind.Parameter:
case SyntaxKind.PropertyDeclaration:
if ((<ParameterDeclaration | PropertyDeclaration>parent).questionToken === node) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics._0_can_only_be_used_in_a_ts_file, "?"));
return;
}
break;
case SyntaxKind.ClassDeclaration:
let classDeclaration = <ClassDeclaration>node;
if (checkModifiers(classDeclaration.modifiers) ||
checkTypeParameters(classDeclaration.typeParameters)) {
return true;
}
break;
case SyntaxKind.HeritageClause:
let heritageClause = <HeritageClause>node;
if (heritageClause.token === SyntaxKind.ImplementsKeyword) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file));
return true;
}
break;
case SyntaxKind.InterfaceDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.ModuleDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.module_declarations_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.TypeAliasDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.type_aliases_can_only_be_used_in_a_ts_file));
return true;
// Pass through
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.Constructor:
@@ -954,124 +933,151 @@ namespace ts {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ArrowFunction:
case SyntaxKind.FunctionDeclaration:
const functionDeclaration = <FunctionLikeDeclaration>node;
if (checkModifiers(functionDeclaration.modifiers) ||
checkTypeParameters(functionDeclaration.typeParameters) ||
checkTypeAnnotation(functionDeclaration.type)) {
return true;
}
break;
case SyntaxKind.VariableStatement:
const variableStatement = <VariableStatement>node;
if (checkModifiers(variableStatement.modifiers)) {
return true;
}
break;
case SyntaxKind.VariableDeclaration:
const variableDeclaration = <VariableDeclaration>node;
if (checkTypeAnnotation(variableDeclaration.type)) {
return true;
// type annotation
if ((<FunctionLikeDeclaration | VariableDeclaration | ParameterDeclaration | PropertyDeclaration>parent).type === node) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.types_can_only_be_used_in_a_ts_file));
return;
}
}
switch (node.kind) {
case SyntaxKind.ImportEqualsDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_a_ts_file));
return;
case SyntaxKind.ExportAssignment:
if ((<ExportAssignment>node).isExportEquals) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_a_ts_file));
return;
}
break;
case SyntaxKind.HeritageClause:
let heritageClause = <HeritageClause>node;
if (heritageClause.token === SyntaxKind.ImplementsKeyword) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file));
return;
}
break;
case SyntaxKind.InterfaceDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file));
return;
case SyntaxKind.ModuleDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.module_declarations_can_only_be_used_in_a_ts_file));
return;
case SyntaxKind.TypeAliasDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.type_aliases_can_only_be_used_in_a_ts_file));
return;
case SyntaxKind.EnumDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file));
return;
case SyntaxKind.TypeAssertionExpression:
let typeAssertionExpression = <TypeAssertion>node;
diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file));
return;
}
const prevParent = parent;
parent = node;
forEachChild(node, walk, walkArray);
parent = prevParent;
}
function walkArray(nodes: NodeArray<Node>) {
if (parent.decorators === nodes && !options.experimentalDecorators) {
diagnostics.push(createDiagnosticForNode(parent, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning));
}
switch (parent.kind) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ArrowFunction:
case SyntaxKind.FunctionDeclaration:
// Check type parameters
if (nodes === (<ClassDeclaration | FunctionLikeDeclaration>parent).typeParameters) {
diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file));
return;
}
// pass through
case SyntaxKind.VariableStatement:
// Check modifiers
if (nodes === (<ClassDeclaration | FunctionLikeDeclaration | VariableStatement>parent).modifiers) {
return checkModifiers(<NodeArray<Modifier>>nodes, parent.kind === SyntaxKind.VariableStatement);
}
break;
case SyntaxKind.PropertyDeclaration:
// Check modifiers of property declaration
if (nodes === (<PropertyDeclaration>parent).modifiers) {
for (const modifier of <NodeArray<Modifier>>nodes) {
if (modifier.kind !== SyntaxKind.StaticKeyword) {
diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind)));
}
}
return;
}
break;
case SyntaxKind.Parameter:
// Check modifiers of parameter declaration
if (nodes === (<ParameterDeclaration>parent).modifiers) {
diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file));
return;
}
break;
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
const expression = <CallExpression>node;
if (expression.typeArguments && expression.typeArguments.length > 0) {
const start = expression.typeArguments.pos;
diagnostics.push(createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start,
Diagnostics.type_arguments_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.ExpressionWithTypeArguments:
// Check type arguments
if (nodes === (<CallExpression | NewExpression | ExpressionWithTypeArguments>parent).typeArguments) {
diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.type_arguments_can_only_be_used_in_a_ts_file));
return;
}
break;
case SyntaxKind.Parameter:
const parameter = <ParameterDeclaration>node;
if (parameter.modifiers) {
const start = parameter.modifiers.pos;
diagnostics.push(createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start,
Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file));
return true;
}
if (parameter.questionToken) {
diagnostics.push(createDiagnosticForNode(parameter.questionToken, Diagnostics._0_can_only_be_used_in_a_ts_file, "?"));
return true;
}
if (parameter.type) {
diagnostics.push(createDiagnosticForNode(parameter.type, Diagnostics.types_can_only_be_used_in_a_ts_file));
return true;
}
break;
case SyntaxKind.PropertyDeclaration:
const propertyDeclaration = <PropertyDeclaration>node;
if (propertyDeclaration.modifiers) {
for (const modifier of propertyDeclaration.modifiers) {
if (modifier.kind !== SyntaxKind.StaticKeyword) {
diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind)));
return true;
}
}
for (const node of nodes) {
walk(node);
}
}
function checkModifiers(modifiers: NodeArray<Modifier>, isConstValid: boolean) {
for (const modifier of modifiers) {
switch (modifier.kind) {
case SyntaxKind.ConstKeyword:
if (isConstValid) {
continue;
}
}
if (checkTypeAnnotation((<PropertyDeclaration>node).type)) {
return true;
}
break;
case SyntaxKind.EnumDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.TypeAssertionExpression:
let typeAssertionExpression = <TypeAssertion>node;
diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.Decorator:
if (!options.experimentalDecorators) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning));
}
return true;
}
// Fallthrough to report error
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.ReadonlyKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.AbstractKeyword:
diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind)));
break;
return forEachChild(node, walk);
}
function checkTypeParameters(typeParameters: NodeArray<TypeParameterDeclaration>): boolean {
if (typeParameters) {
const start = typeParameters.pos;
diagnostics.push(createFileDiagnostic(sourceFile, start, typeParameters.end - start, Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file));
return true;
}
return false;
}
function checkTypeAnnotation(type: TypeNode): boolean {
if (type) {
diagnostics.push(createDiagnosticForNode(type, Diagnostics.types_can_only_be_used_in_a_ts_file));
return true;
}
return false;
}
function checkModifiers(modifiers: NodeArray<Modifier>): boolean {
if (modifiers) {
for (const modifier of modifiers) {
switch (modifier.kind) {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.ReadonlyKeyword:
case SyntaxKind.DeclareKeyword:
diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind)));
return true;
// These are all legal modifiers.
case SyntaxKind.StaticKeyword:
case SyntaxKind.ExportKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.AbstractKeyword:
}
// These are all legal modifiers.
case SyntaxKind.StaticKeyword:
case SyntaxKind.ExportKeyword:
case SyntaxKind.DefaultKeyword:
}
}
}
return false;
function createDiagnosticForNodeArray(nodes: NodeArray<Node>, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): Diagnostic {
const start = nodes.pos;
return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
}
// Since these are syntactic diagnostics, parent might not have been set
// this means the sourceFile cannot be infered from the node
function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): Diagnostic {
return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
}
});
}
@@ -1135,9 +1141,14 @@ namespace ts {
if (options.importHelpers
&& (options.isolatedModules || isExternalModuleFile)
&& !file.isDeclarationFile) {
const externalHelpersModuleReference = <StringLiteral>createNode(SyntaxKind.StringLiteral);
// synthesize 'import "tslib"' declaration
const externalHelpersModuleReference = <StringLiteral>createSynthesizedNode(SyntaxKind.StringLiteral);
externalHelpersModuleReference.text = externalHelpersModuleNameText;
externalHelpersModuleReference.parent = file;
const importDecl = createSynthesizedNode(SyntaxKind.ImportDeclaration);
importDecl.parent = file;
externalHelpersModuleReference.parent = importDecl;
imports = [externalHelpersModuleReference];
}
@@ -1390,14 +1401,17 @@ namespace ts {
// If we already resolved to this file, it must have been a secondary reference. Check file contents
// for sameness and possibly issue an error
if (previousResolution) {
const otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) {
fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd,
Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict,
typeReferenceDirective,
resolvedTypeReferenceDirective.resolvedFileName,
previousResolution.resolvedFileName
));
// Don't bother reading the file again if it's the same file.
if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
const otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) {
fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd,
Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict,
typeReferenceDirective,
resolvedTypeReferenceDirective.resolvedFileName,
previousResolution.resolvedFileName
));
}
}
// don't overwrite previous resolution result
saveResolution = false;
@@ -1434,7 +1448,9 @@ namespace ts {
collectExternalModuleReferences(file);
if (file.imports.length || file.moduleAugmentations.length) {
file.resolvedModules = createMap<ResolvedModuleFull>();
const moduleNames = map(concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral);
// Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
const nonGlobalAugmentation = filter(file.moduleAugmentations, (moduleAugmentation) => moduleAugmentation.kind === SyntaxKind.StringLiteral);
const moduleNames = map(concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral);
const resolutions = resolveModuleNamesReusingOldState(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory), file);
Debug.assert(resolutions.length === moduleNames.length);
for (let i = 0; i < moduleNames.length; i++) {
@@ -1665,7 +1681,15 @@ namespace ts {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
}
if (options.reactNamespace && !isIdentifierText(options.reactNamespace, languageVersion)) {
if (options.jsxFactory) {
if (options.reactNamespace) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"));
}
if (!parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory));
}
}
else if (options.reactNamespace && !isIdentifierText(options.reactNamespace, languageVersion)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace));
}
@@ -1685,13 +1709,19 @@ namespace ts {
const emitFilePath = toPath(emitFileName, currentDirectory, getCanonicalFileName);
// Report error if the output overwrites input file
if (filesByName.contains(emitFilePath)) {
createEmitBlockingDiagnostics(emitFileName, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file);
let chain: DiagnosticMessageChain;
if (!options.configFilePath) {
// The program is from either an inferred project or an external project
chain = chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig);
}
chain = chainDiagnosticMessages(chain, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
blockEmittingOfFile(emitFileName, createCompilerDiagnosticFromMessageChain(chain));
}
// Report error if multiple files write into same file
if (emitFilesSeen.contains(emitFilePath)) {
// Already seen the same emit file - report error
createEmitBlockingDiagnostics(emitFileName, Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files);
blockEmittingOfFile(emitFileName, createCompilerDiagnostic(Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
}
else {
emitFilesSeen.set(emitFilePath, true);
@@ -1700,9 +1730,9 @@ namespace ts {
}
}
function createEmitBlockingDiagnostics(emitFileName: string, message: DiagnosticMessage) {
function blockEmittingOfFile(emitFileName: string, diag: Diagnostic) {
hasEmitBlockingDiagnostics.set(toPath(emitFileName, currentDirectory, getCanonicalFileName), true);
programDiagnostics.add(createCompilerDiagnostic(message, emitFileName));
programDiagnostics.add(diag);
}
}
+9 -4
View File
@@ -17,7 +17,11 @@ namespace ts {
readFile(path: string, encoding?: string): string;
getFileSize?(path: string): number;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
/**
* @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that
* use native OS file watching
*/
watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
@@ -439,6 +443,7 @@ namespace ts {
return filter<string>(_fs.readdirSync(path), dir => fileSystemEntryExists(combinePaths(path, dir), FileSystemEntryKind.Directory));
}
const noOpFileWatcher: FileWatcher = { close: noop };
const nodeSystem: System = {
args: process.argv.slice(2),
newLine: _os.EOL,
@@ -448,7 +453,7 @@ namespace ts {
},
readFile,
writeFile,
watchFile: (fileName, callback) => {
watchFile: (fileName, callback, pollingInterval) => {
if (useNonPollingWatchers) {
const watchedFile = watchedFileSet.addFile(fileName, callback);
return {
@@ -456,7 +461,7 @@ namespace ts {
};
}
else {
_fs.watchFile(fileName, { persistent: true, interval: 250 }, fileChanged);
_fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged);
return {
close: () => _fs.unwatchFile(fileName, fileChanged)
};
@@ -475,7 +480,7 @@ namespace ts {
// (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
let options: any;
if (!directoryExists(directoryName)) {
return;
return noOpFileWatcher;
}
if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) {
+70 -102
View File
@@ -1,6 +1,7 @@
/// <reference path="visitor.ts" />
/// <reference path="transformers/ts.ts" />
/// <reference path="transformers/jsx.ts" />
/// <reference path="transformers/esnext.ts" />
/// <reference path="transformers/es2017.ts" />
/// <reference path="transformers/es2016.ts" />
/// <reference path="transformers/es2015.ts" />
@@ -26,84 +27,6 @@ namespace ts {
EmitNotifications = 1 << 1,
}
export interface TransformationResult {
/**
* Gets the transformed source files.
*/
transformed: SourceFile[];
/**
* Emits the substitute for a node, if one is available; otherwise, emits the node.
*
* @param emitContext The current emit context.
* @param node The node to substitute.
* @param emitCallback A callback used to emit the node or its substitute.
*/
emitNodeWithSubstitution(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void;
/**
* Emits a node with possible notification.
*
* @param emitContext The current emit context.
* @param node The node to emit.
* @param emitCallback A callback used to emit the node.
*/
emitNodeWithNotification(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void;
}
export interface TransformationContext extends LexicalEnvironment {
getCompilerOptions(): CompilerOptions;
getEmitResolver(): EmitResolver;
getEmitHost(): EmitHost;
/**
* Hoists a function declaration to the containing scope.
*/
hoistFunctionDeclaration(node: FunctionDeclaration): void;
/**
* Hoists a variable declaration to the containing scope.
*/
hoistVariableDeclaration(node: Identifier): void;
/**
* Enables expression substitutions in the pretty printer for the provided SyntaxKind.
*/
enableSubstitution(kind: SyntaxKind): void;
/**
* Determines whether expression substitutions are enabled for the provided node.
*/
isSubstitutionEnabled(node: Node): boolean;
/**
* Hook used by transformers to substitute expressions just before they
* are emitted by the pretty printer.
*/
onSubstituteNode?: (emitContext: EmitContext, node: Node) => Node;
/**
* Enables before/after emit notifications in the pretty printer for the provided
* SyntaxKind.
*/
enableEmitNotification(kind: SyntaxKind): void;
/**
* Determines whether before/after emit notifications should be raised in the pretty
* printer when it emits a node.
*/
isEmitNotificationEnabled(node: Node): boolean;
/**
* Hook used to allow transformers to capture state before or after
* the printer emits a node.
*/
onEmitNode?: (emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) => void;
}
/* @internal */
export type Transformer = (context: TransformationContext) => (node: SourceFile) => SourceFile;
export function getTransformers(compilerOptions: CompilerOptions) {
const jsx = compilerOptions.jsx;
const languageVersion = getEmitScriptTarget(compilerOptions);
@@ -116,6 +39,10 @@ namespace ts {
transformers.push(transformJsx);
}
if (languageVersion < ScriptTarget.ESNext) {
transformers.push(transformESNext);
}
if (languageVersion < ScriptTarget.ES2017) {
transformers.push(transformES2017);
}
@@ -149,14 +76,18 @@ namespace ts {
* @param transforms An array of Transformers.
*/
export function transformFiles(resolver: EmitResolver, host: EmitHost, sourceFiles: SourceFile[], transformers: Transformer[]): TransformationResult {
const lexicalEnvironmentVariableDeclarationsStack: VariableDeclaration[][] = [];
const lexicalEnvironmentFunctionDeclarationsStack: FunctionDeclaration[][] = [];
const enabledSyntaxKindFeatures = new Array<SyntaxKindFeatureFlags>(SyntaxKind.Count);
let lexicalEnvironmentDisabled = false;
let lexicalEnvironmentVariableDeclarations: VariableDeclaration[];
let lexicalEnvironmentFunctionDeclarations: FunctionDeclaration[];
let lexicalEnvironmentVariableDeclarationsStack: VariableDeclaration[][] = [];
let lexicalEnvironmentFunctionDeclarationsStack: FunctionDeclaration[][] = [];
let lexicalEnvironmentStackOffset = 0;
let hoistedVariableDeclarations: VariableDeclaration[];
let hoistedFunctionDeclarations: FunctionDeclaration[];
let lexicalEnvironmentDisabled: boolean;
let lexicalEnvironmentSuspended = false;
let emitHelpers: EmitHelper[];
// The transformation context is provided to each transformer as part of transformer
// initialization.
@@ -164,10 +95,14 @@ namespace ts {
getCompilerOptions: () => host.getCompilerOptions(),
getEmitResolver: () => resolver,
getEmitHost: () => host,
startLexicalEnvironment,
suspendLexicalEnvironment,
resumeLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration,
hoistFunctionDeclaration,
startLexicalEnvironment,
endLexicalEnvironment,
requestEmitHelper,
readEmitHelpers,
onSubstituteNode: (_emitContext, node) => node,
enableSubstitution,
isSubstitutionEnabled,
@@ -280,11 +215,11 @@ namespace ts {
function hoistVariableDeclaration(name: Identifier): void {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase.");
const decl = createVariableDeclaration(name);
if (!hoistedVariableDeclarations) {
hoistedVariableDeclarations = [decl];
if (!lexicalEnvironmentVariableDeclarations) {
lexicalEnvironmentVariableDeclarations = [decl];
}
else {
hoistedVariableDeclarations.push(decl);
lexicalEnvironmentVariableDeclarations.push(decl);
}
}
@@ -293,11 +228,11 @@ namespace ts {
*/
function hoistFunctionDeclaration(func: FunctionDeclaration): void {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase.");
if (!hoistedFunctionDeclarations) {
hoistedFunctionDeclarations = [func];
if (!lexicalEnvironmentFunctionDeclarations) {
lexicalEnvironmentFunctionDeclarations = [func];
}
else {
hoistedFunctionDeclarations.push(func);
lexicalEnvironmentFunctionDeclarations.push(func);
}
}
@@ -307,16 +242,31 @@ namespace ts {
*/
function startLexicalEnvironment(): void {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase.");
Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
// Save the current lexical environment. Rather than resizing the array we adjust the
// stack size variable. This allows us to reuse existing array slots we've
// already allocated between transformations to avoid allocation and GC overhead during
// transformation.
lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations;
lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations;
lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
lexicalEnvironmentStackOffset++;
hoistedVariableDeclarations = undefined;
hoistedFunctionDeclarations = undefined;
lexicalEnvironmentVariableDeclarations = undefined;
lexicalEnvironmentFunctionDeclarations = undefined;
}
/** Suspends the current lexical environment, usually after visiting a parameter list. */
function suspendLexicalEnvironment(): void {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot suspend a lexical environment during the print phase.");
Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
lexicalEnvironmentSuspended = true;
}
/** Resumes a suspended lexical environment, usually before visiting a function body. */
function resumeLexicalEnvironment(): void {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot resume a lexical environment during the print phase.");
Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
lexicalEnvironmentSuspended = false;
}
/**
@@ -325,17 +275,18 @@ namespace ts {
*/
function endLexicalEnvironment(): Statement[] {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase.");
Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
let statements: Statement[];
if (hoistedVariableDeclarations || hoistedFunctionDeclarations) {
if (hoistedFunctionDeclarations) {
statements = [...hoistedFunctionDeclarations];
if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) {
if (lexicalEnvironmentFunctionDeclarations) {
statements = [...lexicalEnvironmentFunctionDeclarations];
}
if (hoistedVariableDeclarations) {
if (lexicalEnvironmentVariableDeclarations) {
const statement = createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList(hoistedVariableDeclarations)
createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)
);
if (!statements) {
@@ -349,9 +300,26 @@ namespace ts {
// Restore the previous lexical environment.
lexicalEnvironmentStackOffset--;
hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
if (lexicalEnvironmentStackOffset === 0) {
lexicalEnvironmentVariableDeclarationsStack = [];
lexicalEnvironmentFunctionDeclarationsStack = [];
}
return statements;
}
function requestEmitHelper(helper: EmitHelper): void {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase.");
Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
emitHelpers = append(emitHelpers, helper);
}
function readEmitHelpers(): EmitHelper[] | undefined {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase.");
const helpers = emitHelpers;
emitHelpers = undefined;
return helpers;
}
}
}
+433 -379
View File
@@ -3,410 +3,397 @@
/*@internal*/
namespace ts {
interface FlattenContext {
context: TransformationContext;
level: FlattenLevel;
hoistTempVariables: boolean;
emitExpression: (value: Expression) => void;
emitBindingOrAssignment: (target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node) => void;
createArrayBindingOrAssignmentPattern: (elements: BindingOrAssignmentElement[]) => ArrayBindingOrAssignmentPattern;
createObjectBindingOrAssignmentPattern: (elements: BindingOrAssignmentElement[]) => ObjectBindingOrAssignmentPattern;
createArrayBindingOrAssignmentElement: (node: Identifier) => BindingOrAssignmentElement;
visitor?: (node: Node) => VisitResult<Node>;
}
export const enum FlattenLevel {
All,
ObjectRest,
}
/**
* Flattens a destructuring assignment expression.
* Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
*
* @param root The destructuring assignment expression.
* @param needsValue Indicates whether the value from the right-hand-side of the
* destructuring assignment is needed as part of a larger expression.
* @param recordTempVariable A callback used to record new temporary variables.
* @param visitor An optional visitor to use to visit expressions.
* @param node The node to flatten.
* @param visitor An optional visitor used to visit initializers.
* @param context The transformation context.
* @param level Indicates the extent to which flattening should occur.
* @param needsValue An optional value indicating whether the value from the right-hand-side of
* the destructuring assignment is needed as part of a larger expression.
* @param createAssignmentCallback An optional callback used to create the assignment expression.
*/
export function flattenDestructuringAssignment(
node: VariableDeclaration | DestructuringAssignment,
visitor: ((node: Node) => VisitResult<Node>) | undefined,
context: TransformationContext,
node: BinaryExpression,
needsValue: boolean,
recordTempVariable: (node: Identifier) => void,
visitor?: (node: Node) => VisitResult<Node>): Expression {
if (isEmptyObjectLiteralOrArrayLiteral(node.left)) {
const right = node.right;
if (isDestructuringAssignment(right)) {
return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor);
}
else {
return node.right;
}
}
level: FlattenLevel,
needsValue?: boolean,
createAssignmentCallback?: (name: Identifier, value: Expression, location?: TextRange) => Expression): Expression {
let location: TextRange = node;
let value = node.right;
const expressions: Expression[] = [];
if (needsValue) {
// If the right-hand value of the destructuring assignment needs to be preserved (as
// is the case when the destructuring assignmen) is part of a larger expression),
// then we need to cache the right-hand value.
//
// The source map location for the assignment should point to the entire binary
// expression.
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment, visitor);
}
else if (nodeIsSynthesized(node)) {
// Generally, the source map location for a destructuring assignment is the root
// expression.
//
// However, if the root expression is synthesized (as in the case
// of the initializer when transforming a ForOfStatement), then the source map
// location should point to the right-hand value of the expression.
location = value;
let value: Expression;
if (isDestructuringAssignment(node)) {
value = node.right;
while (isEmptyObjectLiteralOrArrayLiteral(node.left)) {
if (isDestructuringAssignment(value)) {
location = node = value;
value = node.right;
}
else {
return value;
}
}
}
flattenDestructuring(node, value, location, emitAssignment, emitTempVariableAssignment, visitor);
let expressions: Expression[];
const flattenContext: FlattenContext = {
context,
level,
hoistTempVariables: true,
emitExpression,
emitBindingOrAssignment,
createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern,
createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern,
createArrayBindingOrAssignmentElement: makeAssignmentElement,
visitor
};
if (value) {
value = visitNode(value, visitor, isExpression);
if (needsValue) {
// If the right-hand value of the destructuring assignment needs to be preserved (as
// is the case when the destructuring assignment is part of a larger expression),
// then we need to cache the right-hand value.
//
// The source map location for the assignment should point to the entire binary
// expression.
value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
}
else if (nodeIsSynthesized(node)) {
// Generally, the source map location for a destructuring assignment is the root
// expression.
//
// However, if the root expression is synthesized (as in the case
// of the initializer when transforming a ForOfStatement), then the source map
// location should point to the right-hand value of the expression.
location = value;
}
}
flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ isDestructuringAssignment(node));
if (value && needsValue) {
if (!some(expressions)) {
return value;
}
if (needsValue) {
expressions.push(value);
}
const expression = inlineExpressions(expressions);
aggregateTransformFlags(expression);
return expression;
function emitAssignment(name: Identifier, value: Expression, location: TextRange) {
const expression = createAssignment(name, value, location);
return aggregateTransformFlags(inlineExpressions(expressions)) || createOmittedExpression();
function emitExpression(expression: Expression) {
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
setEmitFlags(expression, EmitFlags.NoNestedSourceMaps);
aggregateTransformFlags(expression);
expressions.push(expression);
expressions = append(expressions, expression);
}
function emitTempVariableAssignment(value: Expression, location: TextRange) {
const name = createTempVariable(recordTempVariable);
emitAssignment(name, value, location);
return name;
}
}
/**
* Flattens binding patterns in a parameter declaration.
*
* @param node The ParameterDeclaration to flatten.
* @param value The rhs value for the binding pattern.
* @param visitor An optional visitor to use to visit expressions.
*/
export function flattenParameterDestructuring(
node: ParameterDeclaration,
value: Expression,
visitor?: (node: Node) => VisitResult<Node>) {
const declarations: VariableDeclaration[] = [];
flattenDestructuring(node, value, node, emitAssignment, emitTempVariableAssignment, visitor);
return declarations;
function emitAssignment(name: Identifier, value: Expression, location: TextRange) {
const declaration = createVariableDeclaration(name, /*type*/ undefined, value, location);
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
setEmitFlags(declaration, EmitFlags.NoNestedSourceMaps);
aggregateTransformFlags(declaration);
declarations.push(declaration);
}
function emitTempVariableAssignment(value: Expression, location: TextRange) {
const name = createTempVariable(/*recordTempVariable*/ undefined);
emitAssignment(name, value, location);
return name;
}
}
/**
* Flattens binding patterns in a variable declaration.
*
* @param node The VariableDeclaration to flatten.
* @param value An optional rhs value for the binding pattern.
* @param visitor An optional visitor to use to visit expressions.
*/
export function flattenVariableDestructuring(
node: VariableDeclaration,
value?: Expression,
visitor?: (node: Node) => VisitResult<Node>,
recordTempVariable?: (node: Identifier) => void) {
const declarations: VariableDeclaration[] = [];
let pendingAssignments: Expression[];
flattenDestructuring(node, value, node, emitAssignment, emitTempVariableAssignment, visitor);
return declarations;
function emitAssignment(name: Identifier, value: Expression, location: TextRange, original: Node) {
if (pendingAssignments) {
pendingAssignments.push(value);
value = inlineExpressions(pendingAssignments);
pendingAssignments = undefined;
}
const declaration = createVariableDeclaration(name, /*type*/ undefined, value, location);
declaration.original = original;
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
setEmitFlags(declaration, EmitFlags.NoNestedSourceMaps);
declarations.push(declaration);
aggregateTransformFlags(declaration);
}
function emitTempVariableAssignment(value: Expression, location: TextRange) {
const name = createTempVariable(recordTempVariable);
if (recordTempVariable) {
const assignment = createAssignment(name, value, location);
if (pendingAssignments) {
pendingAssignments.push(assignment);
}
else {
pendingAssignments = [assignment];
}
}
else {
emitAssignment(name, value, location, /*original*/ undefined);
}
return name;
}
}
/**
* Flattens binding patterns in a variable declaration and transforms them into an expression.
*
* @param node The VariableDeclaration to flatten.
* @param recordTempVariable A callback used to record new temporary variables.
* @param createAssignmentCallback An optional callback used to create assignment expressions
* for non-temporary variables.
* @param visitor An optional visitor to use to visit expressions.
*/
export function flattenVariableDestructuringToExpression(
node: VariableDeclaration,
recordTempVariable: (name: Identifier) => void,
createAssignmentCallback?: (name: Identifier, value: Expression, location?: TextRange) => Expression,
visitor?: (node: Node) => VisitResult<Node>) {
const pendingAssignments: Expression[] = [];
flattenDestructuring(node, /*value*/ undefined, node, emitAssignment, emitTempVariableAssignment, visitor);
const expression = inlineExpressions(pendingAssignments);
aggregateTransformFlags(expression);
return expression;
function emitAssignment(name: Identifier, value: Expression, location: TextRange, original: Node) {
function emitBindingOrAssignment(target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node) {
Debug.assertNode(target, createAssignmentCallback ? isIdentifier : isExpression);
const expression = createAssignmentCallback
? createAssignmentCallback(name, value, location)
: createAssignment(name, value, location);
emitPendingAssignment(expression, original);
}
function emitTempVariableAssignment(value: Expression, location: TextRange) {
const name = createTempVariable(recordTempVariable);
emitPendingAssignment(createAssignment(name, value, location), /*original*/ undefined);
return name;
}
function emitPendingAssignment(expression: Expression, original: Node) {
? createAssignmentCallback(<Identifier>target, value, location)
: createAssignment(visitNode(<Expression>target, visitor, isExpression), value, location);
expression.original = original;
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
setEmitFlags(expression, EmitFlags.NoNestedSourceMaps);
pendingAssignments.push(expression);
emitExpression(expression);
}
}
function flattenDestructuring(
root: VariableDeclaration | ParameterDeclaration | BindingElement | BinaryExpression,
value: Expression,
/**
* Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
*
* @param node The node to flatten.
* @param visitor An optional visitor used to visit initializers.
* @param context The transformation context.
* @param boundValue The value bound to the declaration.
* @param skipInitializer A value indicating whether to ignore the initializer of `node`.
* @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
* @param level Indicates the extent to which flattening should occur.
*/
export function flattenDestructuringBinding(
node: VariableDeclaration | ParameterDeclaration,
visitor: (node: Node) => VisitResult<Node>,
context: TransformationContext,
level: FlattenLevel,
rval?: Expression,
hoistTempVariables?: boolean,
skipInitializer?: boolean): VariableDeclaration[] {
let pendingExpressions: Expression[];
const pendingDeclarations: { pendingExpressions?: Expression[], name: BindingName, value: Expression, location?: TextRange, original?: Node; }[] = [];
const declarations: VariableDeclaration[] = [];
const flattenContext: FlattenContext = {
context,
level,
hoistTempVariables,
emitExpression,
emitBindingOrAssignment,
createArrayBindingOrAssignmentPattern: makeArrayBindingPattern,
createObjectBindingOrAssignmentPattern: makeObjectBindingPattern,
createArrayBindingOrAssignmentElement: makeBindingElement,
visitor
};
flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
if (pendingExpressions) {
const temp = createTempVariable(/*recordTempVariable*/ undefined);
if (hoistTempVariables) {
const value = inlineExpressions(pendingExpressions);
pendingExpressions = undefined;
emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
}
else {
context.hoistVariableDeclaration(temp);
const pendingDeclaration = lastOrUndefined(pendingDeclarations);
pendingDeclaration.pendingExpressions = append(
pendingDeclaration.pendingExpressions,
createAssignment(temp, pendingDeclaration.value)
);
addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
pendingDeclaration.value = temp;
}
}
for (const { pendingExpressions, name, value, location, original } of pendingDeclarations) {
const variable = createVariableDeclaration(
name,
/*type*/ undefined,
pendingExpressions ? inlineExpressions(append(pendingExpressions, value)) : value,
location);
variable.original = original;
if (isIdentifier(name)) {
setEmitFlags(variable, EmitFlags.NoNestedSourceMaps);
}
aggregateTransformFlags(variable);
declarations.push(variable);
}
return declarations;
function emitExpression(value: Expression) {
pendingExpressions = append(pendingExpressions, value);
}
function emitBindingOrAssignment(target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node) {
Debug.assertNode(target, isBindingName);
if (pendingExpressions) {
value = inlineExpressions(append(pendingExpressions, value));
pendingExpressions = undefined;
}
pendingDeclarations.push({ pendingExpressions, name: <BindingName>target, value, location, original });
}
}
/**
* Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
*
* @param flattenContext Options used to control flattening.
* @param element The element to flatten.
* @param value The current RHS value to assign to the element.
* @param location The location to use for source maps and comments.
* @param skipInitializer An optional value indicating whether to include the initializer
* for the element.
*/
function flattenBindingOrAssignmentElement(
flattenContext: FlattenContext,
element: BindingOrAssignmentElement,
value: Expression | undefined,
location: TextRange,
emitAssignment: (name: Identifier, value: Expression, location: TextRange, original: Node) => void,
emitTempVariableAssignment: (value: Expression, location: TextRange) => Identifier,
visitor?: (node: Node) => VisitResult<Node>) {
if (value && visitor) {
value = visitNode(value, visitor, isExpression);
}
if (isBinaryExpression(root)) {
emitDestructuringAssignment(root.left, value, location);
}
else {
emitBindingElement(root, value);
}
function emitDestructuringAssignment(bindingTarget: Expression | ShorthandPropertyAssignment, value: Expression, location: TextRange) {
// When emitting target = value use source map node to highlight, including any temporary assignments needed for this
let target: Expression;
if (isShorthandPropertyAssignment(bindingTarget)) {
const initializer = visitor
? visitNode(bindingTarget.objectAssignmentInitializer, visitor, isExpression)
: bindingTarget.objectAssignmentInitializer;
if (initializer) {
value = createDefaultValueCheck(value, initializer, location);
}
target = bindingTarget.name;
}
else if (isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === SyntaxKind.EqualsToken) {
const initializer = visitor
? visitNode(bindingTarget.right, visitor, isExpression)
: bindingTarget.right;
value = createDefaultValueCheck(value, initializer, location);
target = bindingTarget.left;
}
else {
target = bindingTarget;
}
if (target.kind === SyntaxKind.ObjectLiteralExpression) {
emitObjectLiteralAssignment(<ObjectLiteralExpression>target, value, location);
}
else if (target.kind === SyntaxKind.ArrayLiteralExpression) {
emitArrayLiteralAssignment(<ArrayLiteralExpression>target, value, location);
}
else {
const name = getMutableClone(<Identifier>target);
setSourceMapRange(name, target);
setCommentRange(name, target);
emitAssignment(name, value, location, /*original*/ undefined);
}
}
function emitObjectLiteralAssignment(target: ObjectLiteralExpression, value: Expression, location: TextRange) {
const properties = target.properties;
if (properties.length !== 1) {
// For anything but a single element destructuring we need to generate a temporary
// to ensure value is evaluated exactly once.
// When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
}
for (const p of properties) {
if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) {
const propName = <Identifier | LiteralExpression>(<PropertyAssignment>p).name;
const target = p.kind === SyntaxKind.ShorthandPropertyAssignment ? <ShorthandPropertyAssignment>p : (<PropertyAssignment>p).initializer || propName;
// Assignment for target = value.propName should highligh whole property, hence use p as source map node
emitDestructuringAssignment(target, createDestructuringPropertyAccess(value, propName), p);
}
}
}
function emitArrayLiteralAssignment(target: ArrayLiteralExpression, value: Expression, location: TextRange) {
const elements = target.elements;
const numElements = elements.length;
if (numElements !== 1) {
// For anything but a single element destructuring we need to generate a temporary
// to ensure value is evaluated exactly once.
// When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
}
for (let i = 0; i < numElements; i++) {
const e = elements[i];
if (e.kind !== SyntaxKind.OmittedExpression) {
// Assignment for target = value.propName should highligh whole property, hence use e as source map node
if (e.kind !== SyntaxKind.SpreadElementExpression) {
emitDestructuringAssignment(e, createElementAccess(value, createLiteral(i)), e);
}
else if (i === numElements - 1) {
emitDestructuringAssignment((<SpreadElementExpression>e).expression, createArraySlice(value, i), e);
}
}
}
}
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;
skipInitializer?: boolean) {
if (!skipInitializer) {
const initializer = visitNode(getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, isExpression);
if (initializer) {
// Combine value and initializer
value = value ? createDefaultValueCheck(value, initializer, target) : initializer;
value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer;
}
else if (!value) {
// Use 'void 0' in absence of value and initializer
value = createVoidZero();
}
const name = target.name;
if (isBindingPattern(name)) {
const elements = name.elements;
const numElements = elements.length;
if (numElements !== 1) {
// For anything other than a single-element destructuring we need to generate a temporary
// to ensure value is evaluated exactly once. Additionally, if we have zero elements
// we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
// so in that case, we'll intentionally create that temporary.
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target, emitTempVariableAssignment);
}
for (let i = 0; i < numElements; i++) {
const element = elements[i];
if (isOmittedExpression(element)) {
continue;
}
else if (name.kind === SyntaxKind.ObjectBindingPattern) {
// Rewrite element to a declaration with an initializer that fetches property
const propName = element.propertyName || <Identifier>element.name;
emitBindingElement(element, createDestructuringPropertyAccess(value, propName));
}
else {
if (!element.dotDotDotToken) {
// Rewrite element to a declaration that accesses array element at index i
emitBindingElement(element, createElementAccess(value, i));
}
else if (i === numElements - 1) {
emitBindingElement(element, createArraySlice(value, i));
}
}
}
}
else {
emitAssignment(name, value, target, target);
}
}
function createDefaultValueCheck(value: Expression, defaultValue: Expression, location: TextRange): Expression {
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
return createConditional(
createStrictEquality(value, createVoidZero()),
createToken(SyntaxKind.QuestionToken),
defaultValue,
createToken(SyntaxKind.ColonToken),
value
);
const bindingTarget = getTargetOfBindingOrAssignmentElement(element);
if (isObjectBindingOrAssignmentPattern(bindingTarget)) {
flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
}
else if (isArrayBindingOrAssignmentPattern(bindingTarget)) {
flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
}
else {
flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element);
}
}
/**
* Creates either a PropertyAccessExpression or an ElementAccessExpression for the
* right-hand side of a transformed destructuring assignment.
*
* @param expression The right-hand expression that is the source of the property.
* @param propertyName The destructuring property name.
*/
function createDestructuringPropertyAccess(expression: Expression, propertyName: PropertyName): LeftHandSideExpression {
if (isComputedPropertyName(propertyName)) {
return createElementAccess(
expression,
ensureIdentifier(propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName, emitTempVariableAssignment)
);
}
else if (isLiteralExpression(propertyName)) {
const clone = getSynthesizedClone(propertyName);
clone.text = unescapeIdentifier(clone.text);
return createElementAccess(expression, clone);
}
else {
if (isGeneratedIdentifier(propertyName)) {
const clone = getSynthesizedClone(propertyName);
clone.text = unescapeIdentifier(clone.text);
return createPropertyAccess(expression, clone);
/**
* Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
*
* @param flattenContext Options used to control flattening.
* @param parent The parent element of the pattern.
* @param pattern The ObjectBindingOrAssignmentPattern to flatten.
* @param value The current RHS value to assign to the element.
* @param location The location to use for source maps and comments.
*/
function flattenObjectBindingOrAssignmentPattern(flattenContext: FlattenContext, parent: BindingOrAssignmentElement, pattern: ObjectBindingOrAssignmentPattern, value: Expression, location: TextRange) {
const elements = getElementsOfBindingOrAssignmentPattern(pattern);
const numElements = elements.length;
if (numElements !== 1) {
// For anything other than a single-element destructuring we need to generate a temporary
// to ensure value is evaluated exactly once. Additionally, if we have zero elements
// we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
// so in that case, we'll intentionally create that temporary.
const reuseIdentifierExpressions = !isDeclarationBindingElement(parent) || numElements !== 0;
value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
}
let bindingElements: BindingOrAssignmentElement[];
let computedTempVariables: Expression[];
for (let i = 0; i < numElements; i++) {
const element = elements[i];
if (!getRestIndicatorOfBindingOrAssignmentElement(element)) {
const propertyName = getPropertyNameOfBindingOrAssignmentElement(element);
if (flattenContext.level >= FlattenLevel.ObjectRest
&& !(element.transformFlags & (TransformFlags.ContainsRest | TransformFlags.ContainsObjectRest))
&& !(getTargetOfBindingOrAssignmentElement(element).transformFlags & (TransformFlags.ContainsRest | TransformFlags.ContainsObjectRest))
&& !isComputedPropertyName(propertyName)) {
bindingElements = append(bindingElements, element);
}
else {
return createPropertyAccess(expression, createIdentifier(unescapeIdentifier(propertyName.text)));
if (bindingElements) {
flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
bindingElements = undefined;
}
const rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
if (isComputedPropertyName(propertyName)) {
computedTempVariables = append(computedTempVariables, (rhsValue as ElementAccessExpression).argumentExpression);
}
flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
}
}
else if (i === numElements - 1) {
if (bindingElements) {
flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
bindingElements = undefined;
}
const rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern);
flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
}
}
if (bindingElements) {
flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
}
}
/**
* Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
*
* @param flattenContext Options used to control flattening.
* @param parent The parent element of the pattern.
* @param pattern The ArrayBindingOrAssignmentPattern to flatten.
* @param value The current RHS value to assign to the element.
* @param location The location to use for source maps and comments.
*/
function flattenArrayBindingOrAssignmentPattern(flattenContext: FlattenContext, parent: BindingOrAssignmentElement, pattern: ArrayBindingOrAssignmentPattern, value: Expression, location: TextRange) {
const elements = getElementsOfBindingOrAssignmentPattern(pattern);
const numElements = elements.length;
if (numElements !== 1 && (flattenContext.level < FlattenLevel.ObjectRest || numElements === 0)) {
// For anything other than a single-element destructuring we need to generate a temporary
// to ensure value is evaluated exactly once. Additionally, if we have zero elements
// we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
// so in that case, we'll intentionally create that temporary.
const reuseIdentifierExpressions = !isDeclarationBindingElement(parent) || numElements !== 0;
value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
}
let bindingElements: BindingOrAssignmentElement[];
let restContainingElements: [Identifier, BindingOrAssignmentElement][];
for (let i = 0; i < numElements; i++) {
const element = elements[i];
if (flattenContext.level >= FlattenLevel.ObjectRest) {
// If an array pattern contains an ObjectRest, we must cache the result so that we
// can perform the ObjectRest destructuring in a different declaration
if (element.transformFlags & TransformFlags.ContainsObjectRest) {
const temp = createTempVariable(/*recordTempVariable*/ undefined);
if (flattenContext.hoistTempVariables) {
flattenContext.context.hoistVariableDeclaration(temp);
}
restContainingElements = append(restContainingElements, <[Identifier, BindingOrAssignmentElement]>[temp, element]);
bindingElements = append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
}
else {
bindingElements = append(bindingElements, element);
}
}
else if (isOmittedExpression(element)) {
continue;
}
else if (!getRestIndicatorOfBindingOrAssignmentElement(element)) {
const rhsValue = createElementAccess(value, i);
flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
}
else if (i === numElements - 1) {
const rhsValue = createArraySlice(value, i);
flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
}
}
if (bindingElements) {
flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
}
if (restContainingElements) {
for (const [id, element] of restContainingElements) {
flattenBindingOrAssignmentElement(flattenContext, element, id, element);
}
}
}
/**
* Creates an expression used to provide a default value if a value is `undefined` at runtime.
*
* @param flattenContext Options used to control flattening.
* @param value The RHS value to test.
* @param defaultValue The default value to use if `value` is `undefined` at runtime.
* @param location The location to use for source maps and comments.
*/
function createDefaultValueCheck(flattenContext: FlattenContext, value: Expression, defaultValue: Expression, location: TextRange): Expression {
value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
return createConditional(createTypeCheck(value, "undefined"), defaultValue, value);
}
/**
* Creates either a PropertyAccessExpression or an ElementAccessExpression for the
* right-hand side of a transformed destructuring assignment.
*
* @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
*
* @param flattenContext Options used to control flattening.
* @param value The RHS value that is the source of the property.
* @param propertyName The destructuring property name.
*/
function createDestructuringPropertyAccess(flattenContext: FlattenContext, value: Expression, propertyName: PropertyName): LeftHandSideExpression {
if (isComputedPropertyName(propertyName)) {
const argumentExpression = ensureIdentifier(flattenContext, propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
return createElementAccess(value, argumentExpression);
}
else if (isStringOrNumericLiteral(propertyName)) {
const argumentExpression = getSynthesizedClone(propertyName);
argumentExpression.text = unescapeIdentifier(argumentExpression.text);
return createElementAccess(value, argumentExpression);
}
else {
const name = createIdentifier(unescapeIdentifier(propertyName.text));
return createPropertyAccess(value, name);
}
}
@@ -415,29 +402,96 @@ namespace ts {
* This function is useful to ensure that the expression's value can be read from in subsequent expressions.
* Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
*
* @param flattenContext Options used to control flattening.
* @param value the expression whose value needs to be bound.
* @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
* false if it is necessary to always emit an identifier.
* false if it is necessary to always emit an identifier.
* @param location The location to use for source maps and comments.
* @param emitTempVariableAssignment A callback used to emit a temporary variable.
* @param visitor An optional callback used to visit the value.
*/
function ensureIdentifier(
value: Expression,
reuseIdentifierExpressions: boolean,
location: TextRange,
emitTempVariableAssignment: (value: Expression, location: TextRange) => Identifier,
visitor?: (node: Node) => VisitResult<Node>) {
function ensureIdentifier(flattenContext: FlattenContext, value: Expression, reuseIdentifierExpressions: boolean, location: TextRange) {
if (isIdentifier(value) && reuseIdentifierExpressions) {
return value;
}
else {
if (visitor) {
value = visitNode(value, visitor, isExpression);
const temp = createTempVariable(/*recordTempVariable*/ undefined);
if (flattenContext.hoistTempVariables) {
flattenContext.context.hoistVariableDeclaration(temp);
flattenContext.emitExpression(createAssignment(temp, value, location));
}
return emitTempVariableAssignment(value, location);
else {
flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
}
return temp;
}
}
function makeArrayBindingPattern(elements: BindingOrAssignmentElement[]) {
Debug.assertEachNode(elements, isArrayBindingElement);
return createArrayBindingPattern(<ArrayBindingElement[]>elements);
}
function makeArrayAssignmentPattern(elements: BindingOrAssignmentElement[]) {
return createArrayLiteral(map(elements, convertToArrayAssignmentElement));
}
function makeObjectBindingPattern(elements: BindingOrAssignmentElement[]) {
Debug.assertEachNode(elements, isBindingElement);
return createObjectBindingPattern(<BindingElement[]>elements);
}
function makeObjectAssignmentPattern(elements: BindingOrAssignmentElement[]) {
return createObjectLiteral(map(elements, convertToObjectAssignmentElement));
}
function makeBindingElement(name: Identifier) {
return createBindingElement(/*propertyName*/ undefined, /*dotDotDotToken*/ undefined, name);
}
function makeAssignmentElement(name: Identifier) {
return name;
}
const restHelper: EmitHelper = {
name: "typescript:rest",
scoped: false,
text: `
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
};`
};
/** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`*/
function createRestCall(context: TransformationContext, value: Expression, elements: BindingOrAssignmentElement[], computedTempVariables: Expression[], location: TextRange): Expression {
context.requestEmitHelper(restHelper);
const propertyNames: Expression[] = [];
let computedTempVariableOffset = 0;
for (let i = 0; i < elements.length - 1; i++) {
const propertyName = getPropertyNameOfBindingOrAssignmentElement(elements[i]);
if (propertyName) {
if (isComputedPropertyName(propertyName)) {
const temp = computedTempVariables[computedTempVariableOffset];
computedTempVariableOffset++;
// typeof _tmp === "symbol" ? _tmp : _tmp + ""
propertyNames.push(
createConditional(
createTypeCheck(temp, "symbol"),
temp,
createAdd(temp, createLiteral(""))
)
);
}
else {
propertyNames.push(createLiteral(propertyName));
}
}
}
return createCall(getHelperName("__rest"), undefined, [value, createArrayLiteral(propertyNames, location)]);
}
}
+231 -163
View File
@@ -3,7 +3,6 @@
/*@internal*/
namespace ts {
const enum ES2015SubstitutionFlags {
/** Enables substitutions for captured `this` */
CapturedThis = 1 << 0,
@@ -166,6 +165,7 @@ namespace ts {
export function transformES2015(context: TransformationContext) {
const {
startLexicalEnvironment,
resumeLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration,
} = context;
@@ -209,7 +209,13 @@ namespace ts {
currentSourceFile = node;
currentText = node.text;
return visitNode(node, visitor, isSourceFile);
const visited = saveStateAndInvoke(node, visitSourceFile);
addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
currentText = undefined;
return visited;
}
function visitor(node: Node): VisitResult<Node> {
@@ -255,6 +261,47 @@ namespace ts {
return visited;
}
function onBeforeVisitNode(node: Node) {
if (currentNode) {
if (isBlockScope(currentNode, currentParent)) {
enclosingBlockScopeContainer = currentNode;
enclosingBlockScopeContainerParent = currentParent;
}
if (isFunctionLike(currentNode)) {
enclosingFunction = currentNode;
if (currentNode.kind !== SyntaxKind.ArrowFunction) {
enclosingNonArrowFunction = currentNode;
if (!(getEmitFlags(currentNode) & EmitFlags.AsyncFunctionBody)) {
enclosingNonAsyncFunctionBody = currentNode;
}
}
}
// keep track of the enclosing variable statement when in the context of
// variable statements, variable declarations, binding elements, and binding
// patterns.
switch (currentNode.kind) {
case SyntaxKind.VariableStatement:
enclosingVariableStatement = <VariableStatement>currentNode;
break;
case SyntaxKind.VariableDeclarationList:
case SyntaxKind.VariableDeclaration:
case SyntaxKind.BindingElement:
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
break;
default:
enclosingVariableStatement = undefined;
}
}
currentParent = currentNode;
currentNode = node;
}
function returnCapturedThis(node: Node): Node {
return setOriginalNode(createReturn(createIdentifier("_this")), node);
}
@@ -279,7 +326,7 @@ namespace ts {
else if (node.transformFlags & TransformFlags.ContainsES2015 || (isInConstructorWithCapturedSuper && !isExpression(node))) {
// we want to dive in this branch either if node has children with ES2015 specific syntax
// or we are inside constructor that captures result of the super call so all returns without expression should be
// rewritten. Note: we skip expressions since returns should never appear there
// rewritten. Note: we skip expressions since returns should never appear there
return visitEachChild(node, visitor, context);
}
else {
@@ -417,6 +464,9 @@ namespace ts {
case SyntaxKind.YieldExpression:
return visitYieldExpression(<YieldExpression>node);
case SyntaxKind.SpreadElement:
return visitSpreadElement(<SpreadElement>node);
case SyntaxKind.SuperKeyword:
return visitSuperKeyword();
@@ -427,9 +477,6 @@ namespace ts {
case SyntaxKind.MethodDeclaration:
return visitMethodDeclaration(<MethodDeclaration>node);
case SyntaxKind.SourceFile:
return visitSourceFileNode(<SourceFile>node);
case SyntaxKind.VariableStatement:
return visitVariableStatement(<VariableStatement>node);
@@ -437,48 +484,19 @@ namespace ts {
Debug.failBadSyntaxKind(node);
return visitEachChild(node, visitor, context);
}
}
function onBeforeVisitNode(node: Node) {
if (currentNode) {
if (isBlockScope(currentNode, currentParent)) {
enclosingBlockScopeContainer = currentNode;
enclosingBlockScopeContainerParent = currentParent;
}
if (isFunctionLike(currentNode)) {
enclosingFunction = currentNode;
if (currentNode.kind !== SyntaxKind.ArrowFunction) {
enclosingNonArrowFunction = currentNode;
if (!(getEmitFlags(currentNode) & EmitFlags.AsyncFunctionBody)) {
enclosingNonAsyncFunctionBody = currentNode;
}
}
}
// keep track of the enclosing variable statement when in the context of
// variable statements, variable declarations, binding elements, and binding
// patterns.
switch (currentNode.kind) {
case SyntaxKind.VariableStatement:
enclosingVariableStatement = <VariableStatement>currentNode;
break;
case SyntaxKind.VariableDeclarationList:
case SyntaxKind.VariableDeclaration:
case SyntaxKind.BindingElement:
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
break;
default:
enclosingVariableStatement = undefined;
}
}
currentParent = currentNode;
currentNode = node;
function visitSourceFile(node: SourceFile): SourceFile {
const statements: Statement[] = [];
startLexicalEnvironment();
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor);
addCaptureThisForNodeIfNeeded(statements, node);
addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset));
addRange(statements, endLexicalEnvironment());
return updateSourceFileNode(
node,
createNodeArray(statements, node.statements)
);
}
function visitSwitchStatement(node: SwitchStatement): SwitchStatement {
@@ -778,7 +796,7 @@ namespace ts {
if (extendsClauseElement) {
statements.push(
createStatement(
createExtendsHelper(currentSourceFile.externalHelpersModuleName, getLocalName(node)),
createExtendsHelper(context, getLocalName(node)),
/*location*/ extendsClauseElement
)
);
@@ -822,17 +840,14 @@ namespace ts {
* @param hasSynthesizedSuper A value indicating whether the constructor starts with a
* synthesized `super` call.
*/
function transformConstructorParameters(constructor: ConstructorDeclaration, hasSynthesizedSuper: boolean): ParameterDeclaration[] {
function transformConstructorParameters(constructor: ConstructorDeclaration, hasSynthesizedSuper: boolean) {
// If the TypeScript transformer needed to synthesize a constructor for property
// initializers, it would have also added a synthetic `...args` parameter and
// `super` call.
// If this is the case, we do not include the synthetic `...args` parameter and
// will instead use the `arguments` object in ES5/3.
if (constructor && !hasSynthesizedSuper) {
return visitNodes(constructor.parameters, visitor, isParameter);
}
return [];
return visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context)
|| <ParameterDeclaration[]>[];
}
/**
@@ -846,14 +861,14 @@ namespace ts {
*/
function transformConstructorBody(constructor: ConstructorDeclaration | undefined, node: ClassDeclaration | ClassExpression, extendsClauseElement: ExpressionWithTypeArguments, hasSynthesizedSuper: boolean) {
const statements: Statement[] = [];
startLexicalEnvironment();
resumeLexicalEnvironment();
let statementOffset = -1;
if (hasSynthesizedSuper) {
// If a super call has already been synthesized,
// we're going to assume that we should just transform everything after that.
// The assumption is that no prior step in the pipeline has added any prologue directives.
statementOffset = 1;
statementOffset = 0;
}
else if (constructor) {
// Otherwise, try to emit all potential prologue directives first.
@@ -1011,7 +1026,20 @@ namespace ts {
// Return the result if we have an immediate super() call on the last statement.
if (superCallExpression && statementOffset === ctorStatements.length - 1) {
statements.push(createReturn(superCallExpression));
const returnStatement = createReturn(superCallExpression);
if (superCallExpression.kind !== SyntaxKind.BinaryExpression
|| (superCallExpression as BinaryExpression).left.kind !== SyntaxKind.CallExpression) {
Debug.fail("Assumed generated super call would have form 'super.call(...) || this'.");
}
// Shift comments from the original super call to the return statement.
setCommentRange(returnStatement, getCommentRange(
setEmitFlags(
(superCallExpression as BinaryExpression).left,
EmitFlags.NoComments)));
statements.push(returnStatement);
return SuperCaptureResult.ReplaceWithReturn;
}
@@ -1145,7 +1173,13 @@ namespace ts {
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList(
flattenParameterDestructuring(parameter, temp, visitor)
flattenDestructuringBinding(
parameter,
visitor,
context,
FlattenLevel.All,
temp
)
)
),
EmitFlags.CustomPrologue
@@ -1178,10 +1212,7 @@ namespace ts {
function addDefaultValueAssignmentForInitializer(statements: Statement[], parameter: ParameterDeclaration, name: Identifier, initializer: Expression): void {
initializer = visitNode(initializer, visitor, isExpression);
const statement = createIf(
createStrictEquality(
getSynthesizedClone(name),
createVoidZero()
),
createTypeCheck(getSynthesizedClone(name), "undefined"),
setEmitFlags(
createBlock([
createStatement(
@@ -1275,7 +1306,9 @@ namespace ts {
createAssignment(
createElementAccess(
expressionName,
createSubtract(temp, createLiteral(restIndex))
restIndex === 0
? temp
: createSubtract(temp, createLiteral(restIndex))
),
createElementAccess(createIdentifier("arguments"), temp)
),
@@ -1377,20 +1410,13 @@ namespace ts {
function transformClassMethodDeclarationToStatement(receiver: LeftHandSideExpression, member: MethodDeclaration) {
const commentRange = getCommentRange(member);
const sourceMapRange = getSourceMapRange(member);
const func = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined);
setEmitFlags(func, EmitFlags.NoComments);
setSourceMapRange(func, sourceMapRange);
const memberName = createMemberAccessForPropertyName(receiver, visitNode(member.name, visitor, isPropertyName), /*location*/ member.name);
const memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined);
setEmitFlags(memberFunction, EmitFlags.NoComments);
setSourceMapRange(memberFunction, sourceMapRange);
const statement = createStatement(
createAssignment(
createMemberAccessForPropertyName(
receiver,
visitNode(member.name, visitor, isPropertyName),
/*location*/ member.name
),
func
),
createAssignment(memberName, memberFunction),
/*location*/ member
);
@@ -1488,8 +1514,17 @@ namespace ts {
if (node.transformFlags & TransformFlags.ContainsLexicalThis) {
enableSubstitutionsForCapturedThis();
}
const func = transformFunctionLikeToExpression(node, /*location*/ node, /*name*/ undefined);
const func = createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node),
node
);
setOriginalNode(func, node);
setEmitFlags(func, EmitFlags.CapturesThis);
return func;
}
@@ -1500,7 +1535,17 @@ namespace ts {
* @param node a FunctionExpression node.
*/
function visitFunctionExpression(node: FunctionExpression): Expression {
return transformFunctionLikeToExpression(node, /*location*/ node, node.name);
return updateFunctionExpression(
node,
/*modifiers*/ undefined,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
node.transformFlags & TransformFlags.ES2015
? transformFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
}
/**
@@ -1509,19 +1554,18 @@ namespace ts {
* @param node a FunctionDeclaration node.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): FunctionDeclaration {
return setOriginalNode(
createFunctionDeclaration(
/*decorators*/ undefined,
node.modifiers,
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ node
),
/*original*/ node);
return updateFunctionDeclaration(
node,
/*decorators*/ undefined,
node.modifiers,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
node.transformFlags & TransformFlags.ES2015
? transformFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
}
/**
@@ -1543,7 +1587,7 @@ namespace ts {
node.asteriskToken,
name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
saveStateAndInvoke(node, transformFunctionBody),
location
@@ -1570,7 +1614,7 @@ namespace ts {
const body = node.body;
let statementOffset: number;
startLexicalEnvironment();
resumeLexicalEnvironment();
if (isBlock(body)) {
// ensureUseStrict is false because no new prologue-directive should be added.
// addPrologueDirectives will simply put already-existing directives at the beginning of the target statement-array
@@ -1624,7 +1668,7 @@ namespace ts {
closeBraceLocation = body;
}
const lexicalEnvironment = endLexicalEnvironment();
const lexicalEnvironment = context.endLexicalEnvironment();
addRange(statements, lexicalEnvironment);
// If we added any final generated statements, this must be a multi-line block
@@ -1650,20 +1694,14 @@ namespace ts {
*
* @param node An ExpressionStatement node.
*/
function visitExpressionStatement(node: ExpressionStatement): ExpressionStatement {
function visitExpressionStatement(node: ExpressionStatement): Statement {
// If we are here it is most likely because our expression is a destructuring assignment.
switch (node.expression.kind) {
case SyntaxKind.ParenthesizedExpression:
return updateStatement(node,
visitParenthesizedExpression(<ParenthesizedExpression>node.expression, /*needsDestructuringValue*/ false)
);
return updateStatement(node, visitParenthesizedExpression(<ParenthesizedExpression>node.expression, /*needsDestructuringValue*/ false));
case SyntaxKind.BinaryExpression:
return updateStatement(node,
visitBinaryExpression(<BinaryExpression>node.expression, /*needsDestructuringValue*/ false)
);
return updateStatement(node, visitBinaryExpression(<BinaryExpression>node.expression, /*needsDestructuringValue*/ false));
}
return visitEachChild(node, visitor, context);
}
@@ -1676,22 +1714,14 @@ namespace ts {
*/
function visitParenthesizedExpression(node: ParenthesizedExpression, needsDestructuringValue: boolean): ParenthesizedExpression {
// If we are here it is most likely because our expression is a destructuring assignment.
if (needsDestructuringValue) {
if (!needsDestructuringValue) {
switch (node.expression.kind) {
case SyntaxKind.ParenthesizedExpression:
return createParen(
visitParenthesizedExpression(<ParenthesizedExpression>node.expression, /*needsDestructuringValue*/ true),
/*location*/ node
);
return updateParen(node, visitParenthesizedExpression(<ParenthesizedExpression>node.expression, /*needsDestructuringValue*/ false));
case SyntaxKind.BinaryExpression:
return createParen(
visitBinaryExpression(<BinaryExpression>node.expression, /*needsDestructuringValue*/ true),
/*location*/ node
);
return updateParen(node, visitBinaryExpression(<BinaryExpression>node.expression, /*needsDestructuringValue*/ false));
}
}
return visitEachChild(node, visitor, context);
}
@@ -1704,8 +1734,14 @@ namespace ts {
*/
function visitBinaryExpression(node: BinaryExpression, needsDestructuringValue: boolean): Expression {
// If we are here it is because this is a destructuring assignment.
Debug.assert(isDestructuringAssignment(node));
return flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor);
if (isDestructuringAssignment(node)) {
return flattenDestructuringAssignment(
<DestructuringAssignment>node,
visitor,
context,
FlattenLevel.All,
needsDestructuringValue);
}
}
function visitVariableStatement(node: VariableStatement): Statement {
@@ -1717,7 +1753,12 @@ namespace ts {
if (decl.initializer) {
let assignment: Expression;
if (isBindingPattern(decl.name)) {
assignment = flattenVariableDestructuringToExpression(decl, hoistVariableDeclaration, /*createAssignmentCallback*/ undefined, visitor);
assignment = flattenDestructuringAssignment(
decl,
visitor,
context,
FlattenLevel.All
);
}
else {
assignment = createBinary(<Identifier>decl.name, SyntaxKind.EqualsToken, visitNode(decl.initializer, visitor, isExpression));
@@ -1868,10 +1909,16 @@ namespace ts {
function visitVariableDeclaration(node: VariableDeclaration): VisitResult<VariableDeclaration> {
// If we are here it is because the name contains a binding pattern.
if (isBindingPattern(node.name)) {
const recordTempVariablesInLine = !enclosingVariableStatement
|| !hasModifier(enclosingVariableStatement, ModifierFlags.Export);
return flattenVariableDestructuring(node, /*value*/ undefined, visitor,
recordTempVariablesInLine ? undefined : hoistVariableDeclaration);
const hoistTempVariables = enclosingVariableStatement
&& hasModifier(enclosingVariableStatement, ModifierFlags.Export);
return flattenDestructuringBinding(
node,
visitor,
context,
FlattenLevel.All,
/*value*/ undefined,
hoistTempVariables
);
}
return visitEachChild(node, visitor, context);
@@ -1960,6 +2007,7 @@ namespace ts {
const rhsReference = expression.kind === SyntaxKind.Identifier
? createUniqueName((<Identifier>expression).text)
: createTempVariable(/*recordTempVariable*/ undefined);
const elementAccess = createElementAccess(rhsReference, counter);
// Initialize LHS
// var v = _a[_i];
@@ -1972,10 +2020,12 @@ namespace ts {
if (firstOriginalDeclaration && isBindingPattern(firstOriginalDeclaration.name)) {
// This works whether the declaration is a var, let, or const.
// It will use rhsIterationValue _a[_i] as the initializer.
const declarations = flattenVariableDestructuring(
const declarations = flattenDestructuringBinding(
firstOriginalDeclaration,
createElementAccess(rhsReference, counter),
visitor
visitor,
context,
FlattenLevel.All,
elementAccess
);
const declarationList = createVariableDeclarationList(declarations, /*location*/ initializer);
@@ -2018,17 +2068,16 @@ namespace ts {
else {
// Initializer is an expression. Emit the expression in the body, so that it's
// evaluated on every iteration.
const assignment = createAssignment(initializer, createElementAccess(rhsReference, counter));
const assignment = createAssignment(initializer, elementAccess);
if (isDestructuringAssignment(assignment)) {
// This is a destructuring pattern, so we flatten the destructuring instead.
statements.push(
createStatement(
flattenDestructuringAssignment(
context,
assignment,
/*needsValue*/ false,
hoistVariableDeclaration,
visitor
visitor,
context,
FlattenLevel.All
)
)
);
@@ -2664,7 +2713,13 @@ namespace ts {
const temp = createTempVariable(undefined);
const newVariableDeclaration = createVariableDeclaration(temp, undefined, undefined, node.variableDeclaration);
const vars = flattenVariableDestructuring(node.variableDeclaration, temp, visitor);
const vars = flattenDestructuringBinding(
node.variableDeclaration,
visitor,
context,
FlattenLevel.All,
temp
);
const list = createVariableDeclarationList(vars, /*location*/node.variableDeclaration, /*flags*/node.variableDeclaration.flags);
const destructure = createVariableStatement(undefined, list);
@@ -2751,7 +2806,7 @@ namespace ts {
setEmitFlags(thisArg, EmitFlags.NoSubstitution);
}
let resultingCall: CallExpression | BinaryExpression;
if (node.transformFlags & TransformFlags.ContainsSpreadElementExpression) {
if (node.transformFlags & TransformFlags.ContainsSpread) {
// [source]
// f(...a, b)
// x.m(...a, b)
@@ -2782,7 +2837,6 @@ namespace ts {
// _super.call(this, a)
// _super.m.call(this, a)
// _super.prototype.m.call(this, a)
resultingCall = createFunctionCall(
visitNode(target, visitor, isExpression),
visitNode(thisArg, visitor, isExpression),
@@ -2813,7 +2867,7 @@ namespace ts {
*/
function visitNewExpression(node: NewExpression): LeftHandSideExpression {
// We are here because we contain a SpreadElementExpression.
Debug.assert((node.transformFlags & TransformFlags.ContainsSpreadElementExpression) !== 0);
Debug.assert((node.transformFlags & TransformFlags.ContainsSpread) !== 0);
// [source]
// new C(...a)
@@ -2834,7 +2888,7 @@ namespace ts {
}
/**
* Transforms an array of Expression nodes that contains a SpreadElementExpression.
* Transforms an array of Expression nodes that contains a SpreadExpression.
*
* @param elements The array of Expression nodes.
* @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
@@ -2851,14 +2905,14 @@ namespace ts {
// expressions into an array literal.
const numElements = elements.length;
const segments = flatten(
spanMap(elements, partitionSpreadElement, (partition, visitPartition, _start, end) =>
spanMap(elements, partitionSpread, (partition, visitPartition, _start, end) =>
visitPartition(partition, multiLine, hasTrailingComma && end === numElements)
)
);
if (segments.length === 1) {
const firstElement = elements[0];
return needsUniqueCopy && isSpreadElementExpression(firstElement) && firstElement.expression.kind !== SyntaxKind.ArrayLiteralExpression
return needsUniqueCopy && isSpreadExpression(firstElement) && firstElement.expression.kind !== SyntaxKind.ArrayLiteralExpression
? createArraySlice(segments[0])
: segments[0];
}
@@ -2867,17 +2921,17 @@ namespace ts {
return createArrayConcat(segments.shift(), segments);
}
function partitionSpreadElement(node: Expression) {
return isSpreadElementExpression(node)
? visitSpanOfSpreadElements
: visitSpanOfNonSpreadElements;
function partitionSpread(node: Expression) {
return isSpreadExpression(node)
? visitSpanOfSpreads
: visitSpanOfNonSpreads;
}
function visitSpanOfSpreadElements(chunk: Expression[]): VisitResult<Expression> {
return map(chunk, visitExpressionOfSpreadElement);
function visitSpanOfSpreads(chunk: Expression[]): VisitResult<Expression> {
return map(chunk, visitExpressionOfSpread);
}
function visitSpanOfNonSpreadElements(chunk: Expression[], multiLine: boolean, hasTrailingComma: boolean): VisitResult<Expression> {
function visitSpanOfNonSpreads(chunk: Expression[], multiLine: boolean, hasTrailingComma: boolean): VisitResult<Expression> {
return createArrayLiteral(
visitNodes(createNodeArray(chunk, /*location*/ undefined, hasTrailingComma), visitor, isExpression),
/*location*/ undefined,
@@ -2885,12 +2939,16 @@ namespace ts {
);
}
function visitSpreadElement(node: SpreadElement) {
return visitNode(node.expression, visitor, isExpression);
}
/**
* Transforms the expression of a SpreadElementExpression node.
* Transforms the expression of a SpreadExpression node.
*
* @param node A SpreadElementExpression node.
* @param node A SpreadExpression node.
*/
function visitExpressionOfSpreadElement(node: SpreadElementExpression) {
function visitExpressionOfSpread(node: SpreadElement) {
return visitNode(node.expression, visitor, isExpression);
}
@@ -3071,19 +3129,6 @@ namespace ts {
: createIdentifier("_super");
}
function visitSourceFileNode(node: SourceFile): SourceFile {
const [prologue, remaining] = span(node.statements, isPrologueDirective);
const statements: Statement[] = [];
startLexicalEnvironment();
addRange(statements, prologue);
addCaptureThisForNodeIfNeeded(statements, node);
addRange(statements, visitNodes(createNodeArray(remaining), visitor, isStatement));
addRange(statements, endLexicalEnvironment());
const clone = getMutableClone(node);
clone.statements = createNodeArray(statements, /*location*/ node.statements);
return clone;
}
/**
* Called by the printer just before a node is printed.
*
@@ -3245,8 +3290,7 @@ namespace ts {
return false;
}
const parameter = singleOrUndefined(constructor.parameters);
if (!parameter || !nodeIsSynthesized(parameter) || !parameter.dotDotDotToken) {
if (some(constructor.parameters)) {
return false;
}
@@ -3266,12 +3310,36 @@ namespace ts {
}
const callArgument = singleOrUndefined((<CallExpression>statementExpression).arguments);
if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== SyntaxKind.SpreadElementExpression) {
if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== SyntaxKind.SpreadElement) {
return false;
}
const expression = (<SpreadElementExpression>callArgument).expression;
return isIdentifier(expression) && expression === parameter.name;
const expression = (<SpreadElement>callArgument).expression;
return isIdentifier(expression) && expression.text === "arguments";
}
}
function createExtendsHelper(context: TransformationContext, name: Identifier) {
context.requestEmitHelper(extendsHelper);
return createCall(
getHelperName("__extends"),
/*typeArguments*/ undefined,
[
name,
createIdentifier("_super")
]
);
}
const extendsHelper: EmitHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
text: `
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};`
};
}
+52 -62
View File
@@ -17,85 +17,75 @@ namespace ts {
}
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.ES2016) {
return visitorWorker(node);
}
else if (node.transformFlags & TransformFlags.ContainsES2016) {
return visitEachChild(node, visitor, context);
}
else {
if ((node.transformFlags & TransformFlags.ContainsES2016) === 0) {
return node;
}
}
function visitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(<BinaryExpression>node);
default:
Debug.failBadSyntaxKind(node);
return visitEachChild(node, visitor, context);
}
}
function visitBinaryExpression(node: BinaryExpression): Expression {
// We are here because ES2016 adds support for the exponentiation operator.
switch (node.operatorToken.kind) {
case SyntaxKind.AsteriskAsteriskEqualsToken:
return visitExponentiationAssignmentExpression(node);
case SyntaxKind.AsteriskAsteriskToken:
return visitExponentiationExpression(node);
default:
return visitEachChild(node, visitor, context);
}
}
function visitExponentiationAssignmentExpression(node: BinaryExpression) {
let target: Expression;
let value: Expression;
const left = visitNode(node.left, visitor, isExpression);
const right = visitNode(node.right, visitor, isExpression);
if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskEqualsToken) {
let target: Expression;
let value: Expression;
if (isElementAccessExpression(left)) {
// Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
const expressionTemp = createTempVariable(hoistVariableDeclaration);
const argumentExpressionTemp = createTempVariable(hoistVariableDeclaration);
target = createElementAccess(
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression),
/*location*/ left
);
value = createElementAccess(
expressionTemp,
argumentExpressionTemp,
/*location*/ left
);
}
else if (isPropertyAccessExpression(left)) {
// Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
const expressionTemp = createTempVariable(hoistVariableDeclaration);
target = createPropertyAccess(
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
left.name,
/*location*/ left
);
value = createPropertyAccess(
expressionTemp,
left.name,
/*location*/ left
);
}
else {
// Transforms `a **= b` into `a = Math.pow(a, b)`
target = left;
value = left;
}
return createAssignment(target, createMathPow(value, right, /*location*/ node), /*location*/ node);
if (isElementAccessExpression(left)) {
// Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
const expressionTemp = createTempVariable(hoistVariableDeclaration);
const argumentExpressionTemp = createTempVariable(hoistVariableDeclaration);
target = createElementAccess(
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression),
/*location*/ left
);
value = createElementAccess(
expressionTemp,
argumentExpressionTemp,
/*location*/ left
);
}
else if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskToken) {
// Transforms `a ** b` into `Math.pow(a, b)`
return createMathPow(left, right, /*location*/ node);
else if (isPropertyAccessExpression(left)) {
// Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
const expressionTemp = createTempVariable(hoistVariableDeclaration);
target = createPropertyAccess(
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
left.name,
/*location*/ left
);
value = createPropertyAccess(
expressionTemp,
left.name,
/*location*/ left
);
}
else {
Debug.failBadSyntaxKind(node);
return visitEachChild(node, visitor, context);
// Transforms `a **= b` into `a = Math.pow(a, b)`
target = left;
value = left;
}
return createAssignment(target, createMathPow(value, right, /*location*/ node), /*location*/ node);
}
function visitExponentiationExpression(node: BinaryExpression) {
// Transforms `a ** b` into `Math.pow(a, b)`
const left = visitNode(node.left, visitor, isExpression);
const right = visitNode(node.right, visitor, isExpression);
return createMathPow(left, right, /*location*/ node);
}
}
}
+149 -143
View File
@@ -5,15 +5,15 @@
namespace ts {
type SuperContainer = ClassDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration;
const enum ES2017SubstitutionFlags {
/** Enables substitutions for async methods with `super` calls. */
AsyncMethodsWithSuper = 1 << 0
}
export function transformES2017(context: TransformationContext) {
const enum ES2017SubstitutionFlags {
/** Enables substitutions for async methods with `super` calls. */
AsyncMethodsWithSuper = 1 << 0
}
const {
startLexicalEnvironment,
resumeLexicalEnvironment,
endLexicalEnvironment,
} = context;
@@ -22,19 +22,14 @@ namespace ts {
const languageVersion = getEmitScriptTarget(compilerOptions);
// These variables contain state that changes as we descend into the tree.
let currentSourceFileExternalHelpersModuleName: Identifier;
let currentSourceFile: SourceFile;
/**
* 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.
@@ -49,8 +44,6 @@ namespace ts {
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
let currentScope: SourceFile | Block | ModuleBlock | CaseBlock;
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
@@ -58,23 +51,20 @@ namespace ts {
return node;
}
currentSourceFileExternalHelpersModuleName = node.externalHelpersModuleName;
currentSourceFile = node;
return visitEachChild(node, visitor, context);
const visited = visitEachChild(node, visitor, context);
addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
return visited;
}
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);
if ((node.transformFlags & TransformFlags.ContainsES2017) === 0) {
return node;
}
return node;
}
function visitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.AsyncKeyword:
// ES2017 async modifier should be elided for targets < ES2017
@@ -101,17 +91,16 @@ namespace ts {
return visitArrowFunction(<ArrowFunction>node);
default:
Debug.failBadSyntaxKind(node);
return node;
return visitEachChild(node, visitor, context);
}
}
/**
* Visits an await expression.
* Visits an AwaitExpression node.
*
* This function will be called any time a ES2017 await expression is encountered.
*
* @param node The await expression node.
* @param node The node to visit.
*/
function visitAwaitExpression(node: AwaitExpression): Expression {
return setOriginalNode(
@@ -125,143 +114,102 @@ namespace ts {
}
/**
* Visits a method declaration of a class.
* Visits a MethodDeclaration node.
*
* This function will be called when one of the following conditions are met:
* - The node is marked as async
*
* @param node The method node.
* @param node The node to visit.
*/
function visitMethodDeclaration(node: MethodDeclaration) {
if (!isAsyncFunctionLike(node)) {
return node;
}
const method = createMethod(
return updateMethod(
node,
/*decorators*/ undefined,
visitNodes(node.modifiers, visitor, isModifier),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ node
isAsyncFunctionLike(node)
? transformAsyncFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
// 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.
* Visits a FunctionDeclaration node.
*
* This function will be called when one of the following conditions are met:
* - The node is marked async
*
* @param node The function node.
* @param node The node to visit.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult<Statement> {
if (!isAsyncFunctionLike(node)) {
return node;
}
const func = createFunctionDeclaration(
return updateFunctionDeclaration(
node,
/*decorators*/ undefined,
visitNodes(node.modifiers, visitor, isModifier),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ node
isAsyncFunctionLike(node)
? transformAsyncFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
setOriginalNode(func, node);
return func;
}
/**
* Visits a function expression node.
* Visits a FunctionExpression 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.
* @param node The node to visit.
*/
function visitFunctionExpression(node: FunctionExpression): Expression {
if (!isAsyncFunctionLike(node)) {
return node;
}
if (nodeIsMissing(node.body)) {
return createOmittedExpression();
}
const func = createFunctionExpression(
return updateFunctionExpression(
node,
/*modifiers*/ undefined,
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ node
isAsyncFunctionLike(node)
? transformAsyncFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
setOriginalNode(func, node);
return func;
}
/**
* @remarks
* Visits an ArrowFunction.
*
* This function will be called when one of the following conditions are met:
* - The node is marked async
*
* @param node The node to visit.
*/
function visitArrowFunction(node: ArrowFunction) {
if (!isAsyncFunctionLike(node)) {
return node;
}
const func = createArrowFunction(
return updateArrowFunction(
node,
visitNodes(node.modifiers, visitor, isModifier),
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
node.equalsGreaterThanToken,
transformConciseBody(node),
/*location*/ node
isAsyncFunctionLike(node)
? transformAsyncFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
setOriginalNode(func, node);
return func;
}
function transformFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody {
return <FunctionBody>transformAsyncFunctionBody(node);
}
function transformAsyncFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody;
function transformAsyncFunctionBody(node: ArrowFunction): ConciseBody;
function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody {
resumeLexicalEnvironment();
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 original = getOriginalNode(node, isFunctionLike);
const nodeType = original.type;
const promiseConstructor = languageVersion < ScriptTarget.ES2015 ? getPromiseConstructor(nodeType) : undefined;
@@ -274,14 +222,13 @@ namespace ts {
// 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,
context,
hasLexicalArguments,
promiseConstructor,
transformFunctionBodyWorker(<Block>node.body, statementOffset)
@@ -289,6 +236,8 @@ namespace ts {
)
);
addRange(statements, endLexicalEnvironment());
const block = createBlock(statements, /*location*/ node.body, /*multiLine*/ true);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
@@ -296,57 +245,56 @@ namespace ts {
if (languageVersion >= ScriptTarget.ES2015) {
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) {
enableSubstitutionForAsyncMethodsWithSuper();
setEmitFlags(block, EmitFlags.EmitAdvancedSuperHelper);
addEmitHelper(block, advancedAsyncSuperHelper);
}
else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) {
enableSubstitutionForAsyncMethodsWithSuper();
setEmitFlags(block, EmitFlags.EmitSuperHelper);
addEmitHelper(block, asyncSuperHelper);
}
}
return block;
}
else {
return createAwaiterHelper(
currentSourceFileExternalHelpersModuleName,
const expression = createAwaiterHelper(
context,
hasLexicalArguments,
promiseConstructor,
<Block>transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ true)
transformFunctionBodyWorker(node.body)
);
const declarations = endLexicalEnvironment();
if (some(declarations)) {
const block = convertToFunctionBody(expression);
return updateBlock(block, createNodeArray(concatenate(block.statements, declarations), block.statements));
}
return expression;
}
}
function transformConciseBodyWorker(body: Block | Expression, forceBlockFunctionBody: boolean) {
function transformFunctionBodyWorker(body: ConciseBody, start?: number) {
if (isBlock(body)) {
return transformFunctionBodyWorker(body);
return updateBlock(body, visitLexicalEnvironment(body.statements, visitor, context, start));
}
else {
startLexicalEnvironment();
const visited: Expression | Block = visitNode(body, visitor, isConciseBody);
const visited = convertToFunctionBody(visitNode(body, visitor, isConciseBody));
const declarations = endLexicalEnvironment();
const merged = mergeFunctionBodyLexicalEnvironment(visited, declarations);
if (forceBlockFunctionBody && !isBlock(merged)) {
return createBlock([
createReturn(<Expression>merged)
]);
}
else {
return merged;
}
return updateBlock(visited, createNodeArray(concatenate(visited.statements, declarations), visited.statements));
}
}
function getPromiseConstructor(type: TypeNode) {
if (type) {
const typeName = getEntityNameFromTypeNode(type);
if (typeName && isEntityName(typeName)) {
const serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
|| serializationKind === TypeReferenceSerializationKind.Unknown) {
return typeName;
}
const typeName = type && getEntityNameFromTypeNode(type);
if (typeName && isEntityName(typeName)) {
const serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
|| serializationKind === TypeReferenceSerializationKind.Unknown) {
return typeName;
}
}
return undefined;
}
@@ -452,18 +400,17 @@ namespace ts {
* @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)) {
const savedCurrentSuperContainer = currentSuperContainer;
currentSuperContainer = node;
previousOnEmitNode(emitContext, node, emitCallback);
currentSuperContainer = savedCurrentSuperContainer;
}
else {
previousOnEmitNode(emitContext, node, emitCallback);
}
previousOnEmitNode(emitContext, node, emitCallback);
applicableSubstitutions = savedApplicableSubstitutions;
currentSuperContainer = savedCurrentSuperContainer;
}
/**
@@ -509,4 +456,63 @@ namespace ts {
&& resolver.getNodeCheckFlags(currentSuperContainer) & (NodeCheckFlags.AsyncMethodWithSuper | NodeCheckFlags.AsyncMethodWithSuperBinding);
}
}
function createAwaiterHelper(context: TransformationContext, hasLexicalArguments: boolean, promiseConstructor: EntityName | Expression, body: Block) {
context.requestEmitHelper(awaiterHelper);
const generatorFunc = createFunctionExpression(
/*modifiers*/ undefined,
createToken(SyntaxKind.AsteriskToken),
/*name*/ undefined,
/*typeParameters*/ undefined,
/*parameters*/ [],
/*type*/ undefined,
body
);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= EmitFlags.AsyncFunctionBody;
return createCall(
getHelperName("__awaiter"),
/*typeArguments*/ undefined,
[
createThis(),
hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(),
promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(),
generatorFunc
]
);
}
const awaiterHelper: EmitHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: `
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 step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
};`
};
const asyncSuperHelper: EmitHelper = {
name: "typescript:async-super",
scoped: true,
text: `
const _super = name => super[name];`
};
const advancedAsyncSuperHelper: EmitHelper = {
name: "typescript:advanced-async-super",
scoped: true,
text: `
const _super = (function (geti, seti) {
const cache = Object.create(null);
return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });
})(name => super[name], (name, value) => super[name] = value);`
};
}
+412
View File
@@ -0,0 +1,412 @@
/// <reference path="../factory.ts" />
/// <reference path="../visitor.ts" />
/*@internal*/
namespace ts {
export function transformESNext(context: TransformationContext) {
const {
resumeLexicalEnvironment,
endLexicalEnvironment
} = context;
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
return node;
}
const visited = visitEachChild(node, visitor, context);
addEmitHelpers(visited, context.readEmitHelpers());
return visited;
}
function visitor(node: Node): VisitResult<Node> {
return visitorWorker(node, /*noDestructuringValue*/ false);
}
function visitorNoDestructuringValue(node: Node): VisitResult<Node> {
return visitorWorker(node, /*noDestructuringValue*/ true);
}
function visitorWorker(node: Node, noDestructuringValue: boolean): VisitResult<Node> {
if ((node.transformFlags & TransformFlags.ContainsESNext) === 0) {
return node;
}
switch (node.kind) {
case SyntaxKind.ObjectLiteralExpression:
return visitObjectLiteralExpression(node as ObjectLiteralExpression);
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(node as BinaryExpression, noDestructuringValue);
case SyntaxKind.VariableDeclaration:
return visitVariableDeclaration(node as VariableDeclaration);
case SyntaxKind.ForOfStatement:
return visitForOfStatement(node as ForOfStatement);
case SyntaxKind.ForStatement:
return visitForStatement(node as ForStatement);
case SyntaxKind.VoidExpression:
return visitVoidExpression(node as VoidExpression);
case SyntaxKind.Constructor:
return visitConstructorDeclaration(node as ConstructorDeclaration);
case SyntaxKind.MethodDeclaration:
return visitMethodDeclaration(node as MethodDeclaration);
case SyntaxKind.GetAccessor:
return visitGetAccessorDeclaration(node as GetAccessorDeclaration);
case SyntaxKind.SetAccessor:
return visitSetAccessorDeclaration(node as SetAccessorDeclaration);
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.FunctionExpression:
return visitFunctionExpression(node as FunctionExpression);
case SyntaxKind.ArrowFunction:
return visitArrowFunction(node as ArrowFunction);
case SyntaxKind.Parameter:
return visitParameter(node as ParameterDeclaration);
case SyntaxKind.ExpressionStatement:
return visitExpressionStatement(node as ExpressionStatement);
case SyntaxKind.ParenthesizedExpression:
return visitParenthesizedExpression(node as ParenthesizedExpression, noDestructuringValue);
default:
return visitEachChild(node, visitor, context);
}
}
function chunkObjectLiteralElements(elements: ObjectLiteralElement[]): Expression[] {
let chunkObject: (ShorthandPropertyAssignment | PropertyAssignment)[];
const objects: Expression[] = [];
for (const e of elements) {
if (e.kind === SyntaxKind.SpreadAssignment) {
if (chunkObject) {
objects.push(createObjectLiteral(chunkObject));
chunkObject = undefined;
}
const target = (e as SpreadAssignment).expression;
objects.push(visitNode(target, visitor, isExpression));
}
else {
if (!chunkObject) {
chunkObject = [];
}
if (e.kind === SyntaxKind.PropertyAssignment) {
const p = e as PropertyAssignment;
chunkObject.push(createPropertyAssignment(p.name, visitNode(p.initializer, visitor, isExpression)));
}
else {
chunkObject.push(e as ShorthandPropertyAssignment);
}
}
}
if (chunkObject) {
objects.push(createObjectLiteral(chunkObject));
}
return objects;
}
function visitObjectLiteralExpression(node: ObjectLiteralExpression): Expression {
if (node.transformFlags & TransformFlags.ContainsObjectSpread) {
// spread elements emit like so:
// non-spread elements are chunked together into object literals, and then all are passed to __assign:
// { a, ...o, b } => __assign({a}, o, {b});
// If the first element is a spread element, then the first argument to __assign is {}:
// { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2)
const objects = chunkObjectLiteralElements(node.properties);
if (objects.length && objects[0].kind !== SyntaxKind.ObjectLiteralExpression) {
objects.unshift(createObjectLiteral());
}
return createAssignHelper(context, objects);
}
return visitEachChild(node, visitor, context);
}
function visitExpressionStatement(node: ExpressionStatement): ExpressionStatement {
return visitEachChild(node, visitorNoDestructuringValue, context);
}
function visitParenthesizedExpression(node: ParenthesizedExpression, noDestructuringValue: boolean): ParenthesizedExpression {
return visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
}
/**
* Visits a BinaryExpression that contains a destructuring assignment.
*
* @param node A BinaryExpression node.
*/
function visitBinaryExpression(node: BinaryExpression, noDestructuringValue: boolean): Expression {
if (isDestructuringAssignment(node) && node.left.transformFlags & TransformFlags.ContainsObjectRest) {
return flattenDestructuringAssignment(
node,
visitor,
context,
FlattenLevel.ObjectRest,
!noDestructuringValue
);
}
else if (node.operatorToken.kind === SyntaxKind.CommaToken) {
return updateBinary(
node,
visitNode(node.left, visitorNoDestructuringValue, isExpression),
visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, isExpression)
);
}
return visitEachChild(node, visitor, context);
}
/**
* Visits a VariableDeclaration node with a binding pattern.
*
* @param node A VariableDeclaration node.
*/
function visitVariableDeclaration(node: VariableDeclaration): VisitResult<VariableDeclaration> {
// If we are here it is because the name contains a binding pattern with a rest somewhere in it.
if (isBindingPattern(node.name) && node.name.transformFlags & TransformFlags.ContainsObjectRest) {
return flattenDestructuringBinding(
node,
visitor,
context,
FlattenLevel.ObjectRest
);
}
return visitEachChild(node, visitor, context);
}
function visitForStatement(node: ForStatement): VisitResult<Statement> {
return updateFor(
node,
visitNode(node.initializer, visitorNoDestructuringValue, isForInitializer),
visitNode(node.condition, visitor, isExpression),
visitNode(node.incrementor, visitor, isExpression),
visitNode(node.statement, visitor, isStatement)
);
}
function visitVoidExpression(node: VoidExpression) {
return visitEachChild(node, visitorNoDestructuringValue, context);
}
/**
* Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
*
* @param node A ForOfStatement.
*/
function visitForOfStatement(node: ForOfStatement): VisitResult<Statement> {
let leadingStatements: Statement[];
let temp: Identifier;
const initializer = skipParentheses(node.initializer);
if (initializer.transformFlags & TransformFlags.ContainsObjectRest) {
if (isVariableDeclarationList(initializer)) {
temp = createTempVariable(/*recordTempVariable*/ undefined);
const firstDeclaration = firstOrUndefined(initializer.declarations);
const declarations = flattenDestructuringBinding(
firstDeclaration,
visitor,
context,
FlattenLevel.ObjectRest,
temp,
/*doNotRecordTempVariablesInLine*/ false,
/*skipInitializer*/ true,
);
if (some(declarations)) {
const statement = createVariableStatement(
/*modifiers*/ undefined,
updateVariableDeclarationList(initializer, declarations),
/*location*/ initializer
);
leadingStatements = append(leadingStatements, statement);
}
}
else if (isAssignmentPattern(initializer)) {
temp = createTempVariable(/*recordTempVariable*/ undefined);
const expression = flattenDestructuringAssignment(
aggregateTransformFlags(createAssignment(initializer, temp, /*location*/ node.initializer)),
visitor,
context,
FlattenLevel.ObjectRest
);
leadingStatements = append(leadingStatements, createStatement(expression, /*location*/ node.initializer));
}
}
if (temp) {
const expression = visitNode(node.expression, visitor, isExpression);
const statement = visitNode(node.statement, visitor, isStatement);
const block = isBlock(statement)
? updateBlock(statement, createNodeArray(concatenate(leadingStatements, statement.statements), statement.statements))
: createBlock(append(leadingStatements, statement), statement, /*multiLine*/ true);
return updateForOf(
node,
createVariableDeclarationList(
[
createVariableDeclaration(temp, /*type*/ undefined, /*initializer*/ undefined, node.initializer)
],
node.initializer,
NodeFlags.Let
),
expression,
block
);
}
return visitEachChild(node, visitor, context);
}
function visitParameter(node: ParameterDeclaration): ParameterDeclaration {
if (node.transformFlags & TransformFlags.ContainsObjectRest) {
// Binding patterns are converted into a generated name and are
// evaluated inside the function body.
return updateParameter(
node,
/*decorators*/ undefined,
/*modifiers*/ undefined,
node.dotDotDotToken,
getGeneratedNameForNode(node),
/*type*/ undefined,
visitNode(node.initializer, visitor, isExpression)
);
}
return visitEachChild(node, visitor, context);
}
function visitConstructorDeclaration(node: ConstructorDeclaration) {
return updateConstructor(
node,
/*decorators*/ undefined,
node.modifiers,
visitParameterList(node.parameters, visitor, context),
transformFunctionBody(node)
);
}
function visitGetAccessorDeclaration(node: GetAccessorDeclaration) {
return updateGetAccessor(
node,
/*decorators*/ undefined,
node.modifiers,
visitNode(node.name, visitor, isPropertyName),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
);
}
function visitSetAccessorDeclaration(node: SetAccessorDeclaration) {
return updateSetAccessor(
node,
/*decorators*/ undefined,
node.modifiers,
visitNode(node.name, visitor, isPropertyName),
visitParameterList(node.parameters, visitor, context),
transformFunctionBody(node)
);
}
function visitMethodDeclaration(node: MethodDeclaration) {
return updateMethod(
node,
/*decorators*/ undefined,
node.modifiers,
visitNode(node.name, visitor, isPropertyName),
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
);
}
function visitFunctionDeclaration(node: FunctionDeclaration) {
return updateFunctionDeclaration(
node,
/*decorators*/ undefined,
node.modifiers,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
);
}
function visitArrowFunction(node: ArrowFunction) {
return updateArrowFunction(
node,
node.modifiers,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
);
}
function visitFunctionExpression(node: FunctionExpression) {
return updateFunctionExpression(
node,
node.modifiers,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
);
}
function transformFunctionBody(node: FunctionDeclaration | FunctionExpression | ConstructorDeclaration | MethodDeclaration | AccessorDeclaration): FunctionBody;
function transformFunctionBody(node: ArrowFunction): ConciseBody;
function transformFunctionBody(node: FunctionLikeDeclaration): ConciseBody {
resumeLexicalEnvironment();
let leadingStatements: Statement[];
for (const parameter of node.parameters) {
if (parameter.transformFlags & TransformFlags.ContainsObjectRest) {
const temp = getGeneratedNameForNode(parameter);
const declarations = flattenDestructuringBinding(
parameter,
visitor,
context,
FlattenLevel.ObjectRest,
temp,
/*doNotRecordTempVariablesInLine*/ false,
/*skipInitializer*/ true,
);
if (some(declarations)) {
const statement = createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList(
declarations
)
);
setEmitFlags(statement, EmitFlags.CustomPrologue);
leadingStatements = append(leadingStatements, statement);
}
}
}
const body = visitNode(node.body, visitor, isConciseBody);
const trailingStatements = endLexicalEnvironment();
if (some(leadingStatements) || some(trailingStatements)) {
const block = convertToFunctionBody(body, /*multiLine*/ true);
return updateBlock(block, createNodeArray(concatenate(concatenate(leadingStatements, block.statements), trailingStatements), block.statements));
}
return body;
}
}
const assignHelper: EmitHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
text: `
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};`
};
export function createAssignHelper(context: TransformationContext, attributesSegments: Expression[]) {
context.requestEmitHelper(assignHelper);
return createCall(
getHelperName("__assign"),
/*typeArguments*/ undefined,
attributesSegments
);
}
}
+152 -42
View File
@@ -227,7 +227,7 @@ namespace ts {
export function transformGenerators(context: TransformationContext) {
const {
startLexicalEnvironment,
resumeLexicalEnvironment,
endLexicalEnvironment,
hoistFunctionDeclaration,
hoistVariableDeclaration,
@@ -291,17 +291,18 @@ namespace ts {
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
if (isDeclarationFile(node)
|| (node.transformFlags & TransformFlags.ContainsGenerator) === 0) {
return node;
}
if (node.transformFlags & TransformFlags.ContainsGenerator) {
currentSourceFile = node;
node = visitEachChild(node, visitor, context);
currentSourceFile = undefined;
}
currentSourceFile = node;
return node;
const visited = visitEachChild(node, visitor, context);
addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
return visited;
}
/**
@@ -449,11 +450,11 @@ namespace ts {
node = setOriginalNode(
createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
node.modifiers,
/*asteriskToken*/ undefined,
node.name,
/*typeParameters*/ undefined,
node.parameters,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformGeneratorFunctionBody(node.body),
/*location*/ node
@@ -500,7 +501,7 @@ namespace ts {
/*asteriskToken*/ undefined,
node.name,
/*typeParameters*/ undefined,
node.parameters,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformGeneratorFunctionBody(node.body),
/*location*/ node
@@ -578,7 +579,7 @@ namespace ts {
state = createTempVariable(/*recordTempVariable*/ undefined);
// Build the generator
startLexicalEnvironment();
resumeLexicalEnvironment();
const statementOffset = addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor);
@@ -946,7 +947,7 @@ namespace ts {
* @param node The node to visit.
*/
function visitArrayLiteralExpression(node: ArrayLiteralExpression) {
return visitElements(node.elements, node.multiLine);
return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
}
/**
@@ -956,7 +957,7 @@ namespace ts {
* @param elements The elements to visit.
* @param multiLine Whether array literals created should be emitted on multiple lines.
*/
function visitElements(elements: NodeArray<Expression>, _multiLine?: boolean) {
function visitElements(elements: NodeArray<Expression>, leadingElement?: Expression, location?: TextRange, multiLine?: boolean) {
// [source]
// ar = [1, yield, 2];
//
@@ -971,18 +972,22 @@ namespace ts {
const temp = declareLocal();
let hasAssignedTemp = false;
if (numInitialElements > 0) {
const initialElements = visitNodes(elements, visitor, isExpression, 0, numInitialElements);
emitAssignment(temp,
createArrayLiteral(
visitNodes(elements, visitor, isExpression, 0, numInitialElements)
leadingElement
? [leadingElement, ...initialElements]
: initialElements
)
);
leadingElement = undefined;
hasAssignedTemp = true;
}
const expressions = reduceLeft(elements, reduceElement, <Expression[]>[], numInitialElements);
return hasAssignedTemp
? createArrayConcat(temp, [createArrayLiteral(expressions)])
: createArrayLiteral(expressions);
? createArrayConcat(temp, [createArrayLiteral(expressions, /*location*/ undefined, multiLine)])
: createArrayLiteral(leadingElement ? [leadingElement, ...expressions] : expressions, location, multiLine);
function reduceElement(expressions: Expression[], element: Expression) {
if (containsYield(element) && expressions.length > 0) {
@@ -991,11 +996,16 @@ namespace ts {
hasAssignedTemp
? createArrayConcat(
temp,
[createArrayLiteral(expressions)]
[createArrayLiteral(expressions, /*location*/ undefined, multiLine)]
)
: createArrayLiteral(
leadingElement ? [leadingElement, ...expressions] : expressions,
/*location*/ undefined,
multiLine
)
: createArrayLiteral(expressions)
);
hasAssignedTemp = true;
leadingElement = undefined;
expressions = [];
}
@@ -1131,7 +1141,10 @@ namespace ts {
createFunctionApply(
cacheExpression(visitNode(target, visitor, isExpression)),
thisArg,
visitElements(node.arguments)
visitElements(
node.arguments,
/*leadingElement*/ createVoidZero()
)
),
/*typeArguments*/ undefined,
[],
@@ -2585,28 +2598,24 @@ namespace ts {
withBlockStack = undefined;
const buildResult = buildStatements();
return createCall(
createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"),
/*typeArguments*/ undefined,
[
createThis(),
setEmitFlags(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
[createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)],
/*type*/ undefined,
createBlock(
buildResult,
/*location*/ undefined,
/*multiLine*/ buildResult.length > 0
)
),
EmitFlags.ReuseTempVariableScope
)
]
return createGeneratorHelper(
context,
setEmitFlags(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
[createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)],
/*type*/ undefined,
createBlock(
buildResult,
/*location*/ undefined,
/*multiLine*/ buildResult.length > 0
)
),
EmitFlags.ReuseTempVariableScope
)
);
}
@@ -3082,4 +3091,105 @@ namespace ts {
);
}
}
function createGeneratorHelper(context: TransformationContext, body: FunctionExpression) {
context.requestEmitHelper(generatorHelper);
return createCall(
getHelperName("__generator"),
/*typeArguments*/ undefined,
[createThis(), body]);
}
// The __generator helper is used by down-level transformations to emulate the runtime
// semantics of an ES2015 generator function. When called, this helper returns an
// object that implements the Iterator protocol, in that it has `next`, `return`, and
// `throw` methods that step through the generator when invoked.
//
// parameters:
// thisArg The value to use as the `this` binding for the transformed generator body.
// body A function that acts as the transformed generator body.
//
// variables:
// _ Persistent state for the generator that is shared between the helper and the
// generator body. The state object has the following members:
// sent() - A method that returns or throws the current completion value.
// label - The next point at which to resume evaluation of the generator body.
// trys - A stack of protected regions (try/catch/finally blocks).
// ops - A stack of pending instructions when inside of a finally block.
// f A value indicating whether the generator is executing.
// y An iterator to delegate for a yield*.
// t A temporary variable that holds one of the following values (note that these
// cases do not overlap):
// - The completion value when resuming from a `yield` or `yield*`.
// - The error value for a catch block.
// - The current protected region (array of try/catch/finally/end labels).
// - The verb (`next`, `throw`, or `return` method) to delegate to the expression
// of a `yield*`.
// - The result of evaluating the verb delegated to the expression of a `yield*`.
//
// functions:
// verb(n) Creates a bound callback to the `step` function for opcode `n`.
// step(op) Evaluates opcodes in a generator body until execution is suspended or
// completed.
//
// The __generator helper understands a limited set of instructions:
// 0: next(value?) - Start or resume the generator with the specified value.
// 1: throw(error) - Resume the generator with an exception. If the generator is
// suspended inside of one or more protected regions, evaluates
// any intervening finally blocks between the current label and
// the nearest catch block or function boundary. If uncaught, the
// exception is thrown to the caller.
// 2: return(value?) - Resume the generator as if with a return. If the generator is
// suspended inside of one or more protected regions, evaluates any
// intervening finally blocks.
// 3: break(label) - Jump to the specified label. If the label is outside of the
// current protected region, evaluates any intervening finally
// blocks.
// 4: yield(value?) - Yield execution to the caller with an optional value. When
// resumed, the generator will continue at the next label.
// 5: yield*(value) - Delegates evaluation to the supplied iterator. When
// delegation completes, the generator will continue at the next
// label.
// 6: catch(error) - Handles an exception thrown from within the generator body. If
// the current label is inside of one or more protected regions,
// evaluates any intervening finally blocks between the current
// label and the nearest catch block or function boundary. If
// uncaught, the exception is thrown to the caller.
// 7: endfinally - Ends a finally block, resuming the last instruction prior to
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
const generatorHelper: EmitHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
text: `
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;
return { next: verb(0), "throw": verb(1), "return": verb(2) };
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};`
};
}
+270 -270
View File
@@ -1,13 +1,13 @@
/// <reference path="../factory.ts" />
/// <reference path="../visitor.ts" />
/// <reference path="./esnext.ts" />
/*@internal*/
namespace ts {
const entities: Map<number> = createEntitiesMap();
export function transformJsx(context: TransformationContext) {
const compilerOptions = context.getCompilerOptions();
let currentSourceFile: SourceFile;
return transformSourceFile;
/**
@@ -21,18 +21,18 @@ namespace ts {
}
currentSourceFile = node;
node = visitEachChild(node, visitor, context);
const visited = visitEachChild(node, visitor, context);
addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
return node;
return visited;
}
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.Jsx) {
if (node.transformFlags & TransformFlags.ContainsJsx) {
return visitorWorker(node);
}
else if (node.transformFlags & TransformFlags.ContainsJsx) {
return visitEachChild(node, visitor, context);
}
else {
return node;
}
@@ -50,8 +50,7 @@ namespace ts {
return visitJsxExpression(<JsxExpression>node);
default:
Debug.failBadSyntaxKind(node);
return undefined;
return visitEachChild(node, visitor, context);
}
}
@@ -109,11 +108,14 @@ namespace ts {
// Either emit one big object literal (no spread attribs), or
// a call to the __assign helper.
objectProperties = singleOrUndefined(segments)
|| createAssignHelper(currentSourceFile.externalHelpersModuleName, segments);
objectProperties = singleOrUndefined(segments);
if (!objectProperties) {
objectProperties = createAssignHelper(context, segments);
}
}
const element = createReactCreateElement(
const element = createExpressionForJsxElement(
context.getEmitResolver().getJsxFactoryEntity(),
compilerOptions.reactNamespace,
tagName,
objectProperties,
@@ -275,261 +277,259 @@ namespace ts {
}
}
function createEntitiesMap(): Map<number> {
return createMap<number>({
"quot": 0x0022,
"amp": 0x0026,
"apos": 0x0027,
"lt": 0x003C,
"gt": 0x003E,
"nbsp": 0x00A0,
"iexcl": 0x00A1,
"cent": 0x00A2,
"pound": 0x00A3,
"curren": 0x00A4,
"yen": 0x00A5,
"brvbar": 0x00A6,
"sect": 0x00A7,
"uml": 0x00A8,
"copy": 0x00A9,
"ordf": 0x00AA,
"laquo": 0x00AB,
"not": 0x00AC,
"shy": 0x00AD,
"reg": 0x00AE,
"macr": 0x00AF,
"deg": 0x00B0,
"plusmn": 0x00B1,
"sup2": 0x00B2,
"sup3": 0x00B3,
"acute": 0x00B4,
"micro": 0x00B5,
"para": 0x00B6,
"middot": 0x00B7,
"cedil": 0x00B8,
"sup1": 0x00B9,
"ordm": 0x00BA,
"raquo": 0x00BB,
"frac14": 0x00BC,
"frac12": 0x00BD,
"frac34": 0x00BE,
"iquest": 0x00BF,
"Agrave": 0x00C0,
"Aacute": 0x00C1,
"Acirc": 0x00C2,
"Atilde": 0x00C3,
"Auml": 0x00C4,
"Aring": 0x00C5,
"AElig": 0x00C6,
"Ccedil": 0x00C7,
"Egrave": 0x00C8,
"Eacute": 0x00C9,
"Ecirc": 0x00CA,
"Euml": 0x00CB,
"Igrave": 0x00CC,
"Iacute": 0x00CD,
"Icirc": 0x00CE,
"Iuml": 0x00CF,
"ETH": 0x00D0,
"Ntilde": 0x00D1,
"Ograve": 0x00D2,
"Oacute": 0x00D3,
"Ocirc": 0x00D4,
"Otilde": 0x00D5,
"Ouml": 0x00D6,
"times": 0x00D7,
"Oslash": 0x00D8,
"Ugrave": 0x00D9,
"Uacute": 0x00DA,
"Ucirc": 0x00DB,
"Uuml": 0x00DC,
"Yacute": 0x00DD,
"THORN": 0x00DE,
"szlig": 0x00DF,
"agrave": 0x00E0,
"aacute": 0x00E1,
"acirc": 0x00E2,
"atilde": 0x00E3,
"auml": 0x00E4,
"aring": 0x00E5,
"aelig": 0x00E6,
"ccedil": 0x00E7,
"egrave": 0x00E8,
"eacute": 0x00E9,
"ecirc": 0x00EA,
"euml": 0x00EB,
"igrave": 0x00EC,
"iacute": 0x00ED,
"icirc": 0x00EE,
"iuml": 0x00EF,
"eth": 0x00F0,
"ntilde": 0x00F1,
"ograve": 0x00F2,
"oacute": 0x00F3,
"ocirc": 0x00F4,
"otilde": 0x00F5,
"ouml": 0x00F6,
"divide": 0x00F7,
"oslash": 0x00F8,
"ugrave": 0x00F9,
"uacute": 0x00FA,
"ucirc": 0x00FB,
"uuml": 0x00FC,
"yacute": 0x00FD,
"thorn": 0x00FE,
"yuml": 0x00FF,
"OElig": 0x0152,
"oelig": 0x0153,
"Scaron": 0x0160,
"scaron": 0x0161,
"Yuml": 0x0178,
"fnof": 0x0192,
"circ": 0x02C6,
"tilde": 0x02DC,
"Alpha": 0x0391,
"Beta": 0x0392,
"Gamma": 0x0393,
"Delta": 0x0394,
"Epsilon": 0x0395,
"Zeta": 0x0396,
"Eta": 0x0397,
"Theta": 0x0398,
"Iota": 0x0399,
"Kappa": 0x039A,
"Lambda": 0x039B,
"Mu": 0x039C,
"Nu": 0x039D,
"Xi": 0x039E,
"Omicron": 0x039F,
"Pi": 0x03A0,
"Rho": 0x03A1,
"Sigma": 0x03A3,
"Tau": 0x03A4,
"Upsilon": 0x03A5,
"Phi": 0x03A6,
"Chi": 0x03A7,
"Psi": 0x03A8,
"Omega": 0x03A9,
"alpha": 0x03B1,
"beta": 0x03B2,
"gamma": 0x03B3,
"delta": 0x03B4,
"epsilon": 0x03B5,
"zeta": 0x03B6,
"eta": 0x03B7,
"theta": 0x03B8,
"iota": 0x03B9,
"kappa": 0x03BA,
"lambda": 0x03BB,
"mu": 0x03BC,
"nu": 0x03BD,
"xi": 0x03BE,
"omicron": 0x03BF,
"pi": 0x03C0,
"rho": 0x03C1,
"sigmaf": 0x03C2,
"sigma": 0x03C3,
"tau": 0x03C4,
"upsilon": 0x03C5,
"phi": 0x03C6,
"chi": 0x03C7,
"psi": 0x03C8,
"omega": 0x03C9,
"thetasym": 0x03D1,
"upsih": 0x03D2,
"piv": 0x03D6,
"ensp": 0x2002,
"emsp": 0x2003,
"thinsp": 0x2009,
"zwnj": 0x200C,
"zwj": 0x200D,
"lrm": 0x200E,
"rlm": 0x200F,
"ndash": 0x2013,
"mdash": 0x2014,
"lsquo": 0x2018,
"rsquo": 0x2019,
"sbquo": 0x201A,
"ldquo": 0x201C,
"rdquo": 0x201D,
"bdquo": 0x201E,
"dagger": 0x2020,
"Dagger": 0x2021,
"bull": 0x2022,
"hellip": 0x2026,
"permil": 0x2030,
"prime": 0x2032,
"Prime": 0x2033,
"lsaquo": 0x2039,
"rsaquo": 0x203A,
"oline": 0x203E,
"frasl": 0x2044,
"euro": 0x20AC,
"image": 0x2111,
"weierp": 0x2118,
"real": 0x211C,
"trade": 0x2122,
"alefsym": 0x2135,
"larr": 0x2190,
"uarr": 0x2191,
"rarr": 0x2192,
"darr": 0x2193,
"harr": 0x2194,
"crarr": 0x21B5,
"lArr": 0x21D0,
"uArr": 0x21D1,
"rArr": 0x21D2,
"dArr": 0x21D3,
"hArr": 0x21D4,
"forall": 0x2200,
"part": 0x2202,
"exist": 0x2203,
"empty": 0x2205,
"nabla": 0x2207,
"isin": 0x2208,
"notin": 0x2209,
"ni": 0x220B,
"prod": 0x220F,
"sum": 0x2211,
"minus": 0x2212,
"lowast": 0x2217,
"radic": 0x221A,
"prop": 0x221D,
"infin": 0x221E,
"ang": 0x2220,
"and": 0x2227,
"or": 0x2228,
"cap": 0x2229,
"cup": 0x222A,
"int": 0x222B,
"there4": 0x2234,
"sim": 0x223C,
"cong": 0x2245,
"asymp": 0x2248,
"ne": 0x2260,
"equiv": 0x2261,
"le": 0x2264,
"ge": 0x2265,
"sub": 0x2282,
"sup": 0x2283,
"nsub": 0x2284,
"sube": 0x2286,
"supe": 0x2287,
"oplus": 0x2295,
"otimes": 0x2297,
"perp": 0x22A5,
"sdot": 0x22C5,
"lceil": 0x2308,
"rceil": 0x2309,
"lfloor": 0x230A,
"rfloor": 0x230B,
"lang": 0x2329,
"rang": 0x232A,
"loz": 0x25CA,
"spades": 0x2660,
"clubs": 0x2663,
"hearts": 0x2665,
"diams": 0x2666
});
}
const entities = createMap<number>({
"quot": 0x0022,
"amp": 0x0026,
"apos": 0x0027,
"lt": 0x003C,
"gt": 0x003E,
"nbsp": 0x00A0,
"iexcl": 0x00A1,
"cent": 0x00A2,
"pound": 0x00A3,
"curren": 0x00A4,
"yen": 0x00A5,
"brvbar": 0x00A6,
"sect": 0x00A7,
"uml": 0x00A8,
"copy": 0x00A9,
"ordf": 0x00AA,
"laquo": 0x00AB,
"not": 0x00AC,
"shy": 0x00AD,
"reg": 0x00AE,
"macr": 0x00AF,
"deg": 0x00B0,
"plusmn": 0x00B1,
"sup2": 0x00B2,
"sup3": 0x00B3,
"acute": 0x00B4,
"micro": 0x00B5,
"para": 0x00B6,
"middot": 0x00B7,
"cedil": 0x00B8,
"sup1": 0x00B9,
"ordm": 0x00BA,
"raquo": 0x00BB,
"frac14": 0x00BC,
"frac12": 0x00BD,
"frac34": 0x00BE,
"iquest": 0x00BF,
"Agrave": 0x00C0,
"Aacute": 0x00C1,
"Acirc": 0x00C2,
"Atilde": 0x00C3,
"Auml": 0x00C4,
"Aring": 0x00C5,
"AElig": 0x00C6,
"Ccedil": 0x00C7,
"Egrave": 0x00C8,
"Eacute": 0x00C9,
"Ecirc": 0x00CA,
"Euml": 0x00CB,
"Igrave": 0x00CC,
"Iacute": 0x00CD,
"Icirc": 0x00CE,
"Iuml": 0x00CF,
"ETH": 0x00D0,
"Ntilde": 0x00D1,
"Ograve": 0x00D2,
"Oacute": 0x00D3,
"Ocirc": 0x00D4,
"Otilde": 0x00D5,
"Ouml": 0x00D6,
"times": 0x00D7,
"Oslash": 0x00D8,
"Ugrave": 0x00D9,
"Uacute": 0x00DA,
"Ucirc": 0x00DB,
"Uuml": 0x00DC,
"Yacute": 0x00DD,
"THORN": 0x00DE,
"szlig": 0x00DF,
"agrave": 0x00E0,
"aacute": 0x00E1,
"acirc": 0x00E2,
"atilde": 0x00E3,
"auml": 0x00E4,
"aring": 0x00E5,
"aelig": 0x00E6,
"ccedil": 0x00E7,
"egrave": 0x00E8,
"eacute": 0x00E9,
"ecirc": 0x00EA,
"euml": 0x00EB,
"igrave": 0x00EC,
"iacute": 0x00ED,
"icirc": 0x00EE,
"iuml": 0x00EF,
"eth": 0x00F0,
"ntilde": 0x00F1,
"ograve": 0x00F2,
"oacute": 0x00F3,
"ocirc": 0x00F4,
"otilde": 0x00F5,
"ouml": 0x00F6,
"divide": 0x00F7,
"oslash": 0x00F8,
"ugrave": 0x00F9,
"uacute": 0x00FA,
"ucirc": 0x00FB,
"uuml": 0x00FC,
"yacute": 0x00FD,
"thorn": 0x00FE,
"yuml": 0x00FF,
"OElig": 0x0152,
"oelig": 0x0153,
"Scaron": 0x0160,
"scaron": 0x0161,
"Yuml": 0x0178,
"fnof": 0x0192,
"circ": 0x02C6,
"tilde": 0x02DC,
"Alpha": 0x0391,
"Beta": 0x0392,
"Gamma": 0x0393,
"Delta": 0x0394,
"Epsilon": 0x0395,
"Zeta": 0x0396,
"Eta": 0x0397,
"Theta": 0x0398,
"Iota": 0x0399,
"Kappa": 0x039A,
"Lambda": 0x039B,
"Mu": 0x039C,
"Nu": 0x039D,
"Xi": 0x039E,
"Omicron": 0x039F,
"Pi": 0x03A0,
"Rho": 0x03A1,
"Sigma": 0x03A3,
"Tau": 0x03A4,
"Upsilon": 0x03A5,
"Phi": 0x03A6,
"Chi": 0x03A7,
"Psi": 0x03A8,
"Omega": 0x03A9,
"alpha": 0x03B1,
"beta": 0x03B2,
"gamma": 0x03B3,
"delta": 0x03B4,
"epsilon": 0x03B5,
"zeta": 0x03B6,
"eta": 0x03B7,
"theta": 0x03B8,
"iota": 0x03B9,
"kappa": 0x03BA,
"lambda": 0x03BB,
"mu": 0x03BC,
"nu": 0x03BD,
"xi": 0x03BE,
"omicron": 0x03BF,
"pi": 0x03C0,
"rho": 0x03C1,
"sigmaf": 0x03C2,
"sigma": 0x03C3,
"tau": 0x03C4,
"upsilon": 0x03C5,
"phi": 0x03C6,
"chi": 0x03C7,
"psi": 0x03C8,
"omega": 0x03C9,
"thetasym": 0x03D1,
"upsih": 0x03D2,
"piv": 0x03D6,
"ensp": 0x2002,
"emsp": 0x2003,
"thinsp": 0x2009,
"zwnj": 0x200C,
"zwj": 0x200D,
"lrm": 0x200E,
"rlm": 0x200F,
"ndash": 0x2013,
"mdash": 0x2014,
"lsquo": 0x2018,
"rsquo": 0x2019,
"sbquo": 0x201A,
"ldquo": 0x201C,
"rdquo": 0x201D,
"bdquo": 0x201E,
"dagger": 0x2020,
"Dagger": 0x2021,
"bull": 0x2022,
"hellip": 0x2026,
"permil": 0x2030,
"prime": 0x2032,
"Prime": 0x2033,
"lsaquo": 0x2039,
"rsaquo": 0x203A,
"oline": 0x203E,
"frasl": 0x2044,
"euro": 0x20AC,
"image": 0x2111,
"weierp": 0x2118,
"real": 0x211C,
"trade": 0x2122,
"alefsym": 0x2135,
"larr": 0x2190,
"uarr": 0x2191,
"rarr": 0x2192,
"darr": 0x2193,
"harr": 0x2194,
"crarr": 0x21B5,
"lArr": 0x21D0,
"uArr": 0x21D1,
"rArr": 0x21D2,
"dArr": 0x21D3,
"hArr": 0x21D4,
"forall": 0x2200,
"part": 0x2202,
"exist": 0x2203,
"empty": 0x2205,
"nabla": 0x2207,
"isin": 0x2208,
"notin": 0x2209,
"ni": 0x220B,
"prod": 0x220F,
"sum": 0x2211,
"minus": 0x2212,
"lowast": 0x2217,
"radic": 0x221A,
"prop": 0x221D,
"infin": 0x221E,
"ang": 0x2220,
"and": 0x2227,
"or": 0x2228,
"cap": 0x2229,
"cup": 0x222A,
"int": 0x222B,
"there4": 0x2234,
"sim": 0x223C,
"cong": 0x2245,
"asymp": 0x2248,
"ne": 0x2260,
"equiv": 0x2261,
"le": 0x2264,
"ge": 0x2265,
"sub": 0x2282,
"sup": 0x2283,
"nsub": 0x2284,
"sube": 0x2286,
"supe": 0x2287,
"oplus": 0x2295,
"otimes": 0x2297,
"perp": 0x22A5,
"sdot": 0x22C5,
"lceil": 0x2308,
"rceil": 0x2309,
"lfloor": 0x230A,
"rfloor": 0x230B,
"lang": 0x2329,
"rang": 0x232A,
"loz": 0x25CA,
"spades": 0x2660,
"clubs": 0x2663,
"hearts": 0x2665,
"diams": 0x2666
});
}
+79 -1
View File
@@ -5,6 +5,14 @@
namespace ts {
export function transformES2015Module(context: TransformationContext) {
const compilerOptions = context.getCompilerOptions();
const previousOnEmitNode = context.onEmitNode;
const previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
context.enableEmitNotification(SyntaxKind.SourceFile);
context.enableSubstitution(SyntaxKind.Identifier);
let currentSourceFile: SourceFile;
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
@@ -13,7 +21,27 @@ namespace ts {
}
if (isExternalModule(node) || compilerOptions.isolatedModules) {
return visitEachChild(node, visitor, context);
const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions);
if (externalHelpersModuleName) {
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, node.statements);
append(statements,
createImportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
createImportClause(/*name*/ undefined, createNamespaceImport(externalHelpersModuleName)),
createLiteral(externalHelpersModuleNameText)
)
);
addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset));
return updateSourceFileNode(
node,
createNodeArray(statements, node.statements));
}
else {
return visitEachChild(node, visitor, context);
}
}
return node;
@@ -35,5 +63,55 @@ namespace ts {
// Elide `export=` as it is not legal with --module ES6
return node.isExportEquals ? undefined : node;
}
//
// Emit Notification
//
/**
* Hook for node emit.
*
* @param emitContext A context hint for the emitter.
* @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 {
if (isSourceFile(node)) {
currentSourceFile = node;
previousOnEmitNode(emitContext, node, emitCallback);
currentSourceFile = undefined;
}
else {
previousOnEmitNode(emitContext, node, emitCallback);
}
}
//
// Substitutions
//
/**
* Hooks node substitutions.
*
* @param emitContext A context hint for the emitter.
* @param node The node to substitute.
*/
function onSubstituteNode(emitContext: EmitContext, node: Node) {
node = previousOnSubstituteNode(emitContext, node);
if (isIdentifier(node) && emitContext === EmitContext.Expression) {
return substituteExpressionIdentifier(node);
}
return node;
}
function substituteExpressionIdentifier(node: Identifier): Expression {
if (getEmitFlags(node) & EmitFlags.HelperName) {
const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile);
if (externalHelpersModuleName) {
return createPropertyAccess(externalHelpersModuleName, node);
}
}
return node;
}
}
}
+41 -9
View File
@@ -19,8 +19,7 @@ namespace ts {
const {
startLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration,
endLexicalEnvironment
} = context;
const compilerOptions = context.getCompilerOptions();
@@ -61,7 +60,7 @@ namespace ts {
}
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[getOriginalNodeId(node)] = collectExternalModuleInfo(node, resolver);
currentModuleInfo = moduleInfoMap[getOriginalNodeId(node)] = collectExternalModuleInfo(node, resolver, compilerOptions);
// Perform the transformation.
const transformModule = transformModuleDelegates[moduleKind] || transformModuleDelegates[ModuleKind.None];
@@ -82,13 +81,14 @@ namespace ts {
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement, /*optional*/ true));
addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset));
addRange(statements, endLexicalEnvironment());
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
const updated = updateSourceFileNode(node, createNodeArray(statements, node.statements));
if (currentModuleInfo.hasExportStarsToExportValues) {
setEmitFlags(updated, EmitFlags.EmitExportStar | getEmitFlags(node));
addEmitHelper(updated, exportStarHelper);
}
return updated;
@@ -111,8 +111,7 @@ namespace ts {
* @param node The SourceFile node.
*/
function transformUMDModule(node: SourceFile) {
const define = createIdentifier("define");
setEmitFlags(define, EmitFlags.UMDDefine);
const define = createRawExpression(umdHelper);
return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false);
}
@@ -257,6 +256,7 @@ namespace ts {
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
// Visit each statement of the module body.
append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement, /*optional*/ true));
addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset));
// End the lexical environment for the module body
@@ -270,7 +270,7 @@ namespace ts {
if (currentModuleInfo.hasExportStarsToExportValues) {
// If we have any `export * from ...` declarations
// we need to inform the emitter to add the __export helper.
setEmitFlags(body, EmitFlags.EmitExportStar);
addEmitHelper(body, exportStarHelper);
}
return body;
@@ -757,9 +757,12 @@ namespace ts {
*/
function transformInitializedVariable(node: VariableDeclaration): Expression {
if (isBindingPattern(node.name)) {
return flattenVariableDestructuringToExpression(
return flattenDestructuringAssignment(
node,
hoistVariableDeclaration,
/*visitor*/ undefined,
context,
FlattenLevel.All,
/*needsValue*/ false,
createExportExpression
);
}
@@ -1186,6 +1189,14 @@ namespace ts {
* @param node The node to substitute.
*/
function substituteExpressionIdentifier(node: Identifier): Expression {
if (getEmitFlags(node) & EmitFlags.HelperName) {
const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile);
if (externalHelpersModuleName) {
return createPropertyAccess(externalHelpersModuleName, node);
}
return node;
}
if (!isGeneratedIdentifier(node) && !isLocalName(node)) {
const exportContainer = resolver.getReferencedExportContainer(node, isExportName(node));
if (exportContainer && exportContainer.kind === SyntaxKind.SourceFile) {
@@ -1312,4 +1323,25 @@ namespace ts {
}
}
}
// emit output for the __export helper function
const exportStarHelper: EmitHelper = {
name: "typescript:export-star",
scoped: true,
text: `
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}`
};
// emit output for the UMD helper function.
const umdHelper = `
(function (dependencies, factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(dependencies, factory);
}
})`;
}
+41 -10
View File
@@ -73,7 +73,7 @@ namespace ts {
// see comment to 'substitutePostfixUnaryExpression' for more details
// Collect information about the external module and dependency groups.
moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(node, resolver);
moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(node, resolver, compilerOptions);
// Make sure that the name of the 'exports' function does not conflict with
// existing identifiers.
@@ -82,6 +82,7 @@ namespace ts {
// Add the body of the module.
const dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
const moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
const moduleBodyFunction = createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
@@ -92,7 +93,7 @@ namespace ts {
createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
],
/*type*/ undefined,
createSystemModuleBody(node, dependencyGroups)
moduleBodyBlock
);
// Write the call to `System.register`
@@ -115,7 +116,9 @@ namespace ts {
], node.statements)
);
setEmitFlags(updated, getEmitFlags(node) & ~EmitFlags.EmitEmitHelpers);
if (!(compilerOptions.outFile || compilerOptions.out)) {
moveEmitHelpers(updated, moduleBodyBlock, helper => !helper.scoped);
}
if (noSubstitution) {
noSubstitutionMap[id] = noSubstitution;
@@ -236,6 +239,9 @@ namespace ts {
)
);
// Visit the synthetic external helpers import declaration if present
visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement, /*optional*/ true);
// Visit the statements of the source file, emitting any transformations into
// the `executeStatements` array. We do this *before* we fill the `setters` array
// as we both emit transformations as well as aggregate some data used when creating
@@ -280,9 +286,7 @@ namespace ts {
)
);
const body = createBlock(statements, /*location*/ undefined, /*multiLine*/ true);
setEmitFlags(body, EmitFlags.EmitEmitHelpers);
return body;
return createBlock(statements, /*location*/ undefined, /*multiLine*/ true);
}
/**
@@ -394,7 +398,13 @@ namespace ts {
if (localNames) {
condition = createLogicalAnd(
condition,
createLogicalNot(createHasOwnProperty(localNames, n))
createLogicalNot(
createCall(
createPropertyAccess(localNames, "hasOwnProperty"),
/*typeArguments*/ undefined,
[n]
)
)
);
}
@@ -808,7 +818,14 @@ namespace ts {
function transformInitializedVariable(node: VariableDeclaration, isExportedDeclaration: boolean): Expression {
const createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
return isBindingPattern(node.name)
? flattenVariableDestructuringToExpression(node, hoistVariableDeclaration, createAssignment, destructuringVisitor)
? flattenDestructuringAssignment(
node,
destructuringVisitor,
context,
FlattenLevel.All,
/*needsValue*/ false,
createAssignment
)
: createAssignment(node.name, visitNode(node.initializer, destructuringVisitor, isExpression));
}
@@ -1459,7 +1476,13 @@ namespace ts {
*/
function visitDestructuringAssignment(node: DestructuringAssignment): VisitResult<Expression> {
if (hasExportedReferenceInDestructuringTarget(node.left)) {
return flattenDestructuringAssignment(context, node, /*needsValue*/ true, hoistVariableDeclaration, destructuringVisitor);
return flattenDestructuringAssignment(
node,
destructuringVisitor,
context,
FlattenLevel.All,
/*needsValue*/ true
);
}
return visitEachChild(node, destructuringVisitor, context);
@@ -1474,7 +1497,7 @@ namespace ts {
if (isAssignmentExpression(node)) {
return hasExportedReferenceInDestructuringTarget(node.left);
}
else if (isSpreadElementExpression(node)) {
else if (isSpreadExpression(node)) {
return hasExportedReferenceInDestructuringTarget(node.expression);
}
else if (isObjectLiteralExpression(node)) {
@@ -1599,6 +1622,14 @@ namespace ts {
* @param node The node to substitute.
*/
function substituteExpressionIdentifier(node: Identifier): Expression {
if (getEmitFlags(node) & EmitFlags.HelperName) {
const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile);
if (externalHelpersModuleName) {
return createPropertyAccess(externalHelpersModuleName, node);
}
return node;
}
// When we see an identifier in an expression position that
// points to an imported symbol, we should substitute a qualified
// reference to the imported symbol if one is needed.
+192 -227
View File
@@ -21,6 +21,7 @@ namespace ts {
export function transformTypeScript(context: TransformationContext) {
const {
startLexicalEnvironment,
resumeLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration,
} = context;
@@ -48,7 +49,6 @@ namespace ts {
let currentNamespaceContainerName: Identifier;
let currentScope: SourceFile | Block | ModuleBlock | CaseBlock;
let currentScopeFirstDeclarationsOfName: Map<Node>;
let currentExternalHelpersModuleName: Identifier;
/**
* Keeps track of whether expression substitution has been enabled for specific edge cases.
@@ -80,7 +80,13 @@ namespace ts {
return node;
}
return visitNode(node, visitor, isSourceFile);
currentSourceFile = node;
const visited = saveStateAndInvoke(node, visitSourceFile);
addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
return visited;
}
/**
@@ -107,6 +113,32 @@ namespace ts {
return visited;
}
/**
* Performs actions that should always occur immediately before visiting a node.
*
* @param node The node to visit.
*/
function onBeforeVisitNode(node: Node) {
switch (node.kind) {
case SyntaxKind.SourceFile:
case SyntaxKind.CaseBlock:
case SyntaxKind.ModuleBlock:
case SyntaxKind.Block:
currentScope = <SourceFile | CaseBlock | ModuleBlock | Block>node;
currentScopeFirstDeclarationsOfName = undefined;
break;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.FunctionDeclaration:
if (hasModifier(node, ModifierFlags.Ambient)) {
break;
}
recordEmittedDeclarationInScope(node);
break;
}
}
/**
* General-purpose node visitor.
*
@@ -122,10 +154,7 @@ namespace ts {
* @param node The node to visit.
*/
function visitorWorker(node: Node): VisitResult<Node> {
if (node.kind === SyntaxKind.SourceFile) {
return visitSourceFile(<SourceFile>node);
}
else if (node.transformFlags & TransformFlags.TypeScript) {
if (node.transformFlags & TransformFlags.TypeScript) {
// This node is explicitly marked as TypeScript, so we should transform the node.
return visitTypeScript(node);
}
@@ -252,7 +281,6 @@ namespace ts {
return node;
}
/**
* Branching visitor, visits a TypeScript syntax node.
*
@@ -302,6 +330,7 @@ namespace ts {
case SyntaxKind.ThisType:
case SyntaxKind.TypeOperator:
case SyntaxKind.IndexedAccessType:
case SyntaxKind.MappedType:
case SyntaxKind.LiteralType:
// TypeScript type nodes are elided.
@@ -316,6 +345,7 @@ namespace ts {
case SyntaxKind.PropertyDeclaration:
// TypeScript property declarations are elided.
return undefined;
case SyntaxKind.Constructor:
return visitConstructor(<ConstructorDeclaration>node);
@@ -441,74 +471,11 @@ namespace ts {
}
}
/**
* Performs actions that should always occur immediately before visiting a node.
*
* @param node The node to visit.
*/
function onBeforeVisitNode(node: Node) {
switch (node.kind) {
case SyntaxKind.SourceFile:
case SyntaxKind.CaseBlock:
case SyntaxKind.ModuleBlock:
case SyntaxKind.Block:
currentScope = <SourceFile | CaseBlock | ModuleBlock | Block>node;
currentScopeFirstDeclarationsOfName = undefined;
break;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.FunctionDeclaration:
if (hasModifier(node, ModifierFlags.Ambient)) {
break;
}
recordEmittedDeclarationInScope(node);
break;
}
}
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.
if (node.flags & NodeFlags.EmitHelperFlags
&& compilerOptions.importHelpers
&& (isExternalModule(node) || compilerOptions.isolatedModules)) {
startLexicalEnvironment();
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor);
const externalHelpersModuleName = createUniqueName(externalHelpersModuleNameText);
const externalHelpersModuleImport = createImportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
createImportClause(/*name*/ undefined, createNamespaceImport(externalHelpersModuleName)),
createLiteral(externalHelpersModuleNameText));
externalHelpersModuleImport.parent = node;
externalHelpersModuleImport.flags &= ~NodeFlags.Synthesized;
statements.push(externalHelpersModuleImport);
currentExternalHelpersModuleName = externalHelpersModuleName;
addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset));
addRange(statements, endLexicalEnvironment());
currentExternalHelpersModuleName = undefined;
node = updateSourceFileNode(node, createNodeArray(statements, node.statements));
node.externalHelpersModuleName = externalHelpersModuleName;
}
else {
node = visitEachChild(node, sourceElementVisitor, context);
}
setEmitFlags(node, EmitFlags.EmitEmitHelpers | getEmitFlags(node));
return node;
const alwaysStrict = compilerOptions.alwaysStrict && !(isExternalModule(node) && moduleKind === ModuleKind.ES2015);
return updateSourceFileNode(
node,
visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
}
/**
@@ -880,9 +847,8 @@ namespace ts {
// downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array.
// Instead, we'll avoid using a rest parameter and spread into the super call as
// 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody".
return constructor
? visitNodes(constructor.parameters, visitor, isParameter)
: <ParameterDeclaration[]>[];
return visitParameterList(constructor && constructor.parameters, visitor, context)
|| <ParameterDeclaration[]>[];
}
/**
@@ -897,8 +863,7 @@ namespace ts {
const statements: Statement[] = [];
let indexOfFirstStatement = 0;
// The body of a constructor is a new lexical environment
startLexicalEnvironment();
resumeLexicalEnvironment();
if (constructor) {
indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements);
@@ -954,15 +919,13 @@ namespace ts {
// End the lexical environment.
addRange(statements, endLexicalEnvironment());
return setMultiLine(
createBlock(
createNodeArray(
statements,
/*location*/ constructor ? constructor.body.statements : node.members
),
/*location*/ constructor ? constructor.body : /*location*/ undefined
return createBlock(
createNodeArray(
statements,
/*location*/ constructor ? constructor.body.statements : node.members
),
true
/*location*/ constructor ? constructor.body : /*location*/ undefined,
/*multiLine*/ true
);
}
@@ -1391,13 +1354,13 @@ namespace ts {
// __metadata("design:type", Function),
// __metadata("design:paramtypes", [Object]),
// __metadata("design:returntype", void 0)
// ], C.prototype, "method", undefined);
// ], C.prototype, "method", null);
//
// The emit for an accessor is:
//
// __decorate([
// dec
// ], C.prototype, "accessor", undefined);
// ], C.prototype, "accessor", null);
//
// The emit for a property is:
//
@@ -1420,7 +1383,7 @@ namespace ts {
: undefined;
const helper = createDecorateHelper(
currentExternalHelpersModuleName,
context,
decoratorExpressions,
prefix,
memberName,
@@ -1458,7 +1421,7 @@ namespace ts {
const classAlias = classAliases && classAliases[getOriginalNodeId(node)];
const localName = getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
const decorate = createDecorateHelper(currentExternalHelpersModuleName, decoratorExpressions, localName);
const decorate = createDecorateHelper(context, decoratorExpressions, localName);
const expression = createAssignment(localName, classAlias ? createAssignment(classAlias, decorate) : decorate);
setEmitFlags(expression, EmitFlags.NoComments);
setSourceMapRange(expression, moveRangePastDecorators(node));
@@ -1486,7 +1449,7 @@ namespace ts {
expressions = [];
for (const decorator of decorators) {
const helper = createParamHelper(
currentExternalHelpersModuleName,
context,
transformDecorator(decorator),
parameterOffset,
/*location*/ decorator.expression);
@@ -1516,13 +1479,13 @@ namespace ts {
function addOldTypeMetadata(node: Declaration, decoratorExpressions: Expression[]) {
if (compilerOptions.emitDecoratorMetadata) {
if (shouldAddTypeMetadata(node)) {
decoratorExpressions.push(createMetadataHelper(currentExternalHelpersModuleName, "design:type", serializeTypeOfNode(node)));
decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node)));
}
if (shouldAddParamTypesMetadata(node)) {
decoratorExpressions.push(createMetadataHelper(currentExternalHelpersModuleName, "design:paramtypes", serializeParameterTypesOfNode(node)));
decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node)));
}
if (shouldAddReturnTypeMetadata(node)) {
decoratorExpressions.push(createMetadataHelper(currentExternalHelpersModuleName, "design:returntype", serializeReturnTypeOfNode(node)));
decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node)));
}
}
}
@@ -1540,7 +1503,7 @@ namespace ts {
(properties || (properties = [])).push(createPropertyAssignment("returnType", createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, createToken(SyntaxKind.EqualsGreaterThanToken), serializeReturnTypeOfNode(node))));
}
if (properties) {
decoratorExpressions.push(createMetadataHelper(currentExternalHelpersModuleName, "design:typeinfo", createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true)));
decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true)));
}
}
}
@@ -1787,6 +1750,7 @@ namespace ts {
case SyntaxKind.TypeQuery:
case SyntaxKind.TypeOperator:
case SyntaxKind.IndexedAccessType:
case SyntaxKind.MappedType:
case SyntaxKind.TypeLiteral:
case SyntaxKind.AnyKeyword:
case SyntaxKind.ThisType:
@@ -1813,12 +1777,7 @@ namespace ts {
const temp = createTempVariable(hoistVariableDeclaration);
return createLogicalOr(
createLogicalAnd(
createStrictEquality(
createTypeOf(
createAssignment(temp, serialized)
),
createLiteral("function")
),
createTypeCheck(createAssignment(temp, serialized), "function"),
temp
),
createIdentifier("Object")
@@ -1927,13 +1886,8 @@ namespace ts {
*/
function getGlobalSymbolNameWithFallback(): Expression {
return createConditional(
createStrictEquality(
createTypeOf(createIdentifier("Symbol")),
createLiteral("function")
),
createToken(SyntaxKind.QuestionToken),
createTypeCheck(createIdentifier("Symbol"), "function"),
createIdentifier("Symbol"),
createToken(SyntaxKind.ColonToken),
createIdentifier("Object")
);
}
@@ -1952,7 +1906,7 @@ namespace ts {
: (<ComputedPropertyName>name).expression;
}
else if (isIdentifier(name)) {
return createLiteral(name.text);
return createLiteral(unescapeIdentifier(name.text));
}
else {
return getSynthesizedClone(name);
@@ -2057,26 +2011,23 @@ namespace ts {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return undefined;
}
const method = createMethod(
const updated = updateMethod(
node,
/*decorators*/ undefined,
visitNodes(node.modifiers, modifierVisitor, isModifier),
node.asteriskToken,
visitPropertyNameOfClassElement(node),
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ node
visitFunctionBody(node.body, visitor, context)
);
// 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;
if (updated !== 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(updated, node);
setSourceMapRange(updated, moveRangePastDecorators(node));
}
return updated;
}
/**
@@ -2102,24 +2053,22 @@ namespace ts {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
}
const accessor = createGetAccessor(
const updated = updateGetAccessor(
node,
/*decorators*/ undefined,
visitNodes(node.modifiers, modifierVisitor, isModifier),
visitPropertyNameOfClassElement(node),
visitNodes(node.parameters, visitor, isParameter),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
node.body ? visitEachChild(node.body, visitor, context) : createBlock([]),
/*location*/ node
visitFunctionBody(node.body, visitor, context) || createBlock([])
);
// While we emit the source map for the node after skipping decorators and modifiers,
// we need to emit the comments for the original range.
setOriginalNode(accessor, node);
setCommentRange(accessor, node);
setSourceMapRange(accessor, moveRangePastDecorators(node));
return accessor;
if (updated !== 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(updated, node);
setSourceMapRange(updated, moveRangePastDecorators(node));
}
return updated;
}
/**
@@ -2135,23 +2084,21 @@ namespace ts {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
}
const accessor = createSetAccessor(
const updated = updateSetAccessor(
node,
/*decorators*/ undefined,
visitNodes(node.modifiers, modifierVisitor, isModifier),
visitPropertyNameOfClassElement(node),
visitNodes(node.parameters, visitor, isParameter),
node.body ? visitEachChild(node.body, visitor, context) : createBlock([]),
/*location*/ node
visitParameterList(node.parameters, visitor, context),
visitFunctionBody(node.body, visitor, context) || createBlock([])
);
// While we emit the source map for the node after skipping decorators and modifiers,
// we need to emit the comments for the original range.
setOriginalNode(accessor, node);
setCommentRange(accessor, node);
setSourceMapRange(accessor, moveRangePastDecorators(node));
return accessor;
if (updated !== 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(updated, node);
setSourceMapRange(updated, moveRangePastDecorators(node));
}
return updated;
}
/**
@@ -2168,27 +2115,22 @@ namespace ts {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return createNotEmittedStatement(node);
}
const func = createFunctionDeclaration(
const updated = updateFunctionDeclaration(
node,
/*decorators*/ undefined,
visitNodes(node.modifiers, modifierVisitor, isModifier),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ node
visitFunctionBody(node.body, visitor, context) || createBlock([])
);
setOriginalNode(func, node);
if (isNamespaceExport(node)) {
const statements: Statement[] = [func];
const statements: Statement[] = [updated];
addExportMemberAssignment(statements, node);
return statements;
}
return func;
return updated;
}
/**
@@ -2203,21 +2145,16 @@ namespace ts {
if (nodeIsMissing(node.body)) {
return createOmittedExpression();
}
const func = createFunctionExpression(
const updated = updateFunctionExpression(
node,
visitNodes(node.modifiers, modifierVisitor, isModifier),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ node
visitFunctionBody(node.body, visitor, context)
);
setOriginalNode(func, node);
return func;
return updated;
}
/**
@@ -2226,62 +2163,15 @@ namespace ts {
* - The node has type annotations
*/
function visitArrowFunction(node: ArrowFunction) {
const func = createArrowFunction(
const updated = updateArrowFunction(
node,
visitNodes(node.modifiers, modifierVisitor, isModifier),
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
node.equalsGreaterThanToken,
transformConciseBody(node),
/*location*/ node
visitFunctionBody(node.body, visitor, context)
);
setOriginalNode(func, node);
return func;
}
function transformFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody {
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 {
return transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ false);
}
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;
}
}
return updated;
}
/**
@@ -2349,11 +2239,13 @@ namespace ts {
function transformInitializedVariable(node: VariableDeclaration): Expression {
const name = node.name;
if (isBindingPattern(name)) {
return flattenVariableDestructuringToExpression(
return flattenDestructuringAssignment(
node,
hoistVariableDeclaration,
createNamespaceExportExpression,
visitor
visitor,
context,
FlattenLevel.All,
/*needsValue*/ false,
createNamespaceExportExpression
);
}
else {
@@ -3353,7 +3245,7 @@ namespace ts {
function trySubstituteNamespaceExportedName(node: Identifier): Expression {
// If this is explicitly a local name, do not substitute.
if (enabledSubstitutions & applicableSubstitutions && !isLocalName(node)) {
if (enabledSubstitutions & applicableSubstitutions && !isGeneratedIdentifier(node) && !isLocalName(node)) {
// If we are nested within a namespace declaration, we may need to qualifiy
// an identifier that is exported from a merged namespace.
const container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
@@ -3408,4 +3300,77 @@ namespace ts {
: undefined;
}
}
const paramHelper: EmitHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
text: `
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};`
};
function createParamHelper(context: TransformationContext, expression: Expression, parameterOffset: number, location?: TextRange) {
context.requestEmitHelper(paramHelper);
return createCall(
getHelperName("__param"),
/*typeArguments*/ undefined,
[
createLiteral(parameterOffset),
expression
],
location
);
}
const metadataHelper: EmitHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: `
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};`
};
function createMetadataHelper(context: TransformationContext, metadataKey: string, metadataValue: Expression) {
context.requestEmitHelper(metadataHelper);
return createCall(
getHelperName("__metadata"),
/*typeArguments*/ undefined,
[
createLiteral(metadataKey),
metadataValue
]
);
}
const decorateHelper: EmitHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: `
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};`
};
function createDecorateHelper(context: TransformationContext, decoratorExpressions: Expression[], target: Expression, memberName?: Expression, descriptor?: Expression, location?: TextRange) {
context.requestEmitHelper(decorateHelper);
const argumentsArray: Expression[] = [];
argumentsArray.push(createArrayLiteral(decoratorExpressions, /*location*/ undefined, /*multiLine*/ true));
argumentsArray.push(target);
if (memberName) {
argumentsArray.push(memberName);
if (descriptor) {
argumentsArray.push(descriptor);
}
}
return createCall(getHelperName("__decorate"), /*typeArguments*/ undefined, argumentsArray, location);
}
}
+1 -61
View File
@@ -43,66 +43,6 @@ namespace ts {
}
}
/**
* Checks to see if the locale is in the appropriate format,
* and if it is, attempts to set the appropriate language.
*/
function validateLocaleAndSetLanguage(locale: string, errors: Diagnostic[]): boolean {
const matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
if (!matchResult) {
errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
return false;
}
const language = matchResult[1];
const territory = matchResult[3];
// First try the entire locale, then fall back to just language if that's all we have.
// Either ways do not fail, and fallback to the English diagnostic strings.
if (!trySetLanguageAndTerritory(language, territory, errors)) {
trySetLanguageAndTerritory(language, undefined, errors);
}
return true;
}
function trySetLanguageAndTerritory(language: string, territory: string, errors: Diagnostic[]): boolean {
const compilerFilePath = normalizePath(sys.getExecutingFilePath());
const containingDirectoryPath = getDirectoryPath(compilerFilePath);
let filePath = combinePaths(containingDirectoryPath, language);
if (territory) {
filePath = filePath + "-" + territory;
}
filePath = sys.resolvePath(combinePaths(filePath, "diagnosticMessages.generated.json"));
if (!sys.fileExists(filePath)) {
return false;
}
// TODO: Add codePage support for readFile?
let fileContents = "";
try {
fileContents = sys.readFile(filePath);
}
catch (e) {
errors.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath));
return false;
}
try {
ts.localizedDiagnosticMessages = JSON.parse(fileContents);
}
catch (e) {
errors.push(createCompilerDiagnostic(Diagnostics.Corrupted_locale_file_0, filePath));
return false;
}
return true;
}
function countLines(program: Program): number {
let count = 0;
forEach(program.getSourceFiles(), file => {
@@ -263,7 +203,7 @@ namespace ts {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--locale"), /* host */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
validateLocaleAndSetLanguage(commandLine.options.locale, commandLine.errors);
validateLocaleAndSetLanguage(commandLine.options.locale, sys, commandLine.errors);
}
// If there are any errors due to command line parsing and/or
+3 -1
View File
@@ -11,7 +11,8 @@
"stripInternal": true,
"target": "es5",
"noUnusedLocals": true,
"noUnusedParameters": true
"noUnusedParameters": true,
"types": [ ]
},
"files": [
"core.ts",
@@ -27,6 +28,7 @@
"visitor.ts",
"transformers/ts.ts",
"transformers/jsx.ts",
"transformers/esnext.ts",
"transformers/es2017.ts",
"transformers/es2016.ts",
"transformers/es2015.ts",
+386 -137
View File
@@ -219,6 +219,7 @@ namespace ts {
ThisType,
TypeOperator,
IndexedAccessType,
MappedType,
LiteralType,
// Binding patterns
ObjectBindingPattern,
@@ -246,7 +247,7 @@ namespace ts {
ConditionalExpression,
TemplateExpression,
YieldExpression,
SpreadElementExpression,
SpreadElement,
ClassExpression,
OmittedExpression,
ExpressionWithTypeArguments,
@@ -320,6 +321,7 @@ namespace ts {
// Property assignments
PropertyAssignment,
ShorthandPropertyAssignment,
SpreadAssignment,
// Enum
EnumMember,
@@ -347,6 +349,7 @@ namespace ts {
JSDocThisType,
JSDocComment,
JSDocTag,
JSDocAugmentsTag,
JSDocParameterTag,
JSDocReturnTag,
JSDocTypeTag,
@@ -367,6 +370,7 @@ namespace ts {
PartiallyEmittedExpression,
MergeDeclarationMarker,
EndOfDeclarationMarker,
RawExpression,
// Enum value count
Count,
@@ -414,25 +418,20 @@ namespace ts {
HasImplicitReturn = 1 << 7, // If function implicitly returns on one of codepaths (initialized by binding)
HasExplicitReturn = 1 << 8, // If function has explicit reachable return on one of codepaths (initialized by binding)
GlobalAugmentation = 1 << 9, // Set if module declaration is an augmentation for the global scope
HasClassExtends = 1 << 10, // If the file has a non-ambient class with an extends clause in ES5 or lower (initialized by binding)
HasDecorators = 1 << 11, // If the file has decorators (initialized by binding)
HasParamDecorators = 1 << 12, // If the file has parameter decorators (initialized by binding)
HasAsyncFunctions = 1 << 13, // If the file has async functions (initialized by binding)
HasJsxSpreadAttributes = 1 << 14, // If the file as JSX spread attributes (initialized by binding)
DisallowInContext = 1 << 15, // If node was parsed in a context where 'in-expressions' are not allowed
YieldContext = 1 << 16, // If node was parsed in the 'yield' context created when parsing a generator
DecoratorContext = 1 << 17, // If node was parsed as part of a decorator
AwaitContext = 1 << 18, // If node was parsed in the 'await' context created when parsing an async function
ThisNodeHasError = 1 << 19, // If the parser encountered an error when parsing the code that created this node
JavaScriptFile = 1 << 20, // If node was parsed in a JavaScript
ThisNodeOrAnySubNodesHasError = 1 << 21, // If this node or any of its children had an error
HasAggregatedChildData = 1 << 22, // If we've computed data from children and cached it in this node
HasAsyncFunctions = 1 << 10, // If the file has async functions (initialized by binding)
DisallowInContext = 1 << 11, // If node was parsed in a context where 'in-expressions' are not allowed
YieldContext = 1 << 12, // If node was parsed in the 'yield' context created when parsing a generator
DecoratorContext = 1 << 13, // If node was parsed as part of a decorator
AwaitContext = 1 << 14, // If node was parsed in the 'await' context created when parsing an async function
ThisNodeHasError = 1 << 15, // If the parser encountered an error when parsing the code that created this node
JavaScriptFile = 1 << 16, // If node was parsed in a JavaScript
ThisNodeOrAnySubNodesHasError = 1 << 17, // If this node or any of its children had an error
HasAggregatedChildData = 1 << 18, // If we've computed data from children and cached it in this node
BlockScoped = Let | Const,
ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn,
EmitHelperFlags = HasClassExtends | HasDecorators | HasParamDecorators | HasAsyncFunctions | HasJsxSpreadAttributes,
ReachabilityAndEmitFlags = ReachabilityCheckFlags | EmitHelperFlags,
ReachabilityAndEmitFlags = ReachabilityCheckFlags | HasAsyncFunctions,
// Parsing context flags
ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile,
@@ -454,7 +453,6 @@ namespace ts {
Async = 1 << 8, // Property/Method/Function
Default = 1 << 9, // Function/Class (export default declaration)
Const = 1 << 11, // Variable declaration
HasComputedFlags = 1 << 29, // Modifier flags have been computed
AccessibilityModifier = Public | Private | Protected,
@@ -494,7 +492,8 @@ namespace ts {
parent?: Node; // Parent node (initialized by binding)
/* @internal */ original?: Node; // The original node if this is an updated node.
/* @internal */ startsOnNewLine?: boolean; // Whether a synthesized node should start on a new line (used by transforms).
/* @internal */ jsDocComments?: JSDoc[]; // JSDoc for the node, if it has any.
/* @internal */ jsDoc?: JSDoc[]; // JSDoc that directly precedes this node
/* @internal */ jsDocCache?: (JSDoc | JSDocTag)[]; // All JSDoc that applies to the node, including parent docs and @param tags
/* @internal */ symbol?: Symbol; // Symbol declared by node (initialized by binding)
/* @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding)
/* @internal */ nextContainer?: Node; // Next container in declaration order (initialized by binding)
@@ -505,6 +504,7 @@ namespace ts {
export interface NodeArray<T extends Node> extends Array<T>, TextRange {
hasTrailingComma?: boolean;
/* @internal */ transformFlags?: TransformFlags;
}
export interface Token<TKind extends SyntaxKind> extends Node {
@@ -519,6 +519,7 @@ namespace ts {
export type EqualsGreaterThanToken = Token<SyntaxKind.EqualsGreaterThanToken>;
export type EndOfFileToken = Token<SyntaxKind.EndOfFileToken>;
export type AtToken = Token<SyntaxKind.AtToken>;
export type ReadonlyToken = Token<SyntaxKind.ReadonlyKeyword>;
export type Modifier
= Token<SyntaxKind.AbstractKeyword>
@@ -575,9 +576,9 @@ namespace ts {
export type EntityName = Identifier | QualifiedName;
export type PropertyName = Identifier | LiteralExpression | ComputedPropertyName;
export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName;
export type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern;
export type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern;
export interface Declaration extends Node {
_declarationBrand: any;
@@ -585,7 +586,7 @@ namespace ts {
}
export interface DeclarationStatement extends Declaration, Statement {
name?: Identifier | LiteralExpression;
name?: Identifier | StringLiteral | NumericLiteral;
}
export interface ComputedPropertyName extends Node {
@@ -649,7 +650,7 @@ namespace ts {
export interface BindingElement extends Declaration {
kind: SyntaxKind.BindingElement;
propertyName?: PropertyName; // Binding property name (in object binding pattern)
dotDotDotToken?: DotDotDotToken; // Present on rest binding element
dotDotDotToken?: DotDotDotToken; // Present on rest element (in object binding pattern)
name: BindingName; // Declared binding element name
initializer?: Expression; // Optional initializer
}
@@ -675,7 +676,7 @@ namespace ts {
name?: PropertyName;
}
export type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration;
export type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration | SpreadAssignment;
export interface PropertyAssignment extends ObjectLiteralElement {
kind: SyntaxKind.PropertyAssignment;
@@ -694,6 +695,11 @@ namespace ts {
objectAssignmentInitializer?: Expression;
}
export interface SpreadAssignment extends ObjectLiteralElement {
kind: SyntaxKind.SpreadAssignment;
expression: Expression;
}
// SyntaxKind.VariableDeclaration
// SyntaxKind.Parameter
// SyntaxKind.BindingElement
@@ -715,22 +721,20 @@ namespace ts {
name: PropertyName;
}
export interface BindingPattern extends Node {
elements: NodeArray<BindingElement | ArrayBindingElement>;
}
export interface ObjectBindingPattern extends BindingPattern {
export interface ObjectBindingPattern extends Node {
kind: SyntaxKind.ObjectBindingPattern;
elements: NodeArray<BindingElement>;
}
export type ArrayBindingElement = BindingElement | OmittedExpression;
export interface ArrayBindingPattern extends BindingPattern {
export interface ArrayBindingPattern extends Node {
kind: SyntaxKind.ArrayBindingPattern;
elements: NodeArray<ArrayBindingElement>;
}
export type BindingPattern = ObjectBindingPattern | ArrayBindingPattern;
export type ArrayBindingElement = BindingElement | OmittedExpression;
/**
* Several node kinds share function-like features such as a signature,
* a name, and a body. These nodes should extend FunctionLikeDeclaration.
@@ -897,6 +901,14 @@ namespace ts {
indexType: TypeNode;
}
export interface MappedTypeNode extends TypeNode, Declaration {
kind: SyntaxKind.MappedType;
readonlyToken?: ReadonlyToken;
typeParameter: TypeParameterDeclaration;
questionToken?: QuestionToken;
type?: TypeNode;
}
export interface LiteralTypeNode extends TypeNode {
kind: SyntaxKind.LiteralType;
literal: Expression;
@@ -904,7 +916,7 @@ namespace ts {
export interface StringLiteral extends LiteralExpression {
kind: SyntaxKind.StringLiteral;
/* @internal */ textSourceNode?: Identifier | StringLiteral; // Allows a StringLiteral to get its text from another node (used by transforms).
/* @internal */ textSourceNode?: Identifier | StringLiteral | NumericLiteral; // Allows a StringLiteral to get its text from another node (used by transforms).
}
// Note: 'brands' in our syntax nodes serve to give us a small amount of nominal typing.
@@ -1169,20 +1181,64 @@ namespace ts {
right: Expression;
}
export interface AssignmentExpression extends BinaryExpression {
export type AssignmentOperatorToken = Token<AssignmentOperator>;
export interface AssignmentExpression<TOperator extends AssignmentOperatorToken> extends BinaryExpression {
left: LeftHandSideExpression;
operatorToken: Token<SyntaxKind.EqualsToken>;
operatorToken: TOperator;
}
export interface ObjectDestructuringAssignment extends AssignmentExpression {
export interface ObjectDestructuringAssignment extends AssignmentExpression<EqualsToken> {
left: ObjectLiteralExpression;
}
export interface ArrayDestructuringAssignment extends AssignmentExpression {
export interface ArrayDestructuringAssignment extends AssignmentExpression<EqualsToken> {
left: ArrayLiteralExpression;
}
export type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment;
export type DestructuringAssignment
= ObjectDestructuringAssignment
| ArrayDestructuringAssignment
;
export type BindingOrAssignmentElement
= VariableDeclaration
| ParameterDeclaration
| BindingElement
| PropertyAssignment // AssignmentProperty
| ShorthandPropertyAssignment // AssignmentProperty
| SpreadAssignment // AssignmentRestProperty
| OmittedExpression // Elision
| SpreadElement // AssignmentRestElement
| ArrayLiteralExpression // ArrayAssignmentPattern
| ObjectLiteralExpression // ObjectAssignmentPattern
| AssignmentExpression<EqualsToken> // AssignmentElement
| Identifier // DestructuringAssignmentTarget
| PropertyAccessExpression // DestructuringAssignmentTarget
| ElementAccessExpression // DestructuringAssignmentTarget
;
export type BindingOrAssignmentElementRestIndicator
= DotDotDotToken // from BindingElement
| SpreadElement // AssignmentRestElement
| SpreadAssignment // AssignmentRestProperty
;
export type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression;
export type ObjectBindingOrAssignmentPattern
= ObjectBindingPattern
| ObjectLiteralExpression // ObjectAssignmentPattern
;
export type ArrayBindingOrAssignmentPattern
= ArrayBindingPattern
| ArrayLiteralExpression // ArrayAssignmentPattern
;
export type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression;
export type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern;
export interface ConditionalExpression extends Expression {
kind: SyntaxKind.ConditionalExpression;
@@ -1279,8 +1335,8 @@ namespace ts {
multiLine?: boolean;
}
export interface SpreadElementExpression extends Expression {
kind: SyntaxKind.SpreadElementExpression;
export interface SpreadElement extends Expression {
kind: SyntaxKind.SpreadElement;
expression: Expression;
}
@@ -1464,6 +1520,16 @@ namespace ts {
kind: SyntaxKind.EndOfDeclarationMarker;
}
/**
* Emits a string of raw text in an expression position. Raw text is never transformed, should
* be ES3 compliant, and should have the same precedence as PrimaryExpression.
*/
/* @internal */
export interface RawExpression extends PrimaryExpression {
kind: SyntaxKind.RawExpression;
text: string;
}
/**
* Marks the beginning of a merged transformed declaration.
*/
@@ -1503,6 +1569,11 @@ namespace ts {
expression: Expression;
}
/* @internal */
export interface PrologueDirective extends ExpressionStatement {
expression: StringLiteral;
}
export interface IfStatement extends Statement {
kind: SyntaxKind.IfStatement;
expression: Expression;
@@ -1687,7 +1758,7 @@ namespace ts {
export interface ModuleDeclaration extends DeclarationStatement {
kind: SyntaxKind.ModuleDeclaration;
name: Identifier | LiteralExpression;
name: Identifier | StringLiteral;
body?: ModuleBlock | NamespaceDeclaration | JSDocNamespaceDeclaration | Identifier;
}
@@ -1893,7 +1964,7 @@ namespace ts {
export interface JSDocRecordMember extends PropertySignature {
kind: SyntaxKind.JSDocRecordMember;
name: Identifier | LiteralExpression;
name: Identifier | StringLiteral | NumericLiteral;
type?: JSDocType;
}
@@ -1913,6 +1984,11 @@ namespace ts {
kind: SyntaxKind.JSDocTag;
}
export interface JSDocAugmentsTag extends JSDocTag {
kind: SyntaxKind.JSDocAugmentsTag;
typeExpression: JSDocTypeExpression;
}
export interface JSDocTemplateTag extends JSDocTag {
kind: SyntaxKind.JSDocTemplateTag;
typeParameters: NodeArray<TypeParameterDeclaration>;
@@ -2103,8 +2179,6 @@ namespace ts {
/* @internal */ moduleAugmentations: LiteralExpression[];
/* @internal */ patternAmbientModules?: PatternAmbientModule[];
/* @internal */ ambientModuleNames: string[];
// The synthesized identifier for an imported external helpers module.
/* @internal */ externalHelpersModuleName?: Identifier;
}
export interface ScriptReferenceHost {
@@ -2192,6 +2266,7 @@ namespace ts {
/* @internal */ getFileProcessingDiagnostics(): DiagnosticCollection;
/* @internal */ getResolvedTypeReferenceDirectives(): Map<ResolvedTypeReferenceDirective>;
/* @internal */ isSourceFileFromExternalLibrary(file: SourceFile): boolean;
// For testing purposes only.
/* @internal */ structureIsReused?: boolean;
}
@@ -2297,6 +2372,8 @@ namespace ts {
isOptionalParameter(node: ParameterDeclaration): boolean;
getAmbientModules(): Symbol[];
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
/* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol;
// Should not be called directly. Should only be accessed through the Program instance.
@@ -2330,6 +2407,7 @@ namespace ts {
writeSpace(text: string): void;
writeStringLiteral(text: string): void;
writeParameter(text: string): void;
writeProperty(text: string): void;
writeSymbol(text: string, symbol: Symbol): void;
writeLine(): void;
increaseIndent(): void;
@@ -2380,6 +2458,12 @@ namespace ts {
CannotBeNamed
}
/* @internal */
export const enum SyntheticSymbolKind {
UnionOrIntersection,
Spread
}
export const enum TypePredicateKind {
This,
Identifier
@@ -2472,6 +2556,7 @@ namespace ts {
getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[];
isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean;
writeLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, writer: SymbolWriter): void;
getJsxFactoryEntity(): EntityName;
}
export const enum SymbolFlags {
@@ -2487,7 +2572,7 @@ namespace ts {
RegularEnum = 0x00000100, // Enum
ValueModule = 0x00000200, // Instantiated module
NamespaceModule = 0x00000400, // Uninstantiated module
TypeLiteral = 0x00000800, // Type Literal
TypeLiteral = 0x00000800, // Type Literal or mapped type
ObjectLiteral = 0x00001000, // Object Literal
Method = 0x00002000, // Method
Constructor = 0x00004000, // Constructor
@@ -2591,7 +2676,9 @@ namespace ts {
instantiations?: Map<Type>; // Instantiations of generic type alias (undefined if non-generic)
mapper?: TypeMapper; // Type mapper for instantiation alias
referenced?: boolean; // True if alias symbol has been referenced as a value
containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property
containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property
leftSpread?: Symbol; // Left source for synthetic spread property
rightSpread?: Symbol; // Right source for synthetic spread property
hasNonUniformType?: boolean; // True if constituents have non-uniform types
isPartial?: boolean; // True if syntheric property of union type occurs in some but not all constituents
isDiscriminantProperty?: boolean; // True if discriminant synthetic property
@@ -2652,6 +2739,7 @@ namespace ts {
resolvedSignature?: Signature; // Cached signature of signature node or call expression
resolvedSymbol?: Symbol; // Cached name resolution result
resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result
maybeTypePredicate?: boolean; // Cached check whether call expression might reference a type predicate
enumMemberValue?: number; // Constant value of enum member
isVisible?: boolean; // Is this node visible
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
@@ -2703,13 +2791,14 @@ namespace ts {
Intrinsic = Any | String | Number | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never,
/* @internal */
Primitive = String | Number | Boolean | Enum | ESSymbol | Void | Undefined | Null | Literal,
StringLike = String | StringLiteral,
StringLike = String | StringLiteral | Index,
NumberLike = Number | NumberLiteral | Enum | EnumLiteral,
BooleanLike = Boolean | BooleanLiteral,
EnumLike = Enum | EnumLiteral,
UnionOrIntersection = Union | Intersection,
StructuredType = Object | Union | Intersection,
StructuredOrTypeParameter = StructuredType | TypeParameter | Index,
TypeVariable = TypeParameter | IndexedAccess,
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
@@ -2763,10 +2852,11 @@ namespace ts {
Reference = 1 << 2, // Generic type reference
Tuple = 1 << 3, // Synthesized generic tuple type
Anonymous = 1 << 4, // Anonymous
Instantiated = 1 << 5, // Instantiated anonymous type
ObjectLiteral = 1 << 6, // Originates in an object literal
EvolvingArray = 1 << 7, // Evolving array type
ObjectLiteralPatternWithComputedProperties = 1 << 8, // Object literal pattern with computed properties
Mapped = 1 << 5, // Mapped
Instantiated = 1 << 6, // Instantiated anonymous or mapped type
ObjectLiteral = 1 << 7, // Originates in an object literal
EvolvingArray = 1 << 8, // Evolving array type
ObjectLiteralPatternWithComputedProperties = 1 << 9, // Object literal pattern with computed properties
ClassOrInterface = Class | Interface
}
@@ -2819,7 +2909,9 @@ namespace ts {
/* @internal */
resolvedProperties: SymbolTable; // Cache of resolved properties
/* @internal */
couldContainTypeParameters: boolean;
resolvedIndexType: IndexType;
/* @internal */
couldContainTypeVariables: boolean;
}
export interface UnionType extends UnionOrIntersectionType { }
@@ -2835,6 +2927,15 @@ namespace ts {
mapper?: TypeMapper; // Instantiation mapper
}
/* @internal */
export interface MappedType extends ObjectType {
declaration: MappedTypeNode;
typeParameter?: TypeParameter;
constraintType?: Type;
templateType?: Type;
mapper?: TypeMapper; // Instantiation mapper
}
export interface EvolvingArrayType extends ObjectType {
elementType: Type; // Element expressions of evolving array type
finalArrayType?: Type; // Final array type of evolving array type
@@ -2866,8 +2967,13 @@ namespace ts {
iteratorElementType?: Type;
}
export interface TypeVariable extends Type {
/* @internal */
resolvedIndexType: IndexType;
}
// Type parameters (TypeFlags.TypeParameter)
export interface TypeParameter extends Type {
export interface TypeParameter extends TypeVariable {
constraint: Type; // Constraint
/* @internal */
target?: TypeParameter; // Instantiation target
@@ -2876,20 +2982,19 @@ namespace ts {
/* @internal */
resolvedApparentType: Type;
/* @internal */
resolvedIndexType: IndexType;
/* @internal */
resolvedIndexedAccessTypes: IndexedAccessType[];
/* @internal */
isThisType?: boolean;
}
export interface IndexType extends Type {
type: TypeParameter;
// Indexed access types (TypeFlags.IndexedAccess)
// Possible forms are T[xxx], xxx[T], or xxx[keyof T], where T is a type variable
export interface IndexedAccessType extends TypeVariable {
objectType: Type;
indexType: Type;
}
export interface IndexedAccessType extends Type {
objectType: Type;
indexType: TypeParameter;
// keyof T types (TypeFlags.Index)
export interface IndexType extends Type {
type: TypeVariable | UnionOrIntersectionType;
}
export const enum SignatureKind {
@@ -2923,6 +3028,8 @@ namespace ts {
isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison
/* @internal */
typePredicate?: TypePredicate;
/* @internal */
instantiations?: Map<Signature>; // Generic signature instantiation cache
}
export const enum IndexKind {
@@ -2940,7 +3047,6 @@ namespace ts {
export interface TypeMapper {
(t: TypeParameter): Type;
mappedTypes?: Type[]; // Types mapped by this mapper
targetTypes?: Type[]; // Types substituted for mapped types
instantiations?: Type[]; // Cache of instantiations created using this type mapper.
context?: InferenceContext; // The inference context this mapper was created from.
// Only inference mappers have this set (in createInferenceMapper).
@@ -3058,6 +3164,7 @@ namespace ts {
moduleResolution?: ModuleResolutionKind;
newLine?: NewLineKind;
noEmit?: boolean;
/*@internal*/noEmitForJsFiles?: boolean;
noEmitHelpers?: boolean;
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
@@ -3078,6 +3185,7 @@ namespace ts {
project?: string;
/* @internal */ pretty?: DiagnosticStyle;
reactNamespace?: string;
jsxFactory?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -3093,7 +3201,7 @@ namespace ts {
target?: ScriptTarget;
traceResolution?: boolean;
types?: string[];
/** Paths used to used to compute primary types search locations */
/** Paths used to compute primary types search locations */
typeRoots?: string[];
/*@internal*/ version?: boolean;
/*@internal*/ watch?: boolean;
@@ -3101,8 +3209,12 @@ namespace ts {
[option: string]: CompilerOptionsValue | undefined;
}
export interface TypingOptions {
export interface TypeAcquisition {
/* @deprecated typingOptions.enableAutoDiscovery
* Use typeAcquisition.enable instead.
*/
enableAutoDiscovery?: boolean;
enable?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean | undefined;
@@ -3113,7 +3225,7 @@ namespace ts {
projectRootPath: string; // The path to the project root directory
safeListPath: string; // The path used to retrieve the safe list
packageNameToTypingLocation: Map<string>; // The map of package names to their cached typing locations
typingOptions: TypingOptions; // Used to customize the typing inference process
typeAcquisition: TypeAcquisition; // Used to customize the type acquisition process
compilerOptions: CompilerOptions; // Used as a source for typing inference
unresolvedImports: ReadonlyArray<string>; // List of unresolved module ids from imports
}
@@ -3160,7 +3272,8 @@ namespace ts {
ES2015 = 2,
ES2016 = 3,
ES2017 = 4,
Latest = ES2017,
ESNext = 5,
Latest = ESNext,
}
export const enum LanguageVariant {
@@ -3177,7 +3290,7 @@ namespace ts {
/** Either a parsed command line or a parsed tsconfig.json */
export interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
typeAcquisition?: TypeAcquisition;
fileNames: string[];
raw?: any;
errors: Diagnostic[];
@@ -3473,43 +3586,45 @@ namespace ts {
// - Flags used to indicate that a node or subtree contains syntax that requires transformation.
TypeScript = 1 << 0,
ContainsTypeScript = 1 << 1,
Jsx = 1 << 2,
ContainsJsx = 1 << 3,
ES2017 = 1 << 4,
ContainsES2017 = 1 << 5,
ES2016 = 1 << 6,
ContainsES2016 = 1 << 7,
ES2015 = 1 << 8,
ContainsES2015 = 1 << 9,
Generator = 1 << 10,
ContainsGenerator = 1 << 11,
DestructuringAssignment = 1 << 12,
ContainsDestructuringAssignment = 1 << 13,
ContainsJsx = 1 << 2,
ContainsESNext = 1 << 3,
ContainsES2017 = 1 << 4,
ContainsES2016 = 1 << 5,
ES2015 = 1 << 6,
ContainsES2015 = 1 << 7,
Generator = 1 << 8,
ContainsGenerator = 1 << 9,
DestructuringAssignment = 1 << 10,
ContainsDestructuringAssignment = 1 << 11,
// Markers
// - Flags used to indicate that a subtree contains a specific transformation.
ContainsDecorators = 1 << 14,
ContainsPropertyInitializer = 1 << 15,
ContainsLexicalThis = 1 << 16,
ContainsCapturedLexicalThis = 1 << 17,
ContainsLexicalThisInComputedPropertyName = 1 << 18,
ContainsDefaultValueAssignments = 1 << 19,
ContainsParameterPropertyAssignments = 1 << 20,
ContainsSpreadElementExpression = 1 << 21,
ContainsComputedPropertyName = 1 << 22,
ContainsBlockScopedBinding = 1 << 23,
ContainsBindingPattern = 1 << 24,
ContainsYield = 1 << 25,
ContainsHoistedDeclarationOrCompletion = 1 << 26,
ContainsDecorators = 1 << 12,
ContainsPropertyInitializer = 1 << 13,
ContainsLexicalThis = 1 << 14,
ContainsCapturedLexicalThis = 1 << 15,
ContainsLexicalThisInComputedPropertyName = 1 << 16,
ContainsDefaultValueAssignments = 1 << 17,
ContainsParameterPropertyAssignments = 1 << 18,
ContainsSpread = 1 << 19,
ContainsObjectSpread = 1 << 20,
ContainsRest = ContainsSpread,
ContainsObjectRest = ContainsObjectSpread,
ContainsComputedPropertyName = 1 << 21,
ContainsBlockScopedBinding = 1 << 22,
ContainsBindingPattern = 1 << 23,
ContainsYield = 1 << 24,
ContainsHoistedDeclarationOrCompletion = 1 << 25,
HasComputedFlags = 1 << 29, // Transform flags have been computed.
// Assertions
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
AssertTypeScript = TypeScript | ContainsTypeScript,
AssertJsx = Jsx | ContainsJsx,
AssertES2017 = ES2017 | ContainsES2017,
AssertES2016 = ES2016 | ContainsES2016,
AssertJsx = ContainsJsx,
AssertESNext = ContainsESNext,
AssertES2017 = ContainsES2017,
AssertES2016 = ContainsES2016,
AssertES2015 = ES2015 | ContainsES2015,
AssertGenerator = Generator | ContainsGenerator,
AssertDestructuringAssignment = DestructuringAssignment | ContainsDestructuringAssignment,
@@ -3517,18 +3632,20 @@ namespace ts {
// Scope Exclusions
// - Bitmasks that exclude flags from propagating out of a specific context
// into the subtree flags of their container.
NodeExcludes = TypeScript | Jsx | ES2017 | ES2016 | ES2015 | DestructuringAssignment | Generator | HasComputedFlags,
ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
NodeExcludes = TypeScript | ES2015 | DestructuringAssignment | Generator | HasComputedFlags,
ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest,
FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest,
ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest,
MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest,
ClassExcludes = NodeExcludes | ContainsDecorators | ContainsPropertyInitializer | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsParameterPropertyAssignments | ContainsLexicalThisInComputedPropertyName,
ModuleExcludes = NodeExcludes | ContainsDecorators | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion,
TypeExcludes = ~ContainsTypeScript,
ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName,
ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpreadElementExpression,
VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern,
ParameterExcludes = NodeExcludes | ContainsBindingPattern,
ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName | ContainsObjectSpread,
ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpread,
VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern | ContainsObjectRest,
ParameterExcludes = NodeExcludes,
CatchClauseExcludes = NodeExcludes | ContainsObjectRest,
BindingPatternExcludes = NodeExcludes | ContainsRest,
// Masks
// - Additional bitmasks
@@ -3538,45 +3655,70 @@ namespace ts {
/* @internal */
export interface EmitNode {
flags?: EmitFlags;
commentRange?: TextRange;
sourceMapRange?: TextRange;
tokenSourceMapRanges?: Map<TextRange>;
annotatedNodes?: Node[]; // Tracks Parse-tree nodes with EmitNodes for eventual cleanup.
constantValue?: number;
flags?: EmitFlags; // Flags that customize emit
commentRange?: TextRange; // The text range to use when emitting leading or trailing comments
sourceMapRange?: TextRange; // The text range to use when emitting leading or trailing source mappings
tokenSourceMapRanges?: Map<TextRange>; // The text range to use when emitting source mappings for tokens
constantValue?: number; // The constant value of an expression
externalHelpersModuleName?: Identifier; // The local name for an imported helpers module
helpers?: EmitHelper[]; // Emit helpers for the node
}
/* @internal */
export const enum EmitFlags {
EmitEmitHelpers = 1 << 0, // Any emit helpers should be written to this node.
EmitExportStar = 1 << 1, // The export * helper should be written to this node.
EmitSuperHelper = 1 << 2, // Emit the basic _super helper for async methods.
EmitAdvancedSuperHelper = 1 << 3, // Emit the advanced _super helper for async methods.
UMDDefine = 1 << 4, // This node should be replaced with the UMD define helper.
SingleLine = 1 << 5, // The contents of this node should be emitted on a single line.
AdviseOnEmitNode = 1 << 6, // The printer should invoke the onEmitNode callback when printing this node.
NoSubstitution = 1 << 7, // Disables further substitution of an expression.
CapturesThis = 1 << 8, // The function captures a lexical `this`
NoLeadingSourceMap = 1 << 9, // Do not emit a leading source map location for this node.
NoTrailingSourceMap = 1 << 10, // Do not emit a trailing source map location for this node.
SingleLine = 1 << 0, // The contents of this node should be emitted on a single line.
AdviseOnEmitNode = 1 << 1, // The printer should invoke the onEmitNode callback when printing this node.
NoSubstitution = 1 << 2, // Disables further substitution of an expression.
CapturesThis = 1 << 3, // The function captures a lexical `this`
NoLeadingSourceMap = 1 << 4, // Do not emit a leading source map location for this node.
NoTrailingSourceMap = 1 << 5, // Do not emit a trailing source map location for this node.
NoSourceMap = NoLeadingSourceMap | NoTrailingSourceMap, // Do not emit a source map location for this node.
NoNestedSourceMaps = 1 << 11, // Do not emit source map locations for children of this node.
NoTokenLeadingSourceMaps = 1 << 12, // Do not emit leading source map location for token nodes.
NoTokenTrailingSourceMaps = 1 << 13, // Do not emit trailing source map location for token nodes.
NoNestedSourceMaps = 1 << 6, // Do not emit source map locations for children of this node.
NoTokenLeadingSourceMaps = 1 << 7, // Do not emit leading source map location for token nodes.
NoTokenTrailingSourceMaps = 1 << 8, // Do not emit trailing source map location for token nodes.
NoTokenSourceMaps = NoTokenLeadingSourceMaps | NoTokenTrailingSourceMaps, // Do not emit source map locations for tokens of this node.
NoLeadingComments = 1 << 14, // Do not emit leading comments for this node.
NoTrailingComments = 1 << 15, // Do not emit trailing comments for this node.
NoLeadingComments = 1 << 9, // Do not emit leading comments for this node.
NoTrailingComments = 1 << 10, // Do not emit trailing comments for this node.
NoComments = NoLeadingComments | NoTrailingComments, // Do not emit comments for this node.
NoNestedComments = 1 << 16,
ExportName = 1 << 17, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal).
LocalName = 1 << 18, // Ensure an export prefix is not added for an identifier that points to an exported declaration.
Indented = 1 << 19, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter).
NoIndentation = 1 << 20, // Do not indent the node.
AsyncFunctionBody = 1 << 21,
ReuseTempVariableScope = 1 << 22, // Reuse the existing temp variable scope during emit.
CustomPrologue = 1 << 23, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed).
NoHoisting = 1 << 24, // Do not hoist this declaration in --module system
HasEndOfDeclarationMarker = 1 << 25, // Declaration has an associated NotEmittedStatement to mark the end of the declaration
NoNestedComments = 1 << 11,
HelperName = 1 << 12,
ExportName = 1 << 13, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal).
LocalName = 1 << 14, // Ensure an export prefix is not added for an identifier that points to an exported declaration.
Indented = 1 << 15, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter).
NoIndentation = 1 << 16, // Do not indent the node.
AsyncFunctionBody = 1 << 17,
ReuseTempVariableScope = 1 << 18, // Reuse the existing temp variable scope during emit.
CustomPrologue = 1 << 19, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed).
NoHoisting = 1 << 20, // Do not hoist this declaration in --module system
HasEndOfDeclarationMarker = 1 << 21, // Declaration has an associated NotEmittedStatement to mark the end of the declaration
}
/* @internal */
export interface EmitHelper {
readonly name: string; // A unique name for this helper.
readonly scoped: boolean; // Indicates whether ther helper MUST be emitted in the current scope.
readonly text: string; // ES3-compatible raw script text.
readonly priority?: number; // Helpers with a higher priority are emitted earlier than other helpers on the node.
}
/**
* Used by the checker, this enum keeps track of external emit helpers that should be type
* checked.
*/
/* @internal */
export const enum ExternalEmitHelpers {
Extends = 1 << 0, // __extends (used by the ES2015 class transformation)
Assign = 1 << 1, // __assign (used by Jsx and ESNext object spread transformations)
Rest = 1 << 2, // __rest (used by ESNext object rest transformation)
Decorate = 1 << 3, // __decorate (used by TypeScript decorators transformation)
Metadata = 1 << 4, // __metadata (used by TypeScript decorators transformation)
Param = 1 << 5, // __param (used by TypeScript decorators transformation)
Awaiter = 1 << 6, // __awaiter (used by ES2017 async functions transformation)
Generator = 1 << 7, // __generator (used by ES2015 generator transformation)
FirstEmitHelper = Extends,
LastEmitHelper = Generator
}
/* @internal */
@@ -3587,16 +3729,123 @@ namespace ts {
Unspecified, // Emitting an otherwise unspecified node
}
/** Additional context provided to `visitEachChild` */
/* @internal */
export interface LexicalEnvironment {
export interface EmitHost extends ScriptReferenceHost {
getSourceFiles(): SourceFile[];
/* @internal */
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
getCommonSourceDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
isEmitBlocked(emitFileName: string): boolean;
writeFile: WriteFileCallback;
}
/* @internal */
export interface TransformationContext {
getCompilerOptions(): CompilerOptions;
getEmitResolver(): EmitResolver;
getEmitHost(): EmitHost;
/** Starts a new lexical environment. */
startLexicalEnvironment(): void;
/** Suspends the current lexical environment, usually after visiting a parameter list. */
suspendLexicalEnvironment(): void;
/** Resumes a suspended lexical environment, usually before visiting a function body. */
resumeLexicalEnvironment(): void;
/** Ends a lexical environment, returning any declarations. */
endLexicalEnvironment(): Statement[];
/**
* Hoists a function declaration to the containing scope.
*/
hoistFunctionDeclaration(node: FunctionDeclaration): void;
/**
* Hoists a variable declaration to the containing scope.
*/
hoistVariableDeclaration(node: Identifier): void;
/**
* Records a request for a non-scoped emit helper in the current context.
*/
requestEmitHelper(helper: EmitHelper): void;
/**
* Gets and resets the requested non-scoped emit helpers.
*/
readEmitHelpers(): EmitHelper[] | undefined;
/**
* Enables expression substitutions in the pretty printer for the provided SyntaxKind.
*/
enableSubstitution(kind: SyntaxKind): void;
/**
* Determines whether expression substitutions are enabled for the provided node.
*/
isSubstitutionEnabled(node: Node): boolean;
/**
* Hook used by transformers to substitute expressions just before they
* are emitted by the pretty printer.
*/
onSubstituteNode?: (emitContext: EmitContext, node: Node) => Node;
/**
* Enables before/after emit notifications in the pretty printer for the provided
* SyntaxKind.
*/
enableEmitNotification(kind: SyntaxKind): void;
/**
* Determines whether before/after emit notifications should be raised in the pretty
* printer when it emits a node.
*/
isEmitNotificationEnabled(node: Node): boolean;
/**
* Hook used to allow transformers to capture state before or after
* the printer emits a node.
*/
onEmitNode?: (emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) => void;
}
/* @internal */
export interface TransformationResult {
/**
* Gets the transformed source files.
*/
transformed: SourceFile[];
/**
* Emits the substitute for a node, if one is available; otherwise, emits the node.
*
* @param emitContext The current emit context.
* @param node The node to substitute.
* @param emitCallback A callback used to emit the node or its substitute.
*/
emitNodeWithSubstitution(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void;
/**
* Emits a node with possible notification.
*
* @param emitContext The current emit context.
* @param node The node to emit.
* @param emitCallback A callback used to emit the node.
*/
emitNodeWithNotification(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void;
}
/* @internal */
export type Transformer = (context: TransformationContext) => (node: SourceFile) => SourceFile;
export interface TextSpan {
start: number;
+314 -346
View File
File diff suppressed because it is too large Load Diff
+322 -274
View File
@@ -99,20 +99,26 @@ namespace ts {
return node ? f(initial, node) : initial;
}
function reduceNodeArray<T>(nodes: Node[], f: (memo: T, nodes: Node[]) => T, initial: T) {
return nodes ? f(initial, nodes) : initial;
}
/**
* Similar to `reduceLeft`, performs a reduction against each child of a node.
* NOTE: Unlike `forEachChild`, this does *not* visit every node. Only nodes added to the
* `nodeEdgeTraversalMap` above will be visited.
*
* @param node The node containing the children to reduce.
* @param f The callback function
* @param initial The initial value to supply to the reduction.
* @param f The callback function
*/
export function reduceEachChild<T>(node: Node, f: (memo: T, node: Node) => T, initial: T): T {
export function reduceEachChild<T>(node: Node, initial: T, cbNode: (memo: T, node: Node) => T, cbNodeArray?: (memo: T, nodes: Node[]) => T): T {
if (node === undefined) {
return initial;
}
const reduceNodes: (nodes: Node[], f: (memo: T, node: Node | Node[]) => T, initial: T) => T = cbNodeArray ? reduceNodeArray : reduceLeft;
const cbNodes = cbNodeArray || cbNode;
const kind = node.kind;
// No need to visit nodes with no children.
@@ -138,127 +144,127 @@ namespace ts {
// Names
case SyntaxKind.ComputedPropertyName:
result = reduceNode((<ComputedPropertyName>node).expression, f, result);
result = reduceNode((<ComputedPropertyName>node).expression, cbNode, result);
break;
// Signature elements
case SyntaxKind.Parameter:
result = reduceLeft((<ParameterDeclaration>node).decorators, f, result);
result = reduceLeft((<ParameterDeclaration>node).modifiers, f, result);
result = reduceNode((<ParameterDeclaration>node).name, f, result);
result = reduceNode((<ParameterDeclaration>node).type, f, result);
result = reduceNode((<ParameterDeclaration>node).initializer, f, result);
result = reduceNodes((<ParameterDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<ParameterDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<ParameterDeclaration>node).name, cbNode, result);
result = reduceNode((<ParameterDeclaration>node).type, cbNode, result);
result = reduceNode((<ParameterDeclaration>node).initializer, cbNode, result);
break;
case SyntaxKind.Decorator:
result = reduceNode((<Decorator>node).expression, f, result);
result = reduceNode((<Decorator>node).expression, cbNode, result);
break;
// Type member
case SyntaxKind.PropertyDeclaration:
result = reduceLeft((<PropertyDeclaration>node).decorators, f, result);
result = reduceLeft((<PropertyDeclaration>node).modifiers, f, result);
result = reduceNode((<PropertyDeclaration>node).name, f, result);
result = reduceNode((<PropertyDeclaration>node).type, f, result);
result = reduceNode((<PropertyDeclaration>node).initializer, f, result);
result = reduceNodes((<PropertyDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<PropertyDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<PropertyDeclaration>node).name, cbNode, result);
result = reduceNode((<PropertyDeclaration>node).type, cbNode, result);
result = reduceNode((<PropertyDeclaration>node).initializer, cbNode, result);
break;
case SyntaxKind.MethodDeclaration:
result = reduceLeft((<MethodDeclaration>node).decorators, f, result);
result = reduceLeft((<MethodDeclaration>node).modifiers, f, result);
result = reduceNode((<MethodDeclaration>node).name, f, result);
result = reduceLeft((<MethodDeclaration>node).typeParameters, f, result);
result = reduceLeft((<MethodDeclaration>node).parameters, f, result);
result = reduceNode((<MethodDeclaration>node).type, f, result);
result = reduceNode((<MethodDeclaration>node).body, f, result);
result = reduceNodes((<MethodDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<MethodDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<MethodDeclaration>node).name, cbNode, result);
result = reduceNodes((<MethodDeclaration>node).typeParameters, cbNodes, result);
result = reduceNodes((<MethodDeclaration>node).parameters, cbNodes, result);
result = reduceNode((<MethodDeclaration>node).type, cbNode, result);
result = reduceNode((<MethodDeclaration>node).body, cbNode, result);
break;
case SyntaxKind.Constructor:
result = reduceLeft((<ConstructorDeclaration>node).modifiers, f, result);
result = reduceLeft((<ConstructorDeclaration>node).parameters, f, result);
result = reduceNode((<ConstructorDeclaration>node).body, f, result);
result = reduceNodes((<ConstructorDeclaration>node).modifiers, cbNodes, result);
result = reduceNodes((<ConstructorDeclaration>node).parameters, cbNodes, result);
result = reduceNode((<ConstructorDeclaration>node).body, cbNode, result);
break;
case SyntaxKind.GetAccessor:
result = reduceLeft((<GetAccessorDeclaration>node).decorators, f, result);
result = reduceLeft((<GetAccessorDeclaration>node).modifiers, f, result);
result = reduceNode((<GetAccessorDeclaration>node).name, f, result);
result = reduceLeft((<GetAccessorDeclaration>node).parameters, f, result);
result = reduceNode((<GetAccessorDeclaration>node).type, f, result);
result = reduceNode((<GetAccessorDeclaration>node).body, f, result);
result = reduceNodes((<GetAccessorDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<GetAccessorDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<GetAccessorDeclaration>node).name, cbNode, result);
result = reduceNodes((<GetAccessorDeclaration>node).parameters, cbNodes, result);
result = reduceNode((<GetAccessorDeclaration>node).type, cbNode, result);
result = reduceNode((<GetAccessorDeclaration>node).body, cbNode, result);
break;
case SyntaxKind.SetAccessor:
result = reduceLeft((<GetAccessorDeclaration>node).decorators, f, result);
result = reduceLeft((<GetAccessorDeclaration>node).modifiers, f, result);
result = reduceNode((<GetAccessorDeclaration>node).name, f, result);
result = reduceLeft((<GetAccessorDeclaration>node).parameters, f, result);
result = reduceNode((<GetAccessorDeclaration>node).body, f, result);
result = reduceNodes((<GetAccessorDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<GetAccessorDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<GetAccessorDeclaration>node).name, cbNode, result);
result = reduceNodes((<GetAccessorDeclaration>node).parameters, cbNodes, result);
result = reduceNode((<GetAccessorDeclaration>node).body, cbNode, result);
break;
// Binding patterns
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
result = reduceLeft((<BindingPattern>node).elements, f, result);
result = reduceNodes((<BindingPattern>node).elements, cbNodes, result);
break;
case SyntaxKind.BindingElement:
result = reduceNode((<BindingElement>node).propertyName, f, result);
result = reduceNode((<BindingElement>node).name, f, result);
result = reduceNode((<BindingElement>node).initializer, f, result);
result = reduceNode((<BindingElement>node).propertyName, cbNode, result);
result = reduceNode((<BindingElement>node).name, cbNode, result);
result = reduceNode((<BindingElement>node).initializer, cbNode, result);
break;
// Expression
case SyntaxKind.ArrayLiteralExpression:
result = reduceLeft((<ArrayLiteralExpression>node).elements, f, result);
result = reduceNodes((<ArrayLiteralExpression>node).elements, cbNodes, result);
break;
case SyntaxKind.ObjectLiteralExpression:
result = reduceLeft((<ObjectLiteralExpression>node).properties, f, result);
result = reduceNodes((<ObjectLiteralExpression>node).properties, cbNodes, result);
break;
case SyntaxKind.PropertyAccessExpression:
result = reduceNode((<PropertyAccessExpression>node).expression, f, result);
result = reduceNode((<PropertyAccessExpression>node).name, f, result);
result = reduceNode((<PropertyAccessExpression>node).expression, cbNode, result);
result = reduceNode((<PropertyAccessExpression>node).name, cbNode, result);
break;
case SyntaxKind.ElementAccessExpression:
result = reduceNode((<ElementAccessExpression>node).expression, f, result);
result = reduceNode((<ElementAccessExpression>node).argumentExpression, f, result);
result = reduceNode((<ElementAccessExpression>node).expression, cbNode, result);
result = reduceNode((<ElementAccessExpression>node).argumentExpression, cbNode, result);
break;
case SyntaxKind.CallExpression:
result = reduceNode((<CallExpression>node).expression, f, result);
result = reduceLeft((<CallExpression>node).typeArguments, f, result);
result = reduceLeft((<CallExpression>node).arguments, f, result);
result = reduceNode((<CallExpression>node).expression, cbNode, result);
result = reduceNodes((<CallExpression>node).typeArguments, cbNodes, result);
result = reduceNodes((<CallExpression>node).arguments, cbNodes, result);
break;
case SyntaxKind.NewExpression:
result = reduceNode((<NewExpression>node).expression, f, result);
result = reduceLeft((<NewExpression>node).typeArguments, f, result);
result = reduceLeft((<NewExpression>node).arguments, f, result);
result = reduceNode((<NewExpression>node).expression, cbNode, result);
result = reduceNodes((<NewExpression>node).typeArguments, cbNodes, result);
result = reduceNodes((<NewExpression>node).arguments, cbNodes, result);
break;
case SyntaxKind.TaggedTemplateExpression:
result = reduceNode((<TaggedTemplateExpression>node).tag, f, result);
result = reduceNode((<TaggedTemplateExpression>node).template, f, result);
result = reduceNode((<TaggedTemplateExpression>node).tag, cbNode, result);
result = reduceNode((<TaggedTemplateExpression>node).template, cbNode, result);
break;
case SyntaxKind.FunctionExpression:
result = reduceLeft((<FunctionExpression>node).modifiers, f, result);
result = reduceNode((<FunctionExpression>node).name, f, result);
result = reduceLeft((<FunctionExpression>node).typeParameters, f, result);
result = reduceLeft((<FunctionExpression>node).parameters, f, result);
result = reduceNode((<FunctionExpression>node).type, f, result);
result = reduceNode((<FunctionExpression>node).body, f, result);
result = reduceNodes((<FunctionExpression>node).modifiers, cbNodes, result);
result = reduceNode((<FunctionExpression>node).name, cbNode, result);
result = reduceNodes((<FunctionExpression>node).typeParameters, cbNodes, result);
result = reduceNodes((<FunctionExpression>node).parameters, cbNodes, result);
result = reduceNode((<FunctionExpression>node).type, cbNode, result);
result = reduceNode((<FunctionExpression>node).body, cbNode, result);
break;
case SyntaxKind.ArrowFunction:
result = reduceLeft((<ArrowFunction>node).modifiers, f, result);
result = reduceLeft((<ArrowFunction>node).typeParameters, f, result);
result = reduceLeft((<ArrowFunction>node).parameters, f, result);
result = reduceNode((<ArrowFunction>node).type, f, result);
result = reduceNode((<ArrowFunction>node).body, f, result);
result = reduceNodes((<ArrowFunction>node).modifiers, cbNodes, result);
result = reduceNodes((<ArrowFunction>node).typeParameters, cbNodes, result);
result = reduceNodes((<ArrowFunction>node).parameters, cbNodes, result);
result = reduceNode((<ArrowFunction>node).type, cbNode, result);
result = reduceNode((<ArrowFunction>node).body, cbNode, result);
break;
case SyntaxKind.ParenthesizedExpression:
@@ -267,256 +273,260 @@ namespace ts {
case SyntaxKind.VoidExpression:
case SyntaxKind.AwaitExpression:
case SyntaxKind.YieldExpression:
case SyntaxKind.SpreadElementExpression:
case SyntaxKind.SpreadElement:
case SyntaxKind.NonNullExpression:
result = reduceNode((<ParenthesizedExpression | DeleteExpression | TypeOfExpression | VoidExpression | AwaitExpression | YieldExpression | SpreadElementExpression | NonNullExpression>node).expression, f, result);
result = reduceNode((<ParenthesizedExpression | DeleteExpression | TypeOfExpression | VoidExpression | AwaitExpression | YieldExpression | SpreadElement | NonNullExpression>node).expression, cbNode, result);
break;
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
result = reduceNode((<PrefixUnaryExpression | PostfixUnaryExpression>node).operand, f, result);
result = reduceNode((<PrefixUnaryExpression | PostfixUnaryExpression>node).operand, cbNode, result);
break;
case SyntaxKind.BinaryExpression:
result = reduceNode((<BinaryExpression>node).left, f, result);
result = reduceNode((<BinaryExpression>node).right, f, result);
result = reduceNode((<BinaryExpression>node).left, cbNode, result);
result = reduceNode((<BinaryExpression>node).right, cbNode, result);
break;
case SyntaxKind.ConditionalExpression:
result = reduceNode((<ConditionalExpression>node).condition, f, result);
result = reduceNode((<ConditionalExpression>node).whenTrue, f, result);
result = reduceNode((<ConditionalExpression>node).whenFalse, f, result);
result = reduceNode((<ConditionalExpression>node).condition, cbNode, result);
result = reduceNode((<ConditionalExpression>node).whenTrue, cbNode, result);
result = reduceNode((<ConditionalExpression>node).whenFalse, cbNode, result);
break;
case SyntaxKind.TemplateExpression:
result = reduceNode((<TemplateExpression>node).head, f, result);
result = reduceLeft((<TemplateExpression>node).templateSpans, f, result);
result = reduceNode((<TemplateExpression>node).head, cbNode, result);
result = reduceNodes((<TemplateExpression>node).templateSpans, cbNodes, result);
break;
case SyntaxKind.ClassExpression:
result = reduceLeft((<ClassExpression>node).modifiers, f, result);
result = reduceNode((<ClassExpression>node).name, f, result);
result = reduceLeft((<ClassExpression>node).typeParameters, f, result);
result = reduceLeft((<ClassExpression>node).heritageClauses, f, result);
result = reduceLeft((<ClassExpression>node).members, f, result);
result = reduceNodes((<ClassExpression>node).modifiers, cbNodes, result);
result = reduceNode((<ClassExpression>node).name, cbNode, result);
result = reduceNodes((<ClassExpression>node).typeParameters, cbNodes, result);
result = reduceNodes((<ClassExpression>node).heritageClauses, cbNodes, result);
result = reduceNodes((<ClassExpression>node).members, cbNodes, result);
break;
case SyntaxKind.ExpressionWithTypeArguments:
result = reduceNode((<ExpressionWithTypeArguments>node).expression, f, result);
result = reduceLeft((<ExpressionWithTypeArguments>node).typeArguments, f, result);
result = reduceNode((<ExpressionWithTypeArguments>node).expression, cbNode, result);
result = reduceNodes((<ExpressionWithTypeArguments>node).typeArguments, cbNodes, result);
break;
// Misc
case SyntaxKind.TemplateSpan:
result = reduceNode((<TemplateSpan>node).expression, f, result);
result = reduceNode((<TemplateSpan>node).literal, f, result);
result = reduceNode((<TemplateSpan>node).expression, cbNode, result);
result = reduceNode((<TemplateSpan>node).literal, cbNode, result);
break;
// Element
case SyntaxKind.Block:
result = reduceLeft((<Block>node).statements, f, result);
result = reduceNodes((<Block>node).statements, cbNodes, result);
break;
case SyntaxKind.VariableStatement:
result = reduceLeft((<VariableStatement>node).modifiers, f, result);
result = reduceNode((<VariableStatement>node).declarationList, f, result);
result = reduceNodes((<VariableStatement>node).modifiers, cbNodes, result);
result = reduceNode((<VariableStatement>node).declarationList, cbNode, result);
break;
case SyntaxKind.ExpressionStatement:
result = reduceNode((<ExpressionStatement>node).expression, f, result);
result = reduceNode((<ExpressionStatement>node).expression, cbNode, result);
break;
case SyntaxKind.IfStatement:
result = reduceNode((<IfStatement>node).expression, f, result);
result = reduceNode((<IfStatement>node).thenStatement, f, result);
result = reduceNode((<IfStatement>node).elseStatement, f, result);
result = reduceNode((<IfStatement>node).expression, cbNode, result);
result = reduceNode((<IfStatement>node).thenStatement, cbNode, result);
result = reduceNode((<IfStatement>node).elseStatement, cbNode, result);
break;
case SyntaxKind.DoStatement:
result = reduceNode((<DoStatement>node).statement, f, result);
result = reduceNode((<DoStatement>node).expression, f, result);
result = reduceNode((<DoStatement>node).statement, cbNode, result);
result = reduceNode((<DoStatement>node).expression, cbNode, result);
break;
case SyntaxKind.WhileStatement:
case SyntaxKind.WithStatement:
result = reduceNode((<WhileStatement | WithStatement>node).expression, f, result);
result = reduceNode((<WhileStatement | WithStatement>node).statement, f, result);
result = reduceNode((<WhileStatement | WithStatement>node).expression, cbNode, result);
result = reduceNode((<WhileStatement | WithStatement>node).statement, cbNode, result);
break;
case SyntaxKind.ForStatement:
result = reduceNode((<ForStatement>node).initializer, f, result);
result = reduceNode((<ForStatement>node).condition, f, result);
result = reduceNode((<ForStatement>node).incrementor, f, result);
result = reduceNode((<ForStatement>node).statement, f, result);
result = reduceNode((<ForStatement>node).initializer, cbNode, result);
result = reduceNode((<ForStatement>node).condition, cbNode, result);
result = reduceNode((<ForStatement>node).incrementor, cbNode, result);
result = reduceNode((<ForStatement>node).statement, cbNode, result);
break;
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
result = reduceNode((<ForInStatement | ForOfStatement>node).initializer, f, result);
result = reduceNode((<ForInStatement | ForOfStatement>node).expression, f, result);
result = reduceNode((<ForInStatement | ForOfStatement>node).statement, f, result);
result = reduceNode((<ForInStatement | ForOfStatement>node).initializer, cbNode, result);
result = reduceNode((<ForInStatement | ForOfStatement>node).expression, cbNode, result);
result = reduceNode((<ForInStatement | ForOfStatement>node).statement, cbNode, result);
break;
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
result = reduceNode((<ReturnStatement>node).expression, f, result);
result = reduceNode((<ReturnStatement>node).expression, cbNode, result);
break;
case SyntaxKind.SwitchStatement:
result = reduceNode((<SwitchStatement>node).expression, f, result);
result = reduceNode((<SwitchStatement>node).caseBlock, f, result);
result = reduceNode((<SwitchStatement>node).expression, cbNode, result);
result = reduceNode((<SwitchStatement>node).caseBlock, cbNode, result);
break;
case SyntaxKind.LabeledStatement:
result = reduceNode((<LabeledStatement>node).label, f, result);
result = reduceNode((<LabeledStatement>node).statement, f, result);
result = reduceNode((<LabeledStatement>node).label, cbNode, result);
result = reduceNode((<LabeledStatement>node).statement, cbNode, result);
break;
case SyntaxKind.TryStatement:
result = reduceNode((<TryStatement>node).tryBlock, f, result);
result = reduceNode((<TryStatement>node).catchClause, f, result);
result = reduceNode((<TryStatement>node).finallyBlock, f, result);
result = reduceNode((<TryStatement>node).tryBlock, cbNode, result);
result = reduceNode((<TryStatement>node).catchClause, cbNode, result);
result = reduceNode((<TryStatement>node).finallyBlock, cbNode, result);
break;
case SyntaxKind.VariableDeclaration:
result = reduceNode((<VariableDeclaration>node).name, f, result);
result = reduceNode((<VariableDeclaration>node).type, f, result);
result = reduceNode((<VariableDeclaration>node).initializer, f, result);
result = reduceNode((<VariableDeclaration>node).name, cbNode, result);
result = reduceNode((<VariableDeclaration>node).type, cbNode, result);
result = reduceNode((<VariableDeclaration>node).initializer, cbNode, result);
break;
case SyntaxKind.VariableDeclarationList:
result = reduceLeft((<VariableDeclarationList>node).declarations, f, result);
result = reduceNodes((<VariableDeclarationList>node).declarations, cbNodes, result);
break;
case SyntaxKind.FunctionDeclaration:
result = reduceLeft((<FunctionDeclaration>node).decorators, f, result);
result = reduceLeft((<FunctionDeclaration>node).modifiers, f, result);
result = reduceNode((<FunctionDeclaration>node).name, f, result);
result = reduceLeft((<FunctionDeclaration>node).typeParameters, f, result);
result = reduceLeft((<FunctionDeclaration>node).parameters, f, result);
result = reduceNode((<FunctionDeclaration>node).type, f, result);
result = reduceNode((<FunctionDeclaration>node).body, f, result);
result = reduceNodes((<FunctionDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<FunctionDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<FunctionDeclaration>node).name, cbNode, result);
result = reduceNodes((<FunctionDeclaration>node).typeParameters, cbNodes, result);
result = reduceNodes((<FunctionDeclaration>node).parameters, cbNodes, result);
result = reduceNode((<FunctionDeclaration>node).type, cbNode, result);
result = reduceNode((<FunctionDeclaration>node).body, cbNode, result);
break;
case SyntaxKind.ClassDeclaration:
result = reduceLeft((<ClassDeclaration>node).decorators, f, result);
result = reduceLeft((<ClassDeclaration>node).modifiers, f, result);
result = reduceNode((<ClassDeclaration>node).name, f, result);
result = reduceLeft((<ClassDeclaration>node).typeParameters, f, result);
result = reduceLeft((<ClassDeclaration>node).heritageClauses, f, result);
result = reduceLeft((<ClassDeclaration>node).members, f, result);
result = reduceNodes((<ClassDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<ClassDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<ClassDeclaration>node).name, cbNode, result);
result = reduceNodes((<ClassDeclaration>node).typeParameters, cbNodes, result);
result = reduceNodes((<ClassDeclaration>node).heritageClauses, cbNodes, result);
result = reduceNodes((<ClassDeclaration>node).members, cbNodes, result);
break;
case SyntaxKind.CaseBlock:
result = reduceLeft((<CaseBlock>node).clauses, f, result);
result = reduceNodes((<CaseBlock>node).clauses, cbNodes, result);
break;
case SyntaxKind.ImportDeclaration:
result = reduceLeft((<ImportDeclaration>node).decorators, f, result);
result = reduceLeft((<ImportDeclaration>node).modifiers, f, result);
result = reduceNode((<ImportDeclaration>node).importClause, f, result);
result = reduceNode((<ImportDeclaration>node).moduleSpecifier, f, result);
result = reduceNodes((<ImportDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<ImportDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<ImportDeclaration>node).importClause, cbNode, result);
result = reduceNode((<ImportDeclaration>node).moduleSpecifier, cbNode, result);
break;
case SyntaxKind.ImportClause:
result = reduceNode((<ImportClause>node).name, f, result);
result = reduceNode((<ImportClause>node).namedBindings, f, result);
result = reduceNode((<ImportClause>node).name, cbNode, result);
result = reduceNode((<ImportClause>node).namedBindings, cbNode, result);
break;
case SyntaxKind.NamespaceImport:
result = reduceNode((<NamespaceImport>node).name, f, result);
result = reduceNode((<NamespaceImport>node).name, cbNode, result);
break;
case SyntaxKind.NamedImports:
case SyntaxKind.NamedExports:
result = reduceLeft((<NamedImports | NamedExports>node).elements, f, result);
result = reduceNodes((<NamedImports | NamedExports>node).elements, cbNodes, result);
break;
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ExportSpecifier:
result = reduceNode((<ImportSpecifier | ExportSpecifier>node).propertyName, f, result);
result = reduceNode((<ImportSpecifier | ExportSpecifier>node).name, f, result);
result = reduceNode((<ImportSpecifier | ExportSpecifier>node).propertyName, cbNode, result);
result = reduceNode((<ImportSpecifier | ExportSpecifier>node).name, cbNode, result);
break;
case SyntaxKind.ExportAssignment:
result = reduceLeft((<ExportAssignment>node).decorators, f, result);
result = reduceLeft((<ExportAssignment>node).modifiers, f, result);
result = reduceNode((<ExportAssignment>node).expression, f, result);
result = reduceLeft((<ExportAssignment>node).decorators, cbNode, result);
result = reduceLeft((<ExportAssignment>node).modifiers, cbNode, result);
result = reduceNode((<ExportAssignment>node).expression, cbNode, result);
break;
case SyntaxKind.ExportDeclaration:
result = reduceLeft((<ExportDeclaration>node).decorators, f, result);
result = reduceLeft((<ExportDeclaration>node).modifiers, f, result);
result = reduceNode((<ExportDeclaration>node).exportClause, f, result);
result = reduceNode((<ExportDeclaration>node).moduleSpecifier, f, result);
result = reduceLeft((<ExportDeclaration>node).decorators, cbNode, result);
result = reduceLeft((<ExportDeclaration>node).modifiers, cbNode, result);
result = reduceNode((<ExportDeclaration>node).exportClause, cbNode, result);
result = reduceNode((<ExportDeclaration>node).moduleSpecifier, cbNode, result);
break;
// JSX
case SyntaxKind.JsxElement:
result = reduceNode((<JsxElement>node).openingElement, f, result);
result = reduceLeft((<JsxElement>node).children, f, result);
result = reduceNode((<JsxElement>node).closingElement, f, result);
result = reduceNode((<JsxElement>node).openingElement, cbNode, result);
result = reduceLeft((<JsxElement>node).children, cbNode, result);
result = reduceNode((<JsxElement>node).closingElement, cbNode, result);
break;
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxOpeningElement:
result = reduceNode((<JsxSelfClosingElement | JsxOpeningElement>node).tagName, f, result);
result = reduceLeft((<JsxSelfClosingElement | JsxOpeningElement>node).attributes, f, result);
result = reduceNode((<JsxSelfClosingElement | JsxOpeningElement>node).tagName, cbNode, result);
result = reduceNodes((<JsxSelfClosingElement | JsxOpeningElement>node).attributes, cbNodes, result);
break;
case SyntaxKind.JsxClosingElement:
result = reduceNode((<JsxClosingElement>node).tagName, f, result);
result = reduceNode((<JsxClosingElement>node).tagName, cbNode, result);
break;
case SyntaxKind.JsxAttribute:
result = reduceNode((<JsxAttribute>node).name, f, result);
result = reduceNode((<JsxAttribute>node).initializer, f, result);
result = reduceNode((<JsxAttribute>node).name, cbNode, result);
result = reduceNode((<JsxAttribute>node).initializer, cbNode, result);
break;
case SyntaxKind.JsxSpreadAttribute:
result = reduceNode((<JsxSpreadAttribute>node).expression, f, result);
result = reduceNode((<JsxSpreadAttribute>node).expression, cbNode, result);
break;
case SyntaxKind.JsxExpression:
result = reduceNode((<JsxExpression>node).expression, f, result);
result = reduceNode((<JsxExpression>node).expression, cbNode, result);
break;
// Clauses
case SyntaxKind.CaseClause:
result = reduceNode((<CaseClause>node).expression, f, result);
result = reduceNode((<CaseClause>node).expression, cbNode, result);
// fall-through
case SyntaxKind.DefaultClause:
result = reduceLeft((<CaseClause | DefaultClause>node).statements, f, result);
result = reduceNodes((<CaseClause | DefaultClause>node).statements, cbNodes, result);
break;
case SyntaxKind.HeritageClause:
result = reduceLeft((<HeritageClause>node).types, f, result);
result = reduceNodes((<HeritageClause>node).types, cbNodes, result);
break;
case SyntaxKind.CatchClause:
result = reduceNode((<CatchClause>node).variableDeclaration, f, result);
result = reduceNode((<CatchClause>node).block, f, result);
result = reduceNode((<CatchClause>node).variableDeclaration, cbNode, result);
result = reduceNode((<CatchClause>node).block, cbNode, result);
break;
// Property assignments
case SyntaxKind.PropertyAssignment:
result = reduceNode((<PropertyAssignment>node).name, f, result);
result = reduceNode((<PropertyAssignment>node).initializer, f, result);
result = reduceNode((<PropertyAssignment>node).name, cbNode, result);
result = reduceNode((<PropertyAssignment>node).initializer, cbNode, result);
break;
case SyntaxKind.ShorthandPropertyAssignment:
result = reduceNode((<ShorthandPropertyAssignment>node).name, f, result);
result = reduceNode((<ShorthandPropertyAssignment>node).objectAssignmentInitializer, f, result);
result = reduceNode((<ShorthandPropertyAssignment>node).name, cbNode, result);
result = reduceNode((<ShorthandPropertyAssignment>node).objectAssignmentInitializer, cbNode, result);
break;
case SyntaxKind.SpreadAssignment:
result = reduceNode((node as SpreadAssignment).expression, cbNode, result);
break;
// Top-level nodes
case SyntaxKind.SourceFile:
result = reduceLeft((<SourceFile>node).statements, f, result);
result = reduceNodes((<SourceFile>node).statements, cbNodes, result);
break;
case SyntaxKind.PartiallyEmittedExpression:
result = reduceNode((<PartiallyEmittedExpression>node).expression, f, result);
result = reduceNode((<PartiallyEmittedExpression>node).expression, cbNode, result);
break;
default:
@@ -526,8 +536,8 @@ namespace ts {
const value = (<MapLike<any>>node)[edge.name];
if (value !== undefined) {
result = isArray(value)
? reduceLeft(<NodeArray<Node>>value, f, result)
: f(result, <Node>value);
? reduceNodes(<NodeArray<Node>>value, cbNodes, result)
: cbNode(result, <Node>value);
}
}
}
@@ -549,10 +559,11 @@ namespace ts {
export function visitNode<T extends Node>(node: T, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, optional?: boolean, lift?: (node: NodeArray<Node>) => T): T;
export function visitNode<T extends Node>(node: T, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, optional: boolean, lift: (node: NodeArray<Node>) => T, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node): T;
export function visitNode(node: Node, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, optional?: boolean, lift?: (node: Node[]) => Node, parenthesize?: (node: Node, parentNode: Node) => Node, parentNode?: Node): Node {
if (node === undefined) {
return undefined;
if (node === undefined || visitor === undefined) {
return node;
}
aggregateTransformFlags(node);
const visited = visitor(node);
if (visited === node) {
return node;
@@ -621,6 +632,7 @@ namespace ts {
// Visit each original node.
for (let i = 0; i < count; i++) {
const node = nodes[i + start];
aggregateTransformFlags(node);
const visited = node !== undefined ? visitor(node) : undefined;
if (updated !== undefined || visited === undefined || visited !== node) {
if (updated === undefined) {
@@ -653,6 +665,53 @@ namespace ts {
return updated || nodes;
}
/**
* Starts a new lexical environment and visits a statement list, ending the lexical environment
* and merging hoisted declarations upon completion.
*/
export function visitLexicalEnvironment(statements: NodeArray<Statement>, visitor: (node: Node) => VisitResult<Node>, context: TransformationContext, start?: number, ensureUseStrict?: boolean) {
context.startLexicalEnvironment();
statements = visitNodes(statements, visitor, isStatement, start);
if (ensureUseStrict && !startsWithUseStrict(statements)) {
statements = createNodeArray([createStatement(createLiteral("use strict")), ...statements], statements);
}
const declarations = context.endLexicalEnvironment();
return createNodeArray(concatenate(statements, declarations), statements);
}
/**
* Starts a new lexical environment and visits a parameter list, suspending the lexical
* environment upon completion.
*/
export function visitParameterList(nodes: NodeArray<ParameterDeclaration>, visitor: (node: Node) => VisitResult<Node>, context: TransformationContext) {
context.startLexicalEnvironment();
const updated = visitNodes(nodes, visitor, isParameterDeclaration);
context.suspendLexicalEnvironment();
return updated;
}
/**
* Resumes a suspended lexical environment and visits a function body, ending the lexical
* environment and merging hoisted declarations upon completion.
*/
export function visitFunctionBody(node: FunctionBody, visitor: (node: Node) => VisitResult<Node>, context: TransformationContext): FunctionBody;
/**
* Resumes a suspended lexical environment and visits a concise body, ending the lexical
* environment and merging hoisted declarations upon completion.
*/
export function visitFunctionBody(node: ConciseBody, visitor: (node: Node) => VisitResult<Node>, context: TransformationContext): ConciseBody;
export function visitFunctionBody(node: ConciseBody, visitor: (node: Node) => VisitResult<Node>, context: TransformationContext): ConciseBody {
context.resumeLexicalEnvironment();
const updated = visitNode(node, visitor, isConciseBody);
const declarations = context.endLexicalEnvironment();
if (some(declarations)) {
const block = convertToFunctionBody(updated);
const statements = mergeLexicalEnvironment(block.statements, declarations);
return updateBlock(block, statements);
}
return updated;
}
/**
* Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place.
*
@@ -660,8 +719,8 @@ namespace ts {
* @param visitor The callback used to visit each child.
* @param context A lexical environment context for the visitor.
*/
export function visitEachChild<T extends Node>(node: T, visitor: (node: Node) => VisitResult<Node>, context: LexicalEnvironment): T;
export function visitEachChild(node: Node, visitor: (node: Node) => VisitResult<Node>, context: LexicalEnvironment): Node {
export function visitEachChild<T extends Node>(node: T, visitor: (node: Node) => VisitResult<Node>, context: TransformationContext): T;
export function visitEachChild(node: Node, visitor: (node: Node) => VisitResult<Node>, context: TransformationContext): Node {
if (node === undefined) {
return undefined;
}
@@ -695,6 +754,7 @@ namespace ts {
return updateParameter(<ParameterDeclaration>node,
visitNodes((<ParameterDeclaration>node).decorators, visitor, isDecorator),
visitNodes((<ParameterDeclaration>node).modifiers, visitor, isModifier),
(<ParameterDeclaration>node).dotDotDotToken,
visitNode((<ParameterDeclaration>node).name, visitor, isBindingName),
visitNode((<ParameterDeclaration>node).type, visitor, isTypeNode, /*optional*/ true),
visitNode((<ParameterDeclaration>node).initializer, visitor, isExpression, /*optional*/ true));
@@ -714,41 +774,33 @@ namespace ts {
visitNodes((<MethodDeclaration>node).modifiers, visitor, isModifier),
visitNode((<MethodDeclaration>node).name, visitor, isPropertyName),
visitNodes((<MethodDeclaration>node).typeParameters, visitor, isTypeParameter),
(context.startLexicalEnvironment(), visitNodes((<MethodDeclaration>node).parameters, visitor, isParameter)),
visitParameterList((<MethodDeclaration>node).parameters, visitor, context),
visitNode((<MethodDeclaration>node).type, visitor, isTypeNode, /*optional*/ true),
mergeFunctionBodyLexicalEnvironment(
visitNode((<MethodDeclaration>node).body, visitor, isFunctionBody, /*optional*/ true),
context.endLexicalEnvironment()));
visitFunctionBody((<MethodDeclaration>node).body, visitor, context));
case SyntaxKind.Constructor:
return updateConstructor(<ConstructorDeclaration>node,
visitNodes((<ConstructorDeclaration>node).decorators, visitor, isDecorator),
visitNodes((<ConstructorDeclaration>node).modifiers, visitor, isModifier),
(context.startLexicalEnvironment(), visitNodes((<ConstructorDeclaration>node).parameters, visitor, isParameter)),
mergeFunctionBodyLexicalEnvironment(
visitNode((<ConstructorDeclaration>node).body, visitor, isFunctionBody, /*optional*/ true),
context.endLexicalEnvironment()));
visitParameterList((<ConstructorDeclaration>node).parameters, visitor, context),
visitFunctionBody((<ConstructorDeclaration>node).body, visitor, context));
case SyntaxKind.GetAccessor:
return updateGetAccessor(<GetAccessorDeclaration>node,
visitNodes((<GetAccessorDeclaration>node).decorators, visitor, isDecorator),
visitNodes((<GetAccessorDeclaration>node).modifiers, visitor, isModifier),
visitNode((<GetAccessorDeclaration>node).name, visitor, isPropertyName),
(context.startLexicalEnvironment(), visitNodes((<GetAccessorDeclaration>node).parameters, visitor, isParameter)),
visitParameterList((<GetAccessorDeclaration>node).parameters, visitor, context),
visitNode((<GetAccessorDeclaration>node).type, visitor, isTypeNode, /*optional*/ true),
mergeFunctionBodyLexicalEnvironment(
visitNode((<GetAccessorDeclaration>node).body, visitor, isFunctionBody, /*optional*/ true),
context.endLexicalEnvironment()));
visitFunctionBody((<GetAccessorDeclaration>node).body, visitor, context));
case SyntaxKind.SetAccessor:
return updateSetAccessor(<SetAccessorDeclaration>node,
visitNodes((<SetAccessorDeclaration>node).decorators, visitor, isDecorator),
visitNodes((<SetAccessorDeclaration>node).modifiers, visitor, isModifier),
visitNode((<SetAccessorDeclaration>node).name, visitor, isPropertyName),
(context.startLexicalEnvironment(), visitNodes((<SetAccessorDeclaration>node).parameters, visitor, isParameter)),
mergeFunctionBodyLexicalEnvironment(
visitNode((<SetAccessorDeclaration>node).body, visitor, isFunctionBody, /*optional*/ true),
context.endLexicalEnvironment()));
visitParameterList((<SetAccessorDeclaration>node).parameters, visitor, context),
visitFunctionBody((<SetAccessorDeclaration>node).body, visitor, context));
// Binding patterns
case SyntaxKind.ObjectBindingPattern:
@@ -761,6 +813,7 @@ namespace ts {
case SyntaxKind.BindingElement:
return updateBindingElement(<BindingElement>node,
(<BindingElement>node).dotDotDotToken,
visitNode((<BindingElement>node).propertyName, visitor, isPropertyName, /*optional*/ true),
visitNode((<BindingElement>node).name, visitor, isBindingName),
visitNode((<BindingElement>node).initializer, visitor, isExpression, /*optional*/ true));
@@ -810,21 +863,17 @@ namespace ts {
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)),
visitParameterList((<FunctionExpression>node).parameters, visitor, context),
visitNode((<FunctionExpression>node).type, visitor, isTypeNode, /*optional*/ true),
mergeFunctionBodyLexicalEnvironment(
visitNode((<FunctionExpression>node).body, visitor, isFunctionBody, /*optional*/ true),
context.endLexicalEnvironment()));
visitFunctionBody((<FunctionExpression>node).body, visitor, context));
case SyntaxKind.ArrowFunction:
return updateArrowFunction(<ArrowFunction>node,
visitNodes((<ArrowFunction>node).modifiers, visitor, isModifier),
visitNodes((<ArrowFunction>node).typeParameters, visitor, isTypeParameter),
(context.startLexicalEnvironment(), visitNodes((<ArrowFunction>node).parameters, visitor, isParameter)),
visitParameterList((<ArrowFunction>node).parameters, visitor, context),
visitNode((<ArrowFunction>node).type, visitor, isTypeNode, /*optional*/ true),
mergeFunctionBodyLexicalEnvironment(
visitNode((<ArrowFunction>node).body, visitor, isConciseBody, /*optional*/ true),
context.endLexicalEnvironment()));
visitFunctionBody((<ArrowFunction>node).body, visitor, context));
case SyntaxKind.DeleteExpression:
return updateDelete(<DeleteExpression>node,
@@ -870,9 +919,9 @@ namespace ts {
return updateYield(<YieldExpression>node,
visitNode((<YieldExpression>node).expression, visitor, isExpression));
case SyntaxKind.SpreadElementExpression:
return updateSpread(<SpreadElementExpression>node,
visitNode((<SpreadElementExpression>node).expression, visitor, isExpression));
case SyntaxKind.SpreadElement:
return updateSpread(<SpreadElement>node,
visitNode((<SpreadElement>node).expression, visitor, isExpression));
case SyntaxKind.ClassExpression:
return updateClassExpression(<ClassExpression>node,
@@ -995,11 +1044,9 @@ namespace ts {
visitNodes((<FunctionDeclaration>node).modifiers, visitor, isModifier),
visitNode((<FunctionDeclaration>node).name, visitor, isPropertyName),
visitNodes((<FunctionDeclaration>node).typeParameters, visitor, isTypeParameter),
(context.startLexicalEnvironment(), visitNodes((<FunctionDeclaration>node).parameters, visitor, isParameter)),
visitParameterList((<FunctionDeclaration>node).parameters, visitor, context),
visitNode((<FunctionDeclaration>node).type, visitor, isTypeNode, /*optional*/ true),
mergeFunctionBodyLexicalEnvironment(
visitNode((<FunctionDeclaration>node).body, visitor, isFunctionBody, /*optional*/ true),
context.endLexicalEnvironment()));
visitFunctionBody((<FunctionExpression>node).body, visitor, context));
case SyntaxKind.ClassDeclaration:
return updateClassDeclaration(<ClassDeclaration>node,
@@ -1125,15 +1172,14 @@ namespace ts {
visitNode((<ShorthandPropertyAssignment>node).name, visitor, isIdentifier),
visitNode((<ShorthandPropertyAssignment>node).objectAssignmentInitializer, visitor, isExpression));
// Top-level nodes
case SyntaxKind.SpreadAssignment:
return updateSpreadAssignment(node as SpreadAssignment,
visitNode((node as SpreadAssignment).expression, visitor, isExpression));
// Top-level nodes
case SyntaxKind.SourceFile:
context.startLexicalEnvironment();
return updateSourceFileNode(<SourceFile>node,
createNodeArray(
concatenate(
visitNodes((<SourceFile>node).statements, visitor, isStatement),
context.endLexicalEnvironment()),
(<SourceFile>node).statements));
visitLexicalEnvironment((<SourceFile>node).statements, visitor, context));
// Transformation nodes
case SyntaxKind.PartiallyEmittedExpression:
@@ -1167,6 +1213,24 @@ namespace ts {
// return node;
}
/**
* Merges generated lexical declarations into a new statement list.
*/
export function mergeLexicalEnvironment(statements: NodeArray<Statement>, declarations: Statement[]): NodeArray<Statement>;
/**
* Appends generated lexical declarations to an array of statements.
*/
export function mergeLexicalEnvironment(statements: Statement[], declarations: Statement[]): Statement[];
export function mergeLexicalEnvironment(statements: Statement[], declarations: Statement[]) {
if (!some(declarations)) {
return statements;
}
return isNodeArray(statements)
? createNodeArray(concatenate(statements, declarations), statements)
: addRange(statements, declarations);
}
/**
* Merges generated lexical declarations into the FunctionBody of a non-arrow function-like declaration.
*
@@ -1237,13 +1301,25 @@ namespace ts {
if (node === undefined) {
return TransformFlags.None;
}
else if (node.transformFlags & TransformFlags.HasComputedFlags) {
if (node.transformFlags & TransformFlags.HasComputedFlags) {
return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
}
else {
const subtreeFlags = aggregateTransformFlagsForSubtree(node);
return computeTransformFlagsForNode(node, subtreeFlags);
const subtreeFlags = aggregateTransformFlagsForSubtree(node);
return computeTransformFlagsForNode(node, subtreeFlags);
}
function aggregateTransformFlagsForNodeArray(nodes: NodeArray<Node>): TransformFlags {
if (nodes === undefined) {
return TransformFlags.None;
}
let subtreeFlags = TransformFlags.None;
let nodeArrayFlags = TransformFlags.None;
for (const node of nodes) {
subtreeFlags |= aggregateTransformFlagsForNode(node);
nodeArrayFlags |= node.transformFlags & ~TransformFlags.HasComputedFlags;
}
nodes.transformFlags = nodeArrayFlags | TransformFlags.HasComputedFlags;
return subtreeFlags;
}
/**
@@ -1257,75 +1333,19 @@ namespace ts {
}
// Aggregate the transform flags of each child.
return reduceEachChild(node, aggregateTransformFlagsForChildNode, TransformFlags.None);
return reduceEachChild(node, TransformFlags.None, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes);
}
/**
* Aggregates the TransformFlags of a child node with the TransformFlags of its
* siblings.
*/
function aggregateTransformFlagsForChildNode(transformFlags: TransformFlags, child: Node): TransformFlags {
return transformFlags | aggregateTransformFlagsForNode(child);
function aggregateTransformFlagsForChildNode(transformFlags: TransformFlags, node: Node): TransformFlags {
return transformFlags | aggregateTransformFlagsForNode(node);
}
/**
* Gets the transform flags to exclude when unioning the transform flags of a subtree.
*
* NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`.
* For performance reasons, `computeTransformFlagsForNode` uses local constant values rather
* than calling this function.
*/
function getTransformFlagsSubtreeExclusions(kind: SyntaxKind) {
if (kind >= SyntaxKind.FirstTypeNode && kind <= SyntaxKind.LastTypeNode) {
return TransformFlags.TypeExcludes;
}
switch (kind) {
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.ArrayLiteralExpression:
return TransformFlags.ArrayLiteralOrCallOrNewExcludes;
case SyntaxKind.ModuleDeclaration:
return TransformFlags.ModuleExcludes;
case SyntaxKind.Parameter:
return TransformFlags.ParameterExcludes;
case SyntaxKind.ArrowFunction:
return TransformFlags.ArrowFunctionExcludes;
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
return TransformFlags.FunctionExcludes;
case SyntaxKind.VariableDeclarationList:
return TransformFlags.VariableDeclarationListExcludes;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
return TransformFlags.ClassExcludes;
case SyntaxKind.Constructor:
return TransformFlags.ConstructorExcludes;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return TransformFlags.MethodOrAccessorExcludes;
case SyntaxKind.AnyKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.NeverKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.TypeParameter:
case SyntaxKind.PropertySignature:
case SyntaxKind.MethodSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
return TransformFlags.TypeExcludes;
case SyntaxKind.ObjectLiteralExpression:
return TransformFlags.ObjectLiteralExcludes;
default:
return TransformFlags.NodeExcludes;
}
function aggregateTransformFlagsForChildNodes(transformFlags: TransformFlags, nodes: NodeArray<Node>): TransformFlags {
return transformFlags | aggregateTransformFlagsForNodeArray(nodes);
}
export namespace Debug {
@@ -1337,6 +1357,13 @@ namespace ts {
? (node: Node, message?: string) => assert(false, message || "Unexpected node.", () => `Node ${formatSyntaxKind(node.kind)} was unexpected.`)
: noop;
export const assertEachNode = shouldAssert(AssertionLevel.Normal)
? (nodes: Node[], test: (node: Node) => boolean, message?: string) => assert(
test === undefined || every(nodes, test),
message || "Unexpected node.",
() => `Node array did not pass test '${getFunctionName(test)}'.`)
: noop;
export const assertNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, test: (node: Node) => boolean, message?: string) => assert(
test === undefined || test(node),
@@ -1344,6 +1371,27 @@ namespace ts {
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`)
: noop;
export const assertOptionalNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, test: (node: Node) => boolean, message?: string) => assert(
test === undefined || node === undefined || test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`)
: noop;
export const assertOptionalToken = shouldAssert(AssertionLevel.Normal)
? (node: Node, kind: SyntaxKind, message?: string) => assert(
kind === undefined || node === undefined || node.kind === kind,
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} was not a '${formatSyntaxKind(kind)}' token.`)
: noop;
export const assertMissingNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, message?: string) => assert(
node === undefined,
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} was unexpected'.`)
: noop;
function getFunctionName(func: Function) {
if (typeof func !== "function") {
return "";
+1 -1
View File
@@ -170,7 +170,7 @@ class CompilerBaselineRunner extends RunnerBase {
});
it("Correct Sourcemap output for " + fileName, () => {
Harness.Compiler.doSourcemapBaseline(justName, options, result);
Harness.Compiler.doSourcemapBaseline(justName, options, result, harnessSettings);
});
it("Correct type/symbol baselines for " + fileName, () => {
+60 -5
View File
@@ -1026,7 +1026,7 @@ namespace FourSlash {
ts.displayPartsToString(help.suffixDisplayParts), expected);
}
public verifyCurrentParameterIsletiable(isVariable: boolean) {
public verifyCurrentParameterIsVariable(isVariable: boolean) {
const signature = this.getActiveSignatureHelpItem();
assert.isOk(signature);
assert.equal(isVariable, signature.isVariadic);
@@ -1053,6 +1053,10 @@ namespace FourSlash {
assert.equal(this.getActiveSignatureHelpItem().parameters.length, expectedCount);
}
public verifyCurrentSignatureHelpIsVariadic(expected: boolean) {
assert.equal(this.getActiveSignatureHelpItem().isVariadic, expected);
}
public verifyCurrentSignatureHelpDocComment(docComment: string) {
const actualDocComment = this.getActiveSignatureHelpItem().documentation;
assert.equal(ts.displayPartsToString(actualDocComment), docComment, this.assertionMessageAtLastKnownMarker("current signature help doc comment"));
@@ -1253,7 +1257,18 @@ namespace FourSlash {
resultString += "Diagnostics:" + Harness.IO.newLine();
const diagnostics = ts.getPreEmitDiagnostics(this.languageService.getProgram());
for (const diagnostic of diagnostics) {
resultString += " " + diagnostic.messageText + Harness.IO.newLine();
if (typeof diagnostic.messageText !== "string") {
let chainedMessage = <ts.DiagnosticMessageChain>diagnostic.messageText;
let indentation = " ";
while (chainedMessage) {
resultString += indentation + chainedMessage.messageText + Harness.IO.newLine();
chainedMessage = chainedMessage.next;
indentation = indentation + " ";
}
}
else {
resultString += " " + diagnostic.messageText + Harness.IO.newLine();
}
}
}
@@ -1998,13 +2013,13 @@ namespace FourSlash {
this.raiseError("Errors expected.");
}
if (diagnostics.length > 1 && errorCode !== undefined) {
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]);
return this.languageService.getCodeFixesAtPosition(fileName, diagnostic.start, diagnostic.start + diagnostic.length, [diagnostic.code]);
}
public verifyCodeFixAtPosition(expectedText: string, errorCode?: number) {
@@ -2031,6 +2046,34 @@ namespace FourSlash {
}
}
public verifyImportFixAtPosition(expectedTextArray: string[], errorCode?: number) {
const ranges = this.getRanges();
if (ranges.length == 0) {
this.raiseError("At least one range should be specified in the testfile.");
}
const codeFixes = this.getCodeFixes(errorCode);
if (!codeFixes || codeFixes.length == 0) {
this.raiseError("No codefixes returned.");
}
const actualTextArray: string[] = [];
const scriptInfo = this.languageServiceAdapterHost.getScriptInfo(codeFixes[0].changes[0].fileName);
const originalContent = scriptInfo.content;
for (const codeFix of codeFixes) {
this.applyEdits(codeFix.changes[0].fileName, codeFix.changes[0].textChanges, /*isFormattingEdit*/ false);
actualTextArray.push(this.normalizeNewlines(this.rangeText(ranges[0])));
scriptInfo.updateContent(originalContent);
}
const sortedExpectedArray = ts.map(expectedTextArray, str => this.normalizeNewlines(str)).sort();
const sortedActualArray = actualTextArray.sort();
if (!ts.arrayIsEqualTo(sortedExpectedArray, sortedActualArray)) {
this.raiseError(
`Actual text array doesn't match expected text array. \nActual: \n"${sortedActualArray.join("\n\n")}"\n---\nExpected: \n'${sortedExpectedArray.join("\n\n")}'`);
}
}
public verifyDocCommentTemplate(expected?: ts.TextInsertion) {
const name = "verifyDocCommentTemplate";
const actual = this.languageService.getDocCommentTemplateAtPosition(this.activeFile.fileName, this.currentCaretPosition);
@@ -2064,6 +2107,10 @@ namespace FourSlash {
});
}
private normalizeNewlines(str: string) {
return str.replace(/\r?\n/g, "\n");
}
public verifyBraceCompletionAtPosition(negative: boolean, openingBrace: string) {
const openBraceMap = ts.createMap<ts.CharacterCodes>({
@@ -2591,7 +2638,7 @@ ${code}
resetLocalData();
}
currentFileName = basePath + "/" + value;
currentFileName = ts.isRootedDiskPath(value) ? value : basePath + "/" + value;
currentFileOptions[key] = value;
}
else {
@@ -3220,6 +3267,10 @@ namespace FourSlashInterface {
this.state.verifySignatureHelpCount(expected);
}
public signatureHelpCurrentArgumentListIsVariadic(expected: boolean) {
this.state.verifyCurrentSignatureHelpIsVariadic(expected);
}
public signatureHelpArgumentCountIs(expected: number) {
this.state.verifySignatureHelpArgumentCount(expected);
}
@@ -3284,6 +3335,10 @@ namespace FourSlashInterface {
this.state.verifyCodeFixAtPosition(expectedText, errorCode);
}
public importFixAtPosition(expectedTextArray: string[], errorCode?: number): void {
this.state.verifyImportFixAtPosition(expectedTextArray, errorCode);
}
public navigationBar(json: any) {
this.state.verifyNavigationBar(json);
}
+59 -56
View File
@@ -470,19 +470,6 @@ namespace Utils {
}
}
namespace Harness.Path {
export function getFileName(fullPath: string) {
return fullPath.replace(/^.*[\\\/]/, "");
}
export function filePath(fullPath: string) {
fullPath = ts.normalizeSlashes(fullPath);
const components = fullPath.split("/");
const path: string[] = components.slice(0, components.length - 1);
return path.join("/") + "/";
}
}
namespace Harness {
export interface IO {
newLine(): string;
@@ -971,28 +958,38 @@ namespace Harness {
// Local get canonical file name function, that depends on passed in parameter for useCaseSensitiveFileNames
const getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
const realPathMap: ts.FileMap<string> = ts.createFileMap<string>();
const fileMap: ts.FileMap<() => ts.SourceFile> = ts.createFileMap<() => ts.SourceFile>();
/** Maps a symlink name to a realpath. Used only for exposing `realpath`. */
const realPathMap = ts.createFileMap<string>();
/**
* Maps a file name to a source file.
* This will have a different SourceFile for every symlink pointing to that file;
* if the program resolves realpaths then symlink entries will be ignored.
*/
const fileMap = ts.createFileMap<ts.SourceFile>();
for (const file of inputFiles) {
if (file.content !== undefined) {
const fileName = ts.normalizePath(file.unitName);
const path = ts.toPath(file.unitName, currentDirectory, getCanonicalFileName);
if (file.fileOptions && file.fileOptions["symlink"]) {
const link = file.fileOptions["symlink"];
const linkPath = ts.toPath(link, currentDirectory, getCanonicalFileName);
realPathMap.set(linkPath, fileName);
fileMap.set(path, (): ts.SourceFile => { throw new Error("Symlinks should always be resolved to a realpath first"); });
const links = file.fileOptions["symlink"].split(",");
for (const link of links) {
const linkPath = ts.toPath(link, currentDirectory, getCanonicalFileName);
realPathMap.set(linkPath, fileName);
// Create a different SourceFile for every symlink.
const sourceFile = createSourceFileAndAssertInvariants(linkPath, file.content, scriptTarget);
fileMap.set(linkPath, sourceFile);
}
}
const sourceFile = createSourceFileAndAssertInvariants(fileName, file.content, scriptTarget);
fileMap.set(path, () => sourceFile);
fileMap.set(path, sourceFile);
}
}
function getSourceFile(fileName: string) {
fileName = ts.normalizePath(fileName);
const path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
if (fileMap.contains(path)) {
return fileMap.get(path)();
const fromFileMap = fileMap.get(toPath(fileName));
if (fromFileMap) {
return fromFileMap;
}
else if (fileName === fourslashFileName) {
const tsFn = "tests/cases/fourslash/" + fourslashFileName;
@@ -1011,6 +1008,9 @@ namespace Harness {
newLineKind === ts.NewLineKind.LineFeed ? lineFeed :
Harness.IO.newLine();
function toPath(fileName: string): ts.Path {
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
return {
getCurrentDirectory: () => currentDirectory,
@@ -1020,24 +1020,26 @@ namespace Harness {
getCanonicalFileName,
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
getNewLine: () => newLine,
fileExists: fileName => {
const path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
return fileMap.contains(path) || (realPathMap && realPathMap.contains(path));
},
fileExists: fileName => fileMap.contains(toPath(fileName)),
readFile: (fileName: string): string => {
return fileMap.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName))().getText();
const file = fileMap.get(toPath(fileName));
if (ts.endsWith(fileName, "json")) {
// strip comments
return file.getText();
}
return file.text;
},
realpath: (fileName: string): ts.Path => {
const path = toPath(fileName);
return (realPathMap.get(path) as ts.Path) || path;
},
realpath: realPathMap && ((f: string) => {
const path = ts.toPath(f, currentDirectory, getCanonicalFileName);
return realPathMap.get(path) || path;
}),
directoryExists: dir => {
let path = ts.toPath(dir, currentDirectory, getCanonicalFileName);
// Strip trailing /, which may exist if the path is a drive root
if (path[path.length - 1] === "/") {
path = <ts.Path>path.substr(0, path.length - 1);
}
return mapHasFileInDirectory(path, fileMap) || mapHasFileInDirectory(path, realPathMap);
return mapHasFileInDirectory(path, fileMap);
},
getDirectories: d => {
const path = ts.toPath(d, currentDirectory, getCanonicalFileName);
@@ -1090,7 +1092,9 @@ namespace Harness {
{ name: "suppressOutputPathCheck", type: "boolean" },
{ name: "noImplicitReferences", type: "boolean" },
{ name: "currentDirectory", type: "string" },
{ name: "symlink", type: "string" }
{ name: "symlink", type: "string" },
// Emitted js baseline will print full paths for every output file
{ name: "fullEmitPaths", type: "boolean" }
];
let optionsIndex: ts.Map<ts.CommandLineOption>;
@@ -1483,7 +1487,7 @@ namespace Harness {
}
if (typesError && symbolsError) {
throw new Error(typesError.message + ts.sys.newLine + symbolsError.message);
throw new Error(typesError.message + Harness.IO.newLine() + symbolsError.message);
}
if (typesError) {
@@ -1565,7 +1569,7 @@ namespace Harness {
return file.writeByteOrderMark ? "\u00EF\u00BB\u00BF" : "";
}
export function doSourcemapBaseline(baselinePath: string, options: ts.CompilerOptions, result: CompilerResult) {
export function doSourcemapBaseline(baselinePath: string, options: ts.CompilerOptions, result: CompilerResult, harnessSettings: Harness.TestCaseParser.CompilerSettings) {
if (options.inlineSourceMap) {
if (result.sourceMaps.length > 0) {
throw new Error("No sourcemap files should be generated if inlineSourceMaps was set.");
@@ -1587,10 +1591,8 @@ namespace Harness {
}
let sourceMapCode = "";
for (let i = 0; i < result.sourceMaps.length; i++) {
sourceMapCode += "//// [" + Harness.Path.getFileName(result.sourceMaps[i].fileName) + "]\r\n";
sourceMapCode += getByteOrderMarkText(result.sourceMaps[i]);
sourceMapCode += result.sourceMaps[i].code;
for (const sourceMap of result.sourceMaps) {
sourceMapCode += fileOutput(sourceMap, harnessSettings);
}
return sourceMapCode;
@@ -1611,23 +1613,19 @@ namespace Harness {
tsCode += "//// [" + header + "] ////\r\n\r\n";
}
for (let i = 0; i < tsSources.length; i++) {
tsCode += "//// [" + Harness.Path.getFileName(tsSources[i].unitName) + "]\r\n";
tsCode += "//// [" + ts.getBaseFileName(tsSources[i].unitName) + "]\r\n";
tsCode += tsSources[i].content + (i < (tsSources.length - 1) ? "\r\n" : "");
}
let jsCode = "";
for (let i = 0; i < result.files.length; i++) {
jsCode += "//// [" + Harness.Path.getFileName(result.files[i].fileName) + "]\r\n";
jsCode += getByteOrderMarkText(result.files[i]);
jsCode += result.files[i].code;
for (const file of result.files) {
jsCode += fileOutput(file, harnessSettings);
}
if (result.declFilesCode.length > 0) {
jsCode += "\r\n\r\n";
for (let i = 0; i < result.declFilesCode.length; i++) {
jsCode += "//// [" + Harness.Path.getFileName(result.declFilesCode[i].fileName) + "]\r\n";
jsCode += getByteOrderMarkText(result.declFilesCode[i]);
jsCode += result.declFilesCode[i].code;
for (const declFile of result.declFilesCode) {
jsCode += fileOutput(declFile, harnessSettings);
}
}
@@ -1652,6 +1650,11 @@ namespace Harness {
});
}
function fileOutput(file: GeneratedFile, harnessSettings: Harness.TestCaseParser.CompilerSettings): string {
const fileName = harnessSettings["fullEmitPaths"] ? file.fileName : ts.getBaseFileName(file.fileName);
return "//// [" + fileName + "]\r\n" + getByteOrderMarkText(file) + file.code;
}
export function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[]): string {
// Collect, test, and sort the fileNames
outputFiles.sort((a, b) => ts.compareStrings(cleanName(a.fileName), cleanName(b.fileName)));
@@ -1768,7 +1771,7 @@ namespace Harness {
}
// Regex for parsing options in the format "@Alpha: Value of any sort"
const optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*(\S*)/gm; // multiple matches on multiple lines
const optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*([^\r\n]*)/gm; // multiple matches on multiple lines
function extractCompilerSettings(content: string): CompilerSettings {
const opts: CompilerSettings = {};
@@ -1777,7 +1780,7 @@ namespace Harness {
/* tslint:disable:no-null-keyword */
while ((match = optionRegex.exec(content)) !== null) {
/* tslint:enable:no-null-keyword */
opts[match[1]] = match[2];
opts[match[1]] = match[2].trim();
}
return opts;
@@ -1805,7 +1808,7 @@ namespace Harness {
// Comment line, check for global/file @options and record them
optionRegex.lastIndex = 0;
const metaDataName = testMetaData[1].toLowerCase();
currentFileOptions[testMetaData[1]] = testMetaData[2];
currentFileOptions[testMetaData[1]] = testMetaData[2].trim();
if (metaDataName !== "filename") {
continue;
}
@@ -1825,12 +1828,12 @@ namespace Harness {
// Reset local data
currentFileContent = undefined;
currentFileOptions = {};
currentFileName = testMetaData[2];
currentFileName = testMetaData[2].trim();
refs = [];
}
else {
// First metadata marker in the file
currentFileName = testMetaData[2];
currentFileName = testMetaData[2].trim();
}
}
else {
@@ -1848,7 +1851,7 @@ namespace Harness {
}
// normalize the fileName for the single file case
currentFileName = testUnitData.length > 0 || currentFileName ? currentFileName : Path.getFileName(fileName);
currentFileName = testUnitData.length > 0 || currentFileName ? currentFileName : ts.getBaseFileName(fileName);
// EOF, push whatever remains
const newTestFile2 = {
@@ -2012,7 +2015,7 @@ namespace Harness {
export function isDefaultLibraryFile(filePath: string): boolean {
// We need to make sure that the filePath is prefixed with "lib." not just containing "lib." and end with ".d.ts"
const fileName = Path.getFileName(filePath);
const fileName = ts.getBaseFileName(ts.normalizeSlashes(filePath));
return ts.startsWith(fileName, "lib.") && ts.endsWith(fileName, ".d.ts");
}
+4
View File
@@ -720,6 +720,10 @@ namespace Harness.LanguageService {
clearImmediate(timeoutId: any): void {
clearImmediate(timeoutId);
}
createHash(s: string) {
return s;
}
}
export class ServerLanguageServiceAdapter implements LanguageServiceAdapter {
+4
View File
@@ -61,6 +61,10 @@ function createRunner(kind: TestRunnerKind): RunnerBase {
}
}
if (Harness.IO.tryEnableSourceMapsForHost && /^development$/i.test(Harness.IO.getEnvironmentVariable("NODE_ENV"))) {
Harness.IO.tryEnableSourceMapsForHost();
}
// users can define tests to run in mytest.config that will override cmd line args, otherwise use cmd line args (test.config), otherwise no options
const mytestconfigFileName = "mytest.config";
+1 -1
View File
@@ -32,7 +32,7 @@ abstract class RunnerBase {
/** Replaces instances of full paths with fileNames only */
static removeFullPaths(path: string) {
// If its a full path (starts with "C:" or "/") replace with just the filename
let fixedPath = /^(\w:|\/)/.test(path) ? Harness.Path.getFileName(path) : path;
let fixedPath = /^(\w:|\/)/.test(path) ? ts.getBaseFileName(path) : path;
// when running in the browser the 'full path' is the host name, shows up in error baselines
const localHost = /http:\/localhost:\d+/g;
+1 -1
View File
@@ -199,7 +199,7 @@ namespace RWC {
}
// Do not include the library in the baselines to avoid noise
const baselineFiles = inputFiles.concat(otherFiles).filter(f => !Harness.isDefaultLibraryFile(f.unitName));
const errors = compilerResult.errors.filter(e => !Harness.isDefaultLibraryFile(e.file.fileName));
const errors = compilerResult.errors.filter(e => e.file && !Harness.isDefaultLibraryFile(e.file.fileName));
return Harness.Compiler.getErrorBaseline(baselineFiles, errors);
}, baselineOpts);
});
+2 -1
View File
@@ -29,6 +29,7 @@
"../compiler/visitor.ts",
"../compiler/transformers/ts.ts",
"../compiler/transformers/jsx.ts",
"../compiler/transformers/esnext.ts",
"../compiler/transformers/es2017.ts",
"../compiler/transformers/es2016.ts",
"../compiler/transformers/es2015.ts",
@@ -107,7 +108,7 @@
"./unittests/commandLineParsing.ts",
"./unittests/configurationExtension.ts",
"./unittests/convertCompilerOptionsFromJson.ts",
"./unittests/convertTypingOptionsFromJson.ts",
"./unittests/convertTypeAcquisitionFromJson.ts",
"./unittests/tsserverProjectSystem.ts",
"./unittests/matchFiles.ts",
"./unittests/initializeTSConfig.ts",
@@ -43,7 +43,8 @@ namespace ts {
setTimeout,
clearTimeout,
setImmediate: typeof setImmediate !== "undefined" ? setImmediate : action => setTimeout(action, 0),
clearImmediate: typeof clearImmediate !== "undefined" ? clearImmediate : clearTimeout
clearImmediate: typeof clearImmediate !== "undefined" ? clearImmediate : clearTimeout,
createHash: s => s
};
}
+4 -4
View File
@@ -60,7 +60,7 @@ namespace ts {
assertParseResult(["--lib", "es5,invalidOption", "0.ts"],
{
errors: [{
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'",
category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
@@ -165,7 +165,7 @@ namespace ts {
start: undefined,
length: undefined,
}, {
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017'",
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'esnext'",
category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
@@ -263,7 +263,7 @@ namespace ts {
assertParseResult(["--lib", "es5,", "es7", "0.ts"],
{
errors: [{
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'",
category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
@@ -283,7 +283,7 @@ namespace ts {
assertParseResult(["--lib", "es5, ", "es7", "0.ts"],
{
errors: [{
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'",
category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
+40
View File
@@ -492,5 +492,45 @@ namespace ts.projectSystem {
assert.isTrue(host.fileExists(expectedEmittedFileName));
assert.equal(host.readFile(expectedEmittedFileName), `"use strict";\r\nfunction Foo() { return 10; }\r\nexports.Foo = Foo;\r\n`);
});
it("shoud not emit js files in external projects", () => {
const file1 = {
path: "/a/b/file1.ts",
content: "consonle.log('file1');"
};
// file2 has errors. The emitting should not be blocked.
const file2 = {
path: "/a/b/file2.js",
content: "console.log'file2');"
};
const file3 = {
path: "/a/b/file3.js",
content: "console.log('file3');"
};
const externalProjectName = "externalproject";
const host = createServerHost([file1, file2, file3, libFile]);
const session = createSession(host);
const projectService = session.getProjectService();
projectService.openExternalProject({
rootFiles: toExternalFiles([file1.path, file2.path]),
options: {
allowJs: true,
outFile: "dist.js",
compileOnSave: true
},
projectFileName: externalProjectName
});
const emitRequest = makeSessionRequest<server.protocol.CompileOnSaveEmitFileRequestArgs>(CommandNames.CompileOnSaveEmitFile, { file: file1.path });
session.executeCommand(emitRequest);
const expectedOutFileName = "/a/b/dist.js";
assert.isTrue(host.fileExists(expectedOutFileName));
const outFileContent = host.readFile(expectedOutFileName);
assert.isTrue(outFileContent.indexOf(file1.content) !== -1);
assert.isTrue(outFileContent.indexOf(file2.content) === -1);
assert.isTrue(outFileContent.indexOf(file3.content) === -1);
});
});
}
@@ -179,7 +179,7 @@ namespace ts {
testFailure("can error when 'extends' is neither relative nor rooted.", "extends2.json", [{
code: 18001,
category: DiagnosticCategory.Error,
messageText: `The path in an 'extends' options must be relative or rooted.`
messageText: `A path in an 'extends' option must be relative or rooted, but 'configs/base' is not.`
}]);
});
});
@@ -176,7 +176,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017'",
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'esnext'",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -233,7 +233,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -264,7 +264,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -295,7 +295,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -326,7 +326,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -2,12 +2,13 @@
/// <reference path="..\..\compiler\commandLineParser.ts" />
namespace ts {
describe("convertTypingOptionsFromJson", () => {
function assertTypingOptions(json: any, configFileName: string, expectedResult: { typingOptions: TypingOptions, errors: Diagnostic[] }) {
const { options: actualTypingOptions, errors: actualErrors } = convertTypingOptionsFromJson(json["typingOptions"], "/apath/", configFileName);
const parsedTypingOptions = JSON.stringify(actualTypingOptions);
const expectedTypingOptions = JSON.stringify(expectedResult.typingOptions);
assert.equal(parsedTypingOptions, expectedTypingOptions);
describe("convertTypeAcquisitionFromJson", () => {
function assertTypeAcquisition(json: any, configFileName: string, expectedResult: { typeAcquisition: TypeAcquisition, errors: Diagnostic[] }) {
const jsonOptions = json["typeAcquisition"] || json["typingOptions"];
const { options: actualTypeAcquisition, errors: actualErrors } = convertTypeAcquisitionFromJson(jsonOptions, "/apath/", configFileName);
const parsedTypeAcquisition = JSON.stringify(actualTypeAcquisition);
const expectedTypeAcquisition = JSON.stringify(expectedResult.typeAcquisition);
assert.equal(parsedTypeAcquisition, expectedTypeAcquisition);
const expectedErrors = expectedResult.errors;
assert.isTrue(expectedResult.errors.length === actualErrors.length, `Expected error: ${JSON.stringify(expectedResult.errors)}. Actual error: ${JSON.stringify(actualErrors)}.`);
@@ -20,8 +21,8 @@ namespace ts {
}
// tsconfig.json
it("Convert correctly format tsconfig.json to typing-options ", () => {
assertTypingOptions(
it("Convert deprecated typingOptions.enableAutoDiscovery format tsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typingOptions":
{
@@ -32,9 +33,9 @@ namespace ts {
},
"tsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: true,
enable: true,
include: ["0.d.ts", "1.d.ts"],
exclude: ["0.js", "1.js"]
},
@@ -42,25 +43,47 @@ namespace ts {
});
});
it("Convert incorrect format tsconfig.json to typing-options ", () => {
assertTypingOptions(
it("Convert correctly format tsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typingOptions":
"typeAcquisition":
{
"enable": true,
"include": ["0.d.ts", "1.d.ts"],
"exclude": ["0.js", "1.js"]
}
},
"tsconfig.json",
{
typeAcquisition:
{
enable: true,
include: ["0.d.ts", "1.d.ts"],
exclude: ["0.js", "1.js"]
},
errors: <Diagnostic[]>[]
});
});
it("Convert incorrect format tsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typeAcquisition":
{
"enableAutoDiscovy": true,
}
}, "tsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: false,
enable: false,
include: [],
exclude: []
},
errors: [
{
category: Diagnostics.Unknown_typing_option_0.category,
code: Diagnostics.Unknown_typing_option_0.code,
category: Diagnostics.Unknown_type_acquisition_option_0.category,
code: Diagnostics.Unknown_type_acquisition_option_0.code,
file: undefined,
start: 0,
length: 0,
@@ -70,12 +93,12 @@ namespace ts {
});
});
it("Convert default tsconfig.json to typing-options ", () => {
assertTypingOptions({}, "tsconfig.json",
it("Convert default tsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition({}, "tsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: false,
enable: false,
include: [],
exclude: []
},
@@ -83,18 +106,18 @@ namespace ts {
});
});
it("Convert tsconfig.json with only enableAutoDiscovery property to typing-options ", () => {
assertTypingOptions(
it("Convert tsconfig.json with only enable property to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typingOptions":
"typeAcquisition":
{
"enableAutoDiscovery": true
"enable": true
}
}, "tsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: true,
enable: true,
include: [],
exclude: []
},
@@ -103,20 +126,20 @@ namespace ts {
});
// jsconfig.json
it("Convert jsconfig.json to typing-options ", () => {
assertTypingOptions(
it("Convert jsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typingOptions":
"typeAcquisition":
{
"enableAutoDiscovery": false,
"enable": false,
"include": ["0.d.ts"],
"exclude": ["0.js"]
}
}, "jsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: false,
enable: false,
include: ["0.d.ts"],
exclude: ["0.js"]
},
@@ -124,12 +147,12 @@ namespace ts {
});
});
it("Convert default jsconfig.json to typing-options ", () => {
assertTypingOptions({ }, "jsconfig.json",
it("Convert default jsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition({ }, "jsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: true,
enable: true,
include: [],
exclude: []
},
@@ -137,25 +160,25 @@ namespace ts {
});
});
it("Convert incorrect format jsconfig.json to typing-options ", () => {
assertTypingOptions(
it("Convert incorrect format jsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typingOptions":
"typeAcquisition":
{
"enableAutoDiscovy": true,
}
}, "jsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: true,
enable: true,
include: [],
exclude: []
},
errors: [
{
category: Diagnostics.Unknown_compiler_option_0.category,
code: Diagnostics.Unknown_typing_option_0.code,
code: Diagnostics.Unknown_type_acquisition_option_0.code,
file: undefined,
start: 0,
length: 0,
@@ -165,18 +188,18 @@ namespace ts {
});
});
it("Convert jsconfig.json with only enableAutoDiscovery property to typing-options ", () => {
assertTypingOptions(
it("Convert jsconfig.json with only enable property to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typingOptions":
"typeAcquisition":
{
"enableAutoDiscovery": false
"enable": false
}
}, "jsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: false,
enable: false,
include: [],
exclude: []
},
+17 -7
View File
@@ -44,10 +44,10 @@ namespace ts {
// NOTE: 'reusedElements' is the expected count of elements reused from the old tree to the new
// tree. It may change as we tweak the parser. If the count increases then that should always
// be a good thing. If it decreases, that's not great (less reusability), but that may be
// unavoidable. If it does decrease an investigation should be done to make sure that things
// be a good thing. If it decreases, that's not great (less reusability), but that may be
// unavoidable. If it does decrease an investigation should be done to make sure that things
// are still ok and we're still appropriately reusing most of the tree.
function compareTrees(oldText: IScriptSnapshot, newText: IScriptSnapshot, textChangeRange: TextChangeRange, expectedReusedElements: number, oldTree?: SourceFile): SourceFile {
function compareTrees(oldText: IScriptSnapshot, newText: IScriptSnapshot, textChangeRange: TextChangeRange, expectedReusedElements: number, oldTree?: SourceFile) {
oldTree = oldTree || createTree(oldText, /*version:*/ ".");
Utils.assertInvariants(oldTree, /*parent:*/ undefined);
@@ -76,7 +76,7 @@ namespace ts {
assert.equal(actualReusedCount, expectedReusedElements, actualReusedCount + " !== " + expectedReusedElements);
}
return incrementalNewTree;
return { oldTree, newTree, incrementalNewTree };
}
function reusedElements(oldNode: SourceFile, newNode: SourceFile): number {
@@ -103,7 +103,7 @@ namespace ts {
for (let i = 0; i < repeat; i++) {
const oldText = ScriptSnapshot.fromString(source);
const newTextAndChange = withDelete(oldText, index, 1);
const newTree = compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, -1, oldTree);
const newTree = compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, -1, oldTree).incrementalNewTree;
source = newTextAndChange.text.getText(0, newTextAndChange.text.getLength());
oldTree = newTree;
@@ -116,7 +116,7 @@ namespace ts {
for (let i = 0; i < repeat; i++) {
const oldText = ScriptSnapshot.fromString(source);
const newTextAndChange = withInsert(oldText, index + i, toInsert.charAt(i));
const newTree = compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, -1, oldTree);
const newTree = compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, -1, oldTree).incrementalNewTree;
source = newTextAndChange.text.getText(0, newTextAndChange.text.getLength());
oldTree = newTree;
@@ -639,7 +639,7 @@ module m3 { }\
});
it("Unterminated comment after keyword converted to identifier", () => {
// 'public' as a keyword should be incrementally unusable (because it has an
// 'public' as a keyword should be incrementally unusable (because it has an
// unterminated comment). When we convert it to an identifier, that shouldn't
// change anything, and we should still get the same errors.
const source = "return; a.public /*";
@@ -796,6 +796,16 @@ module m3 { }\
compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 4);
});
it("Reuse transformFlags of subtree during bind", () => {
const source = `class Greeter { constructor(element: HTMLElement) { } }`;
const oldText = ScriptSnapshot.fromString(source);
const newTextAndChange = withChange(oldText, 15, 0, "\n");
const { oldTree, incrementalNewTree } = compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, -1);
bindSourceFile(oldTree, {});
bindSourceFile(incrementalNewTree, {});
assert.equal(oldTree.transformFlags, incrementalNewTree.transformFlags);
});
// Simulated typing tests.
it("Type extends clause 1", () => {
+34 -14
View File
@@ -89,8 +89,6 @@ namespace ts {
"c:/dev/g.min.js/.g/g.ts"
]);
const defaultExcludes = ["node_modules", "bower_components", "jspm_packages"];
function assertParsed(actual: ts.ParsedCommandLine, expected: ts.ParsedCommandLine): void {
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
@@ -98,6 +96,23 @@ namespace ts {
}
describe("matchFiles", () => {
it("with defaults", () => {
const json = {};
const expected: ts.ParsedCommandLine = {
options: {},
errors: [],
fileNames: [
"c:/dev/a.ts",
"c:/dev/b.ts"
],
wildcardDirectories: {
"c:/dev": ts.WatchDirectoryFlags.Recursive
},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath);
assertParsed(actual, expected);
});
describe("with literal file list", () => {
it("without exclusions", () => {
const json = {
@@ -192,7 +207,7 @@ namespace ts {
options: {},
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]")
],
fileNames: [],
wildcardDirectories: {},
@@ -211,7 +226,7 @@ namespace ts {
options: {},
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]")
],
fileNames: [],
wildcardDirectories: {},
@@ -330,7 +345,10 @@ namespace ts {
errors: [],
fileNames: [
"c:/dev/a.ts",
"c:/dev/b.ts"
"c:/dev/b.ts",
"c:/dev/bower_components/a.ts",
"c:/dev/jspm_packages/a.ts",
"c:/dev/node_modules/a.ts"
],
wildcardDirectories: {},
};
@@ -372,8 +390,7 @@ namespace ts {
"node_modules/a.ts",
"bower_components/a.ts",
"jspm_packages/a.ts"
],
exclude: <string[]>[]
]
};
const expected: ts.ParsedCommandLine = {
options: {},
@@ -530,7 +547,7 @@ namespace ts {
options: {},
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]")
],
fileNames: [],
wildcardDirectories: {
@@ -600,7 +617,10 @@ namespace ts {
options: {},
errors: [],
fileNames: [
"c:/dev/a.ts"
"c:/dev/a.ts",
"c:/dev/bower_components/a.ts",
"c:/dev/jspm_packages/a.ts",
"c:/dev/node_modules/a.ts"
],
wildcardDirectories: {
"c:/dev": ts.WatchDirectoryFlags.Recursive
@@ -671,7 +691,7 @@ namespace ts {
},
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]")
],
fileNames: [],
wildcardDirectories: {
@@ -980,7 +1000,7 @@ namespace ts {
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**"),
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]")
],
fileNames: [],
wildcardDirectories: {}
@@ -1022,7 +1042,7 @@ namespace ts {
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, "**/x/**/*"),
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]")
],
fileNames: [],
wildcardDirectories: {}
@@ -1071,7 +1091,7 @@ namespace ts {
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/../*"),
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]")
],
fileNames: [],
wildcardDirectories: {}
@@ -1091,7 +1111,7 @@ namespace ts {
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/../*"),
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]")
],
fileNames: [],
wildcardDirectories: {}
-24
View File
@@ -197,13 +197,9 @@ namespace ts {
"/a/b/c/d/node_modules/foo/index.tsx",
"/a/b/c/d/node_modules/foo/index.d.ts",
"/a/b/c/d/node_modules/@types/foo.ts",
"/a/b/c/d/node_modules/@types/foo.tsx",
"/a/b/c/d/node_modules/@types/foo.d.ts",
"/a/b/c/d/node_modules/@types/foo/package.json",
"/a/b/c/d/node_modules/@types/foo/index.ts",
"/a/b/c/d/node_modules/@types/foo/index.tsx",
"/a/b/c/d/node_modules/@types/foo/index.d.ts",
"/a/b/c/node_modules/foo.ts",
@@ -215,13 +211,9 @@ namespace ts {
"/a/b/c/node_modules/foo/index.tsx",
"/a/b/c/node_modules/foo/index.d.ts",
"/a/b/c/node_modules/@types/foo.ts",
"/a/b/c/node_modules/@types/foo.tsx",
"/a/b/c/node_modules/@types/foo.d.ts",
"/a/b/c/node_modules/@types/foo/package.json",
"/a/b/c/node_modules/@types/foo/index.ts",
"/a/b/c/node_modules/@types/foo/index.tsx",
"/a/b/c/node_modules/@types/foo/index.d.ts",
]);
}
@@ -257,13 +249,9 @@ namespace ts {
"/a/node_modules/b/c/node_modules/d/node_modules/foo/index.tsx",
"/a/node_modules/b/c/node_modules/d/node_modules/foo/index.d.ts",
"/a/node_modules/b/c/node_modules/d/node_modules/@types/foo.ts",
"/a/node_modules/b/c/node_modules/d/node_modules/@types/foo.tsx",
"/a/node_modules/b/c/node_modules/d/node_modules/@types/foo.d.ts",
"/a/node_modules/b/c/node_modules/d/node_modules/@types/foo/package.json",
"/a/node_modules/b/c/node_modules/d/node_modules/@types/foo/index.ts",
"/a/node_modules/b/c/node_modules/d/node_modules/@types/foo/index.tsx",
"/a/node_modules/b/c/node_modules/d/node_modules/@types/foo/index.d.ts",
"/a/node_modules/b/c/node_modules/foo.ts",
@@ -275,13 +263,9 @@ namespace ts {
"/a/node_modules/b/c/node_modules/foo/index.tsx",
"/a/node_modules/b/c/node_modules/foo/index.d.ts",
"/a/node_modules/b/c/node_modules/@types/foo.ts",
"/a/node_modules/b/c/node_modules/@types/foo.tsx",
"/a/node_modules/b/c/node_modules/@types/foo.d.ts",
"/a/node_modules/b/c/node_modules/@types/foo/package.json",
"/a/node_modules/b/c/node_modules/@types/foo/index.ts",
"/a/node_modules/b/c/node_modules/@types/foo/index.tsx",
"/a/node_modules/b/c/node_modules/@types/foo/index.d.ts",
"/a/node_modules/b/node_modules/foo.ts",
@@ -293,13 +277,9 @@ namespace ts {
"/a/node_modules/b/node_modules/foo/index.tsx",
"/a/node_modules/b/node_modules/foo/index.d.ts",
"/a/node_modules/b/node_modules/@types/foo.ts",
"/a/node_modules/b/node_modules/@types/foo.tsx",
"/a/node_modules/b/node_modules/@types/foo.d.ts",
"/a/node_modules/b/node_modules/@types/foo/package.json",
"/a/node_modules/b/node_modules/@types/foo/index.ts",
"/a/node_modules/b/node_modules/@types/foo/index.tsx",
"/a/node_modules/b/node_modules/@types/foo/index.d.ts",
"/a/node_modules/foo.ts",
@@ -709,13 +689,9 @@ import b = require("./moduleB");
"/root/folder1/node_modules/file6/index.tsx",
"/root/folder1/node_modules/file6/index.d.ts",
"/root/folder1/node_modules/@types/file6.ts",
"/root/folder1/node_modules/@types/file6.tsx",
"/root/folder1/node_modules/@types/file6.d.ts",
"/root/folder1/node_modules/@types/file6/package.json",
"/root/folder1/node_modules/@types/file6/index.ts",
"/root/folder1/node_modules/@types/file6/index.tsx",
"/root/folder1/node_modules/@types/file6/index.d.ts",
// success on /root/node_modules/file6.ts
], /*isExternalLibraryImport*/ true);
@@ -394,26 +394,14 @@ namespace ts {
"File '/fs.ts' does not exist.",
"File '/fs.tsx' does not exist.",
"File '/fs.d.ts' does not exist.",
"File '/a/b/node_modules/@types/fs.ts' does not exist.",
"File '/a/b/node_modules/@types/fs.tsx' does not exist.",
"File '/a/b/node_modules/@types/fs.d.ts' does not exist.",
"File '/a/b/node_modules/@types/fs/package.json' does not exist.",
"File '/a/b/node_modules/@types/fs/index.ts' does not exist.",
"File '/a/b/node_modules/@types/fs/index.tsx' does not exist.",
"File '/a/b/node_modules/@types/fs/index.d.ts' does not exist.",
"File '/a/node_modules/@types/fs.ts' does not exist.",
"File '/a/node_modules/@types/fs.tsx' does not exist.",
"File '/a/node_modules/@types/fs.d.ts' does not exist.",
"File '/a/node_modules/@types/fs/package.json' does not exist.",
"File '/a/node_modules/@types/fs/index.ts' does not exist.",
"File '/a/node_modules/@types/fs/index.tsx' does not exist.",
"File '/a/node_modules/@types/fs/index.d.ts' does not exist.",
"File '/node_modules/@types/fs.ts' does not exist.",
"File '/node_modules/@types/fs.tsx' does not exist.",
"File '/node_modules/@types/fs.d.ts' does not exist.",
"File '/node_modules/@types/fs/package.json' does not exist.",
"File '/node_modules/@types/fs/index.ts' does not exist.",
"File '/node_modules/@types/fs/index.tsx' does not exist.",
"File '/node_modules/@types/fs/index.d.ts' does not exist.",
"File '/a/b/fs.js' does not exist.",
"File '/a/b/fs.jsx' does not exist.",
@@ -448,26 +436,14 @@ namespace ts {
"File '/fs.ts' does not exist.",
"File '/fs.tsx' does not exist.",
"File '/fs.d.ts' does not exist.",
"File '/a/b/node_modules/@types/fs.ts' does not exist.",
"File '/a/b/node_modules/@types/fs.tsx' does not exist.",
"File '/a/b/node_modules/@types/fs.d.ts' does not exist.",
"File '/a/b/node_modules/@types/fs/package.json' does not exist.",
"File '/a/b/node_modules/@types/fs/index.ts' does not exist.",
"File '/a/b/node_modules/@types/fs/index.tsx' does not exist.",
"File '/a/b/node_modules/@types/fs/index.d.ts' does not exist.",
"File '/a/node_modules/@types/fs.ts' does not exist.",
"File '/a/node_modules/@types/fs.tsx' does not exist.",
"File '/a/node_modules/@types/fs.d.ts' does not exist.",
"File '/a/node_modules/@types/fs/package.json' does not exist.",
"File '/a/node_modules/@types/fs/index.ts' does not exist.",
"File '/a/node_modules/@types/fs/index.tsx' does not exist.",
"File '/a/node_modules/@types/fs/index.d.ts' does not exist.",
"File '/node_modules/@types/fs.ts' does not exist.",
"File '/node_modules/@types/fs.tsx' does not exist.",
"File '/node_modules/@types/fs.d.ts' does not exist.",
"File '/node_modules/@types/fs/package.json' does not exist.",
"File '/node_modules/@types/fs/index.ts' does not exist.",
"File '/node_modules/@types/fs/index.tsx' does not exist.",
"File '/node_modules/@types/fs/index.d.ts' does not exist.",
"File '/a/b/fs.js' does not exist.",
"File '/a/b/fs.jsx' does not exist.",
+2 -1
View File
@@ -24,7 +24,8 @@ namespace ts.server {
setTimeout() { return 0; },
clearTimeout: noop,
setImmediate: () => 0,
clearImmediate: noop
clearImmediate: noop,
createHash: s => s
};
const nullCancellationToken: HostCancellationToken = { isCancellationRequested: () => false };
const mockLogger: Logger = {
+4
View File
@@ -385,6 +385,10 @@ var x = 0;`, {
options: { compilerOptions: { reactNamespace: "react" }, fileName: "input.js", reportDiagnostics: true }
});
transpilesCorrectly("Supports setting 'jsxFactory'", "x;", {
options: { compilerOptions: { jsxFactory: "createElement" }, fileName: "input.js", reportDiagnostics: true }
});
transpilesCorrectly("Supports setting 'removeComments'", "x;", {
options: { compilerOptions: { removeComments: true }, fileName: "input.js", reportDiagnostics: true }
});
+421 -60
View File
@@ -18,7 +18,6 @@ namespace ts.projectSystem {
};
export interface PostExecAction {
readonly requestKind: TI.RequestKind;
readonly success: boolean;
readonly callback: TI.RequestCompletedAction;
}
@@ -47,9 +46,13 @@ 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, safeList.path, throttleLimit, log);
this.init();
constructor(
readonly globalTypingsCacheLocation: string,
throttleLimit: number,
installTypingHost: server.ServerHost,
readonly typesRegistry = createMap<void>(),
log?: TI.Log) {
super(installTypingHost, globalTypingsCacheLocation, safeList.path, throttleLimit, log);
}
safeFileList = safeList.path;
@@ -63,9 +66,8 @@ namespace ts.projectSystem {
}
}
checkPendingCommands(expected: TI.RequestKind[]) {
assert.equal(this.postExecActions.length, expected.length, `Expected ${expected.length} post install actions`);
this.postExecActions.forEach((act, i) => assert.equal(act.requestKind, expected[i], "Unexpected post install action"));
checkPendingCommands(expectedCount: number) {
assert.equal(this.postExecActions.length, expectedCount, `Expected ${expectedCount} post install actions`);
}
onProjectClosed() {
@@ -79,32 +81,24 @@ namespace ts.projectSystem {
return this.installTypingHost;
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
switch (requestKind) {
case TI.NpmViewRequest:
case TI.NpmInstallRequest:
break;
default:
assert.isTrue(false, `request ${requestKind} is not supported`);
}
this.addPostExecAction(requestKind, "success", cb);
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
this.addPostExecAction("success", cb);
}
sendResponse(response: server.SetTypings | server.InvalidateCachedTypings) {
this.projectService.updateTypingsForProject(response);
}
enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions, unresolvedImports: server.SortedReadonlyArray<string>) {
const request = server.createInstallTypingsRequest(project, typingOptions, unresolvedImports, this.globalTypingsCacheLocation);
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray<string>) {
const request = server.createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, this.globalTypingsCacheLocation);
this.install(request);
}
addPostExecAction(requestKind: TI.RequestKind, stdout: string | string[], cb: TI.RequestCompletedAction) {
addPostExecAction(stdout: string | string[], cb: TI.RequestCompletedAction) {
const out = typeof stdout === "string" ? stdout : createNpmPackageJsonString(stdout);
const action: PostExecAction = {
success: !!out,
callback: cb,
requestKind
callback: cb
};
this.postExecActions.push(action);
}
@@ -159,7 +153,6 @@ namespace ts.projectSystem {
params.executingFilePath || getExecutingFilePathFromLibFile(),
params.currentDirectory || "/",
fileOrFolderList);
host.createFileOrFolder(safeList, /*createParentDirectory*/ true);
return host;
}
@@ -360,7 +353,8 @@ namespace ts.projectSystem {
reloadFS(filesOrFolders: FileOrFolder[]) {
this.filesOrFolders = filesOrFolders;
this.fs = createFileMap<FSEntry>();
for (const fileOrFolder of filesOrFolders) {
// always inject safelist file in the list of files
for (const fileOrFolder of filesOrFolders.concat(safeList)) {
const path = this.toPath(fileOrFolder.path);
const fullPath = getNormalizedAbsolutePath(fileOrFolder.path, this.currentDirectory);
if (typeof fileOrFolder.content === "string") {
@@ -439,6 +433,10 @@ namespace ts.projectSystem {
};
}
createHash(s: string): string {
return s;
}
triggerDirectoryWatcherCallback(directoryName: string, fileName: string): void {
const path = this.toPath(directoryName);
const callbacks = this.watchedDirectories[path];
@@ -579,6 +577,35 @@ namespace ts.projectSystem {
checkWatchedDirectories(host, ["/a/b/c", "/a/b", "/a"]);
});
it("can handle tsconfig file name with difference casing", () => {
const f1 = {
path: "/a/b/app.ts",
content: "let x = 1"
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({
include: []
})
};
const host = createServerHost([f1, config], { useCaseSensitiveFileNames: false });
const service = createProjectService(host);
service.openExternalProject(<protocol.ExternalProject>{
projectFileName: "/a/b/project.csproj",
rootFiles: toExternalFiles([f1.path, combinePaths(getDirectoryPath(config.path).toUpperCase(), getBaseFileName(config.path))]),
options: {}
});
service.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(service.configuredProjects[0], []);
service.openClientFile(f1.path);
service.checkNumberOfProjects({ configuredProjects: 1, inferredProjects: 1 });
checkProjectActualFiles(service.configuredProjects[0], []);
checkProjectActualFiles(service.inferredProjects[0], [f1.path]);
})
it("create configured project without file list", () => {
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
@@ -700,6 +727,66 @@ namespace ts.projectSystem {
checkNumberOfInferredProjects(projectService, 1);
});
it("remove not-listed external projects", () => {
const f1 = {
path: "/a/app.ts",
content: "let x = 1"
};
const f2 = {
path: "/b/app.ts",
content: "let x = 1"
};
const f3 = {
path: "/c/app.ts",
content: "let x = 1"
};
const makeProject = (f: FileOrFolder) => ({ projectFileName: f.path + ".csproj", rootFiles: [toExternalFile(f.path)], options: {} });
const p1 = makeProject(f1);
const p2 = makeProject(f2);
const p3 = makeProject(f3);
const host = createServerHost([f1, f2, f3]);
const session = createSession(host);
session.executeCommand(<protocol.OpenExternalProjectsRequest>{
seq: 1,
type: "request",
command: "openExternalProjects",
arguments: { projects: [p1, p2] }
});
const projectService = session.getProjectService();
checkNumberOfProjects(projectService, { externalProjects: 2 });
assert.equal(projectService.externalProjects[0].getProjectName(), p1.projectFileName);
assert.equal(projectService.externalProjects[1].getProjectName(), p2.projectFileName);
session.executeCommand(<protocol.OpenExternalProjectsRequest>{
seq: 2,
type: "request",
command: "openExternalProjects",
arguments: { projects: [p1, p3] }
});
checkNumberOfProjects(projectService, { externalProjects: 2 });
assert.equal(projectService.externalProjects[0].getProjectName(), p1.projectFileName);
assert.equal(projectService.externalProjects[1].getProjectName(), p3.projectFileName);
session.executeCommand(<protocol.OpenExternalProjectsRequest>{
seq: 3,
type: "request",
command: "openExternalProjects",
arguments: { projects: [] }
});
checkNumberOfProjects(projectService, { externalProjects: 0 });
session.executeCommand(<protocol.OpenExternalProjectsRequest>{
seq: 3,
type: "request",
command: "openExternalProjects",
arguments: { projects: [p2] }
});
assert.equal(projectService.externalProjects[0].getProjectName(), p2.projectFileName);
});
it("handle recreated files correctly", () => {
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
@@ -1586,6 +1673,106 @@ namespace ts.projectSystem {
projectService.closeClientFile(file1.path);
checkNumberOfProjects(projectService, { configuredProjects: 0 });
});
it("language service disabled events are triggered", () => {
const f1 = {
path: "/a/app.js",
content: "let x = 1;"
};
const f2 = {
path: "/a/largefile.js",
content: ""
};
const config = {
path: "/a/jsconfig.json",
content: "{}"
};
const configWithExclude = {
path: config.path,
content: JSON.stringify({ exclude: ["largefile.js"] })
};
const host = createServerHost([f1, f2, config]);
const originalGetFileSize = host.getFileSize;
host.getFileSize = (filePath: string) =>
filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath);
let lastEvent: server.ProjectLanguageServiceStateEvent;
const session = createSession(host, /*typingsInstaller*/ undefined, e => {
if (e.eventName === server.ConfigFileDiagEvent || e.eventName === server.ContextEvent) {
return;
}
assert.equal(e.eventName, server.ProjectLanguageServiceStateEvent);
assert.equal(e.data.project.getProjectName(), config.path, "project name");
lastEvent = <server.ProjectLanguageServiceStateEvent>e;
});
session.executeCommand(<protocol.OpenRequest>{
seq: 0,
type: "request",
command: "open",
arguments: { file: f1.path }
});
const projectService = session.getProjectService();
checkNumberOfProjects(projectService, { configuredProjects: 1 });
const project = projectService.configuredProjects[0];
assert.isFalse(project.languageServiceEnabled, "Language service enabled");
assert.isTrue(!!lastEvent, "should receive event");
assert.equal(lastEvent.data.project, project, "project name");
assert.equal(lastEvent.data.project.getProjectName(), config.path, "config path");
assert.isFalse(lastEvent.data.languageServiceEnabled, "Language service state");
host.reloadFS([f1, f2, configWithExclude]);
host.triggerFileWatcherCallback(config.path, /*removed*/ false);
checkNumberOfProjects(projectService, { configuredProjects: 1 });
assert.isTrue(project.languageServiceEnabled, "Language service enabled");
assert.equal(lastEvent.data.project, project, "project");
assert.isTrue(lastEvent.data.languageServiceEnabled, "Language service state");
});
it("syntactic features work even if language service is disabled", () => {
const f1 = {
path: "/a/app.js",
content: "let x = 1;"
};
const f2 = {
path: "/a/largefile.js",
content: ""
};
const config = {
path: "/a/jsconfig.json",
content: "{}"
};
const host = createServerHost([f1, f2, config]);
const originalGetFileSize = host.getFileSize;
host.getFileSize = (filePath: string) =>
filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath);
let lastEvent: server.ProjectLanguageServiceStateEvent;
const session = createSession(host, /*typingsInstaller*/ undefined, e => {
if (e.eventName === server.ConfigFileDiagEvent) {
return;
}
assert.equal(e.eventName, server.ProjectLanguageServiceStateEvent);
lastEvent = <server.ProjectLanguageServiceStateEvent>e;
});
session.executeCommand(<protocol.OpenRequest>{
seq: 0,
type: "request",
command: "open",
arguments: { file: f1.path }
});
const projectService = session.getProjectService();
checkNumberOfProjects(projectService, { configuredProjects: 1 });
const project = projectService.configuredProjects[0];
assert.isFalse(project.languageServiceEnabled, "Language service enabled");
assert.isTrue(!!lastEvent, "should receive event");
assert.equal(lastEvent.data.project, project, "project name");
assert.isFalse(lastEvent.data.languageServiceEnabled, "Language service state");
const options = projectService.getFormatCodeOptions();
const edits = project.getLanguageService().getFormattingEditsForDocument(f1.path, options);
assert.deepEqual(edits, [{ span: createTextSpan(/*start*/ 7, /*length*/ 3), newText: " " }]);
});
});
describe("Proper errors", () => {
@@ -1627,8 +1814,8 @@ namespace ts.projectSystem {
options: {}
});
projectService.checkNumberOfProjects({ externalProjects: 1 });
const typingOptions = projectService.externalProjects[0].getTypingOptions();
assert.isTrue(typingOptions.enableAutoDiscovery, "Typing autodiscovery should be enabled");
const typeAcquisition = projectService.externalProjects[0].getTypeAcquisition();
assert.isTrue(typeAcquisition.enable, "Typine acquisition should be enabled");
});
});
@@ -1663,12 +1850,8 @@ namespace ts.projectSystem {
"File '/a/b/node_modules/lib/index.ts' does not exist.",
"File '/a/b/node_modules/lib/index.tsx' does not exist.",
"File '/a/b/node_modules/lib/index.d.ts' does not exist.",
"File '/a/b/node_modules/@types/lib.ts' does not exist.",
"File '/a/b/node_modules/@types/lib.tsx' does not exist.",
"File '/a/b/node_modules/@types/lib.d.ts' does not exist.",
"File '/a/b/node_modules/@types/lib/package.json' does not exist.",
"File '/a/b/node_modules/@types/lib/index.ts' does not exist.",
"File '/a/b/node_modules/@types/lib/index.tsx' does not exist.",
"File '/a/b/node_modules/@types/lib/index.d.ts' does not exist.",
"File '/a/node_modules/lib.ts' does not exist.",
"File '/a/node_modules/lib.tsx' does not exist.",
@@ -1677,12 +1860,8 @@ namespace ts.projectSystem {
"File '/a/node_modules/lib/index.ts' does not exist.",
"File '/a/node_modules/lib/index.tsx' does not exist.",
"File '/a/node_modules/lib/index.d.ts' does not exist.",
"File '/a/node_modules/@types/lib.ts' does not exist.",
"File '/a/node_modules/@types/lib.tsx' does not exist.",
"File '/a/node_modules/@types/lib.d.ts' does not exist.",
"File '/a/node_modules/@types/lib/package.json' does not exist.",
"File '/a/node_modules/@types/lib/index.ts' does not exist.",
"File '/a/node_modules/@types/lib/index.tsx' does not exist.",
"File '/a/node_modules/@types/lib/index.d.ts' does not exist.",
"File '/node_modules/lib.ts' does not exist.",
"File '/node_modules/lib.tsx' does not exist.",
@@ -1691,12 +1870,8 @@ namespace ts.projectSystem {
"File '/node_modules/lib/index.ts' does not exist.",
"File '/node_modules/lib/index.tsx' does not exist.",
"File '/node_modules/lib/index.d.ts' does not exist.",
"File '/node_modules/@types/lib.ts' does not exist.",
"File '/node_modules/@types/lib.tsx' does not exist.",
"File '/node_modules/@types/lib.d.ts' does not exist.",
"File '/node_modules/@types/lib/package.json' does not exist.",
"File '/node_modules/@types/lib/index.ts' does not exist.",
"File '/node_modules/@types/lib/index.tsx' does not exist.",
"File '/node_modules/@types/lib/index.d.ts' does not exist.",
"Loading module 'lib' from 'node_modules' folder.",
"File '/a/b/node_modules/lib.js' does not exist.",
@@ -1704,46 +1879,23 @@ namespace ts.projectSystem {
"File '/a/b/node_modules/lib/package.json' does not exist.",
"File '/a/b/node_modules/lib/index.js' does not exist.",
"File '/a/b/node_modules/lib/index.jsx' does not exist.",
"File '/a/b/node_modules/@types/lib.js' does not exist.",
"File '/a/b/node_modules/@types/lib.jsx' does not exist.",
"File '/a/b/node_modules/@types/lib/package.json' does not exist.",
"File '/a/b/node_modules/@types/lib/index.js' does not exist.",
"File '/a/b/node_modules/@types/lib/index.jsx' does not exist.",
"File '/a/node_modules/lib.js' does not exist.",
"File '/a/node_modules/lib.jsx' does not exist.",
"File '/a/node_modules/lib/package.json' does not exist.",
"File '/a/node_modules/lib/index.js' does not exist.",
"File '/a/node_modules/lib/index.jsx' does not exist.",
"File '/a/node_modules/@types/lib.js' does not exist.",
"File '/a/node_modules/@types/lib.jsx' does not exist.",
"File '/a/node_modules/@types/lib/package.json' does not exist.",
"File '/a/node_modules/@types/lib/index.js' does not exist.",
"File '/a/node_modules/@types/lib/index.jsx' does not exist.",
"File '/node_modules/lib.js' does not exist.",
"File '/node_modules/lib.jsx' does not exist.",
"File '/node_modules/lib/package.json' does not exist.",
"File '/node_modules/lib/index.js' does not exist.",
"File '/node_modules/lib/index.jsx' does not exist.",
"File '/node_modules/@types/lib.js' does not exist.",
"File '/node_modules/@types/lib.jsx' does not exist.",
"File '/node_modules/@types/lib/package.json' does not exist.",
"File '/node_modules/@types/lib/index.js' does not exist.",
"File '/node_modules/@types/lib/index.jsx' does not exist.",
"======== Module name 'lib' was not resolved. ========",
`Auto discovery for typings is enabled in project '${proj.getProjectName()}'. Running extra resolution pass for module 'lib' using cache location '/a/cache'.`,
"File '/a/cache/node_modules/lib.ts' does not exist.",
"File '/a/cache/node_modules/lib.tsx' does not exist.",
"File '/a/cache/node_modules/lib.d.ts' does not exist.",
"File '/a/cache/node_modules/lib/package.json' does not exist.",
"File '/a/cache/node_modules/lib/index.ts' does not exist.",
"File '/a/cache/node_modules/lib/index.tsx' does not exist.",
"File '/a/cache/node_modules/lib/index.d.ts' does not exist.",
"File '/a/cache/node_modules/@types/lib.ts' does not exist.",
"File '/a/cache/node_modules/@types/lib.tsx' does not exist.",
"File '/a/cache/node_modules/@types/lib.d.ts' does not exist.",
"File '/a/cache/node_modules/@types/lib/package.json' does not exist.",
"File '/a/cache/node_modules/@types/lib/index.ts' does not exist.",
"File '/a/cache/node_modules/@types/lib/index.tsx' does not exist.",
"File '/a/cache/node_modules/@types/lib/index.d.ts' exist - use it as a name resolution result.",
]);
checkProjectActualFiles(proj, [file1.path, lib.path]);
@@ -1969,6 +2121,33 @@ namespace ts.projectSystem {
projectService.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [libES5.path, libES2015Promise.path, app.path]);
});
it("should handle non-existing directories in config file", () => {
const f = {
path: "/a/src/app.ts",
content: "let x = 1;"
};
const config = {
path: "/a/tsconfig.json",
content: JSON.stringify({
compilerOptions: {},
include: [
"src/**/*",
"notexistingfolder/*"
]
})
};
const host = createServerHost([f, config]);
const projectService = createProjectService(host);
projectService.openClientFile(f.path);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
projectService.closeClientFile(f.path);
projectService.checkNumberOfProjects({ configuredProjects: 0 });
projectService.openClientFile(f.path);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
});
});
describe("prefer typings to js", () => {
@@ -2227,6 +2406,51 @@ namespace ts.projectSystem {
assert.equal(diags.length, 0);
});
it("should property handle missing config files", () => {
const f1 = {
path: "/a/b/app.ts",
content: "let x = 1"
};
const config = {
path: "/a/b/tsconfig.json",
content: "{}"
};
const projectName = "project1";
const host = createServerHost([f1]);
const projectService = createProjectService(host);
projectService.openExternalProject({ rootFiles: toExternalFiles([f1.path, config.path]), options: {}, projectFileName: projectName });
// should have one external project since config file is missing
projectService.checkNumberOfProjects({ externalProjects: 1 });
host.reloadFS([f1, config]);
projectService.openExternalProject({ rootFiles: toExternalFiles([f1.path, config.path]), options: {}, projectFileName: projectName });
projectService.checkNumberOfProjects({ configuredProjects: 1 });
});
it("types should load from config file path if config exists", () => {
const f1 = {
path: "/a/b/app.ts",
content: "let x = 1"
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ compilerOptions: { types: ["node"], typeRoots: [] } })
};
const node = {
path: "/a/b/node_modules/@types/node/index.d.ts",
content: "declare var process: any"
};
const cwd = {
path: "/a/c"
};
debugger;
const host = createServerHost([f1, config, node, cwd], { currentDirectory: cwd.path });
const projectService = createProjectService(host);
projectService.openClientFile(f1.path);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [f1.path, node.path]);
});
});
describe("add the missing module file for inferred project", () => {
@@ -2316,6 +2540,43 @@ namespace ts.projectSystem {
openFilesForSession([file], session);
serverEventManager.checkEventCountOfType("configFileDiag", 1);
});
it("are generated when the config file changes", () => {
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);
configFile.content = `{
"compilerOptions": {
"haha": 123
}
}`;
host.reloadFS([file, configFile]);
host.triggerFileWatcherCallback(configFile.path);
host.runQueuedTimeoutCallbacks();
serverEventManager.checkEventCountOfType("configFileDiag", 2);
configFile.content = `{
"compilerOptions": {}
}`;
host.reloadFS([file, configFile]);
host.triggerFileWatcherCallback(configFile.path);
host.runQueuedTimeoutCallbacks();
serverEventManager.checkEventCountOfType("configFileDiag", 3);
});
});
describe("skipLibCheck", () => {
@@ -2505,4 +2766,104 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[0], [f.path]);
});
});
describe("No overwrite emit error", () => {
it("for inferred project", () => {
const f1 = {
path: "/a/b/f1.js",
content: "function test1() { }"
};
const host = createServerHost([f1, libFile]);
const session = createSession(host);
openFilesForSession([f1], session);
const projectService = session.getProjectService();
checkNumberOfProjects(projectService, { inferredProjects: 1 });
const projectName = projectService.inferredProjects[0].getProjectName();
const diags = session.executeCommand(<server.protocol.CompilerOptionsDiagnosticsRequest>{
type: "request",
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 2,
arguments: { projectFileName: projectName }
}).response;
assert.isTrue(diags.length === 0);
session.executeCommand(<server.protocol.SetCompilerOptionsForInferredProjectsRequest>{
type: "request",
command: server.CommandNames.CompilerOptionsForInferredProjects,
seq: 3,
arguments: { options: { module: ModuleKind.CommonJS } }
});
const diagsAfterUpdate = session.executeCommand(<server.protocol.CompilerOptionsDiagnosticsRequest>{
type: "request",
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 4,
arguments: { projectFileName: projectName }
}).response;
assert.isTrue(diagsAfterUpdate.length === 0);
});
it("for external project", () => {
const f1 = {
path: "/a/b/f1.js",
content: "function test1() { }"
};
const host = createServerHost([f1, libFile]);
const session = createSession(host);
const projectService = session.getProjectService();
const projectFileName = "/a/b/project.csproj";
const externalFiles = toExternalFiles([f1.path]);
projectService.openExternalProject(<protocol.ExternalProject>{
projectFileName,
rootFiles: externalFiles,
options: {}
});
checkNumberOfProjects(projectService, { externalProjects: 1 });
const diags = session.executeCommand(<server.protocol.CompilerOptionsDiagnosticsRequest>{
type: "request",
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 2,
arguments: { projectFileName }
}).response;
assert.isTrue(diags.length === 0);
session.executeCommand(<server.protocol.OpenExternalProjectRequest>{
type: "request",
command: server.CommandNames.OpenExternalProject,
seq: 3,
arguments: {
projectFileName,
rootFiles: externalFiles,
options: { module: ModuleKind.CommonJS }
}
});
const diagsAfterUpdate = session.executeCommand(<server.protocol.CompilerOptionsDiagnosticsRequest>{
type: "request",
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 4,
arguments: { projectFileName }
}).response;
assert.isTrue(diagsAfterUpdate.length === 0);
});
});
describe("import helpers", () => {
it("should not crash in tsserver", () => {
const f1 = {
path: "/a/app.ts",
content: "export async function foo() { return 100; }"
};
const tslib = {
path: "/a/node_modules/tslib/index.d.ts",
content: ""
};
const host = createServerHost([f1, tslib]);
const service = createProjectService(host);
service.openExternalProject({ projectFileName: "p", rootFiles: [toExternalFile(f1.path)], options: { importHelpers: true } });
service.checkNumberOfProjects({ externalProjects: 1 });
});
});
}
+263 -144
View File
@@ -8,6 +8,15 @@ namespace ts.projectSystem {
interface InstallerParams {
globalTypingsCacheLocation?: string;
throttleLimit?: number;
typesRegistry?: Map<void>;
}
function createTypesRegistry(...list: string[]): Map<void> {
const map = createMap<void>();
for (const l of list) {
map[l] = undefined;
}
return map;
}
class Installer extends TestTypingsInstaller {
@@ -16,36 +25,26 @@ namespace ts.projectSystem {
(p && p.globalTypingsCacheLocation) || "/a/data",
(p && p.throttleLimit) || 5,
host,
(p && p.typesRegistry),
log);
}
installAll(expectedView: typeof TI.NpmViewRequest[], expectedInstall: typeof TI.NpmInstallRequest[]) {
this.checkPendingCommands(expectedView);
this.executePendingCommands();
this.checkPendingCommands(expectedInstall);
installAll(expectedCount: number) {
this.checkPendingCommands(expectedCount);
this.executePendingCommands();
}
}
describe("typingsInstaller", () => {
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, success => {
for (const file of typingFiles) {
host.createFileOrFolder(file, /*createParentDirectory*/ true);
}
cb(success);
});
break;
case TI.NpmViewRequest:
self.addPostExecAction(requestKind, installedTypings, cb);
break;
default:
assert.isTrue(false, `unexpected request kind ${requestKind}`);
break;
function executeCommand(self: Installer, host: TestServerHost, installedTypings: string[] | string, typingFiles: FileOrFolder[], cb: TI.RequestCompletedAction): void {
self.addPostExecAction(installedTypings, success => {
for (const file of typingFiles) {
host.createFileOrFolder(file, /*createParentDirectory*/ true);
}
}
cb(success);
});
}
describe("typingsInstaller", () => {
it("configured projects (typings installed) 1", () => {
const file1 = {
path: "/a/b/app.js",
@@ -57,8 +56,8 @@ namespace ts.projectSystem {
compilerOptions: {
allowJs: true
},
typingOptions: {
enableAutoDiscovery: true
typeAcquisition: {
enable: true
}
})
};
@@ -79,12 +78,12 @@ namespace ts.projectSystem {
const host = createServerHost([file1, tsconfig, packageJson]);
const installer = new (class extends Installer {
constructor() {
super(host);
super(host, { typesRegistry: createTypesRegistry("jquery") });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jquery];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
@@ -95,7 +94,7 @@ namespace ts.projectSystem {
const p = projectService.configuredProjects[0];
checkProjectActualFiles(p, [file1.path]);
installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]);
installer.installAll(/*expectedCount*/ 1);
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(p, [file1.path, jquery.path]);
@@ -123,12 +122,12 @@ namespace ts.projectSystem {
const host = createServerHost([file1, packageJson]);
const installer = new (class extends Installer {
constructor() {
super(host);
super(host, { typesRegistry: createTypesRegistry("jquery") });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jquery];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
@@ -139,13 +138,13 @@ namespace ts.projectSystem {
const p = projectService.inferredProjects[0];
checkProjectActualFiles(p, [file1.path]);
installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]);
installer.installAll(/*expectedCount*/ 1);
checkNumberOfProjects(projectService, { inferredProjects: 1 });
checkProjectActualFiles(p, [file1.path, jquery.path]);
});
it("external project - no typing options, no .d.ts/js files", () => {
it("external project - no type acquisition, no .d.ts/js files", () => {
const file1 = {
path: "/a/b/app.ts",
content: ""
@@ -167,13 +166,13 @@ namespace ts.projectSystem {
options: {},
rootFiles: [toExternalFile(file1.path)]
});
installer.checkPendingCommands([]);
installer.checkPendingCommands(/*expectedCount*/ 0);
// by default auto discovery will kick in if project contain only .js/.d.ts files
// in this case project contain only ts files - no auto discovery
projectService.checkNumberOfProjects({ externalProjects: 1 });
});
it("external project - no autoDiscovery in typing options, no .d.ts/js files", () => {
it("external project - no auto in typing acquisition, no .d.ts/js files", () => {
const file1 = {
path: "/a/b/app.ts",
content: ""
@@ -181,7 +180,7 @@ namespace ts.projectSystem {
const host = createServerHost([file1]);
const installer = new (class extends Installer {
constructor() {
super(host);
super(host, { typesRegistry: createTypesRegistry("jquery") });
}
enqueueInstallTypingsRequest() {
assert(false, "auto discovery should not be enabled");
@@ -194,11 +193,11 @@ namespace ts.projectSystem {
projectFileName,
options: {},
rootFiles: [toExternalFile(file1.path)],
typingOptions: { include: ["jquery"] }
typeAcquisition: { include: ["jquery"] }
});
installer.checkPendingCommands([]);
installer.checkPendingCommands(/*expectedCount*/ 0);
// by default auto discovery will kick in if project contain only .js/.d.ts files
// in this case project contain only ts files - no auto discovery even if typing options is set
// in this case project contain only ts files - no auto discovery even if type acquisition is set
projectService.checkNumberOfProjects({ externalProjects: 1 });
});
@@ -215,16 +214,16 @@ namespace ts.projectSystem {
let enqueueIsCalled = false;
const installer = new (class extends Installer {
constructor() {
super(host);
super(host, { typesRegistry: createTypesRegistry("jquery") });
}
enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueIsCalled = true;
super.enqueueInstallTypingsRequest(project, typingOptions, unresolvedImports);
super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/jquery"];
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/node"];
const typingFiles = [jquery];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
@@ -234,17 +233,17 @@ namespace ts.projectSystem {
projectFileName,
options: {},
rootFiles: [toExternalFile(file1.path)],
typingOptions: { enableAutoDiscovery: true, include: ["node"] }
typeAcquisition: { enable: true, include: ["jquery"] }
});
assert.isTrue(enqueueIsCalled, "expected enqueueIsCalled to be true");
installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]);
installer.installAll(/*expectedCount*/ 1);
// autoDiscovery is set in typing options - use it even if project contains only .ts files
// auto is set in type acquisition - use it even if project contains only .ts files
projectService.checkNumberOfProjects({ externalProjects: 1 });
});
it("external project - no typing options, with only js, jsx, d.ts files", () => {
it("external project - no type acquisition, with only js, jsx, d.ts files", () => {
// Tests:
// 1. react typings are installed for .jsx
// 2. loose files names are matched against safe list for typings if
@@ -273,12 +272,12 @@ namespace ts.projectSystem {
const host = createServerHost([file1, file2, file3]);
const installer = new (class extends Installer {
constructor() {
super(host);
super(host, { typesRegistry: createTypesRegistry("lodash", "react") });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
installWorker(_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);
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
@@ -288,20 +287,20 @@ namespace ts.projectSystem {
projectFileName,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(file1.path), toExternalFile(file2.path), toExternalFile(file3.path)],
typingOptions: {}
typeAcquisition: {}
});
const p = projectService.externalProjects[0];
projectService.checkNumberOfProjects({ externalProjects: 1 });
checkProjectActualFiles(p, [file1.path, file2.path, file3.path]);
installer.installAll([TI.NpmViewRequest, TI.NpmViewRequest], [TI.NpmInstallRequest], );
installer.installAll(/*expectedCount*/ 1);
checkNumberOfProjects(projectService, { externalProjects: 1 });
checkProjectActualFiles(p, [file1.path, file2.path, file3.path, lodash.path, react.path]);
});
it("external project - no typing options, with js & ts files", () => {
it("external project - no type acquisition, with js & ts files", () => {
// Tests:
// 1. No typings are included for JS projects when the project contains ts files
const file1 = {
@@ -317,16 +316,16 @@ namespace ts.projectSystem {
let enqueueIsCalled = false;
const installer = new (class extends Installer {
constructor() {
super(host);
super(host, { typesRegistry: createTypesRegistry("jquery") });
}
enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueIsCalled = true;
super.enqueueInstallTypingsRequest(project, typingOptions, unresolvedImports);
super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings: string[] = [];
const typingFiles: FileOrFolder[] = [];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
@@ -336,24 +335,24 @@ namespace ts.projectSystem {
projectFileName,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(file1.path), toExternalFile(file2.path)],
typingOptions: {}
typeAcquisition: {}
});
const p = projectService.externalProjects[0];
projectService.checkNumberOfProjects({ externalProjects: 1 });
checkProjectActualFiles(p, [file1.path, file2.path]);
installer.checkPendingCommands([]);
installer.checkPendingCommands(/*expectedCount*/ 0);
checkNumberOfProjects(projectService, { externalProjects: 1 });
checkProjectActualFiles(p, [file1.path, file2.path]);
});
it("external project - with typing options, with only js, d.ts files", () => {
it("external project - with type acquisition, with only js, d.ts files", () => {
// Tests:
// 1. Safelist matching, typing options includes/excludes and package.json typings are all acquired
// 2. Types for safelist matches are not included when they also appear in the typing option exclude list
// 3. Multiple includes and excludes are respected in typing options
// 1. Safelist matching, type acquisition includes/excludes and package.json typings are all acquired
// 2. Types for safelist matches are not included when they also appear in the type acquisition exclude list
// 3. Multiple includes and excludes are respected in type acquisition
const file1 = {
path: "/a/b/lodash.js",
content: ""
@@ -396,12 +395,12 @@ namespace ts.projectSystem {
const host = createServerHost([file1, file2, file3, packageJson]);
const installer = new (class extends Installer {
constructor() {
super(host);
super(host, { typesRegistry: createTypesRegistry("jquery", "commander", "moment", "express") });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
installWorker(_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);
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
@@ -411,17 +410,14 @@ namespace ts.projectSystem {
projectFileName,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(file1.path), toExternalFile(file2.path), toExternalFile(file3.path)],
typingOptions: { include: ["jquery", "moment"], exclude: ["lodash"] }
typeAcquisition: { include: ["jquery", "moment"], exclude: ["lodash"] }
});
const p = projectService.externalProjects[0];
projectService.checkNumberOfProjects({ externalProjects: 1 });
checkProjectActualFiles(p, [file1.path, file2.path, file3.path]);
installer.installAll(
[TI.NpmViewRequest, TI.NpmViewRequest, TI.NpmViewRequest, TI.NpmViewRequest],
[TI.NpmInstallRequest]
);
installer.installAll(/*expectedCount*/ 1);
checkNumberOfProjects(projectService, { externalProjects: 1 });
checkProjectActualFiles(p, [file1.path, file2.path, file3.path, commander.path, express.path, jquery.path, moment.path]);
@@ -475,11 +471,11 @@ namespace ts.projectSystem {
const host = createServerHost([lodashJs, commanderJs, file3, packageJson]);
const installer = new (class extends Installer {
constructor() {
super(host, { throttleLimit: 3 });
super(host, { throttleLimit: 3, typesRegistry: createTypesRegistry("commander", "express", "jquery", "moment", "lodash") });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
installWorker(_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);
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
@@ -489,24 +485,13 @@ namespace ts.projectSystem {
projectFileName,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(lodashJs.path), toExternalFile(commanderJs.path), toExternalFile(file3.path)],
typingOptions: { include: ["jquery", "moment"] }
typeAcquisition: { include: ["jquery", "moment"] }
});
const p = projectService.externalProjects[0];
projectService.checkNumberOfProjects({ externalProjects: 1 });
checkProjectActualFiles(p, [lodashJs.path, commanderJs.path, file3.path]);
// expected 3 view requests in the queue
installer.checkPendingCommands([TI.NpmViewRequest, TI.NpmViewRequest, TI.NpmViewRequest]);
assert.equal(installer.pendingRunRequests.length, 2, "expected 2 pending requests");
// push view requests
installer.executePendingCommands();
// expected 2 remaining view requests in the queue
installer.checkPendingCommands([TI.NpmViewRequest, TI.NpmViewRequest]);
// push view requests
installer.executePendingCommands();
// expected one install request
installer.checkPendingCommands([TI.NpmInstallRequest]);
installer.checkPendingCommands(/*expectedCount*/ 1);
installer.executePendingCommands();
// expected all typings file to exist
for (const f of typingFiles) {
@@ -565,22 +550,17 @@ namespace ts.projectSystem {
const host = createServerHost([lodashJs, commanderJs, file3]);
const installer = new (class extends Installer {
constructor() {
super(host, { throttleLimit: 3 });
super(host, { throttleLimit: 1, typesRegistry: createTypesRegistry("commander", "jquery", "lodash", "cordova", "gulp", "grunt") });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
if (requestKind === TI.NpmInstallRequest) {
let typingFiles: (FileOrFolder & { typings: string })[] = [];
if (args.indexOf("@types/commander") >= 0) {
typingFiles = [commander, jquery, lodash, cordova];
}
else {
typingFiles = [grunt, gulp];
}
executeCommand(this, host, typingFiles.map(f => f.typings), typingFiles, requestKind, cb);
installWorker(_requestId: number, args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
let typingFiles: (FileOrFolder & { typings: string })[] = [];
if (args.indexOf("@types/commander") >= 0) {
typingFiles = [commander, jquery, lodash, cordova];
}
else {
executeCommand(this, host, [], [], requestKind, cb);
typingFiles = [grunt, gulp];
}
executeCommand(this, host, typingFiles.map(f => f.typings), typingFiles, cb);
}
})();
@@ -591,11 +571,11 @@ namespace ts.projectSystem {
projectFileName: projectFileName1,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(lodashJs.path), toExternalFile(commanderJs.path), toExternalFile(file3.path)],
typingOptions: { include: ["jquery", "cordova"] }
typeAcquisition: { include: ["jquery", "cordova"] }
});
installer.checkPendingCommands([TI.NpmViewRequest, TI.NpmViewRequest, TI.NpmViewRequest]);
assert.equal(installer.pendingRunRequests.length, 1, "expect one throttled request");
installer.checkPendingCommands(/*expectedCount*/ 1);
assert.equal(installer.pendingRunRequests.length, 0, "expect no throttled requests");
// Create project #2 with 2 typings
const projectFileName2 = "/a/app/test2.csproj";
@@ -603,9 +583,9 @@ namespace ts.projectSystem {
projectFileName: projectFileName2,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(file3.path)],
typingOptions: { include: ["grunt", "gulp"] }
typeAcquisition: { include: ["grunt", "gulp"] }
});
assert.equal(installer.pendingRunRequests.length, 3, "expect three throttled request");
assert.equal(installer.pendingRunRequests.length, 1, "expect one throttled request");
const p1 = projectService.externalProjects[0];
const p2 = projectService.externalProjects[1];
@@ -613,18 +593,14 @@ namespace ts.projectSystem {
checkProjectActualFiles(p1, [lodashJs.path, commanderJs.path, file3.path]);
checkProjectActualFiles(p2, [file3.path]);
installer.executePendingCommands();
// expected one view request from the first project and two - from the second one
installer.checkPendingCommands([TI.NpmViewRequest, TI.NpmViewRequest, TI.NpmViewRequest]);
// expected one install request from the second project
installer.checkPendingCommands(/*expectedCount*/ 1);
assert.equal(installer.pendingRunRequests.length, 0, "expected no throttled requests");
installer.executePendingCommands();
// should be two install requests from both projects
installer.checkPendingCommands([TI.NpmInstallRequest, TI.NpmInstallRequest]);
installer.executePendingCommands();
checkProjectActualFiles(p1, [lodashJs.path, commanderJs.path, file3.path, commander.path, jquery.path, lodash.path, cordova.path]);
checkProjectActualFiles(p2, [file3.path, grunt.path, gulp.path]);
});
@@ -653,12 +629,12 @@ namespace ts.projectSystem {
const host = createServerHost([app, jsconfig, jquery, jqueryPackage]);
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" });
super(host, { globalTypingsCacheLocation: "/tmp", typesRegistry: createTypesRegistry("jquery") });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jqueryDTS];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
@@ -669,7 +645,7 @@ namespace ts.projectSystem {
const p = projectService.configuredProjects[0];
checkProjectActualFiles(p, [app.path]);
installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]);
installer.installAll(/*expectedCount*/ 1);
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(p, [app.path, jqueryDTS.path]);
@@ -699,12 +675,12 @@ namespace ts.projectSystem {
const host = createServerHost([app, jsconfig, bowerJson]);
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" });
super(host, { globalTypingsCacheLocation: "/tmp", typesRegistry: createTypesRegistry("jquery") });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jqueryDTS];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
@@ -715,7 +691,7 @@ namespace ts.projectSystem {
const p = projectService.configuredProjects[0];
checkProjectActualFiles(p, [app.path]);
installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]);
installer.installAll(/*expectedCount*/ 1);
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(p, [app.path, jqueryDTS.path]);
@@ -742,23 +718,23 @@ namespace ts.projectSystem {
const host = createServerHost([f, brokenPackageJson]);
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: cachePath });
super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("commander") });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/commander"];
const typingFiles = [commander];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
const service = createProjectService(host, { typingsInstaller: installer });
service.openClientFile(f.path);
installer.checkPendingCommands([]);
installer.checkPendingCommands(/*expectedCount*/ 0);
host.reloadFS([f, fixedPackageJson]);
host.triggerFileWatcherCallback(fixedPackageJson.path, /*removed*/ false);
// expected one view and one install request
installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]);
// expected install request
installer.installAll(/*expectedCount*/ 1);
service.checkNumberOfProjects({ inferredProjects: 1 });
checkProjectActualFiles(service.inferredProjects[0], [f.path, commander.path]);
@@ -783,12 +759,12 @@ namespace ts.projectSystem {
const host = createServerHost([file]);
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: cachePath });
super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("node", "commander") });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/node", "@types/commander"];
const typingFiles = [node, commander];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
const service = createProjectService(host, { typingsInstaller: installer });
@@ -797,7 +773,7 @@ namespace ts.projectSystem {
service.checkNumberOfProjects({ inferredProjects: 1 });
checkProjectActualFiles(service.inferredProjects[0], [file.path]);
installer.installAll([TI.NpmViewRequest, TI.NpmViewRequest], [TI.NpmInstallRequest]);
installer.installAll(/*expectedCount*/1);
assert.isTrue(host.fileExists(node.path), "typings for 'node' should be created");
assert.isTrue(host.fileExists(commander.path), "typings for 'commander' should be created");
@@ -822,14 +798,10 @@ namespace ts.projectSystem {
const host = createServerHost([f1]);
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" });
super(host, { globalTypingsCacheLocation: "/tmp", typesRegistry: createTypesRegistry("foo") });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
if (requestKind === TI.NpmViewRequest) {
// args should have only non-scoped packages - scoped packages are not yet supported
assert.deepEqual(args, ["foo"]);
}
executeCommand(this, host, ["foo"], [], requestKind, cb);
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeCommand(this, host, ["foo"], [], cb);
}
})();
const projectService = createProjectService(host, { typingsInstaller: installer });
@@ -844,7 +816,7 @@ namespace ts.projectSystem {
["foo", "foo", "foo", "@bar/router", "@bar/common", "@bar/common"]
);
installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]);
installer.installAll(/*expectedCount*/ 1);
});
it("cached unresolved typings are not recomputed if program structure did not change", () => {
@@ -936,14 +908,14 @@ namespace ts.projectSystem {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" }, { isEnabled: () => true, writeLine: msg => messages.push(msg) });
}
executeRequest() {
installWorker(_requestId: number, _args: string[], _cwd: string, _cb: server.typingsInstaller.RequestCompletedAction) {
assert(false, "runCommand should not be invoked");
}
})();
const projectService = createProjectService(host, { typingsInstaller: installer });
projectService.openClientFile(f1.path);
installer.checkPendingCommands([]);
installer.checkPendingCommands(/*expectedCount*/ 0);
assert.isTrue(messages.indexOf("Package name '; say Hello from TypeScript! #' contains non URI safe characters") > 0, "should find package with invalid name");
});
});
@@ -957,7 +929,7 @@ namespace ts.projectSystem {
const host = createServerHost([f]);
const cache = createMap<string>();
for (const name of JsTyping.nodeCoreModuleList) {
const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(<Path>f.path), /*safeListPath*/ undefined, cache, { enableAutoDiscovery: true }, [name, "somename"]);
const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(<Path>f.path), /*safeListPath*/ undefined, cache, { enable: true }, [name, "somename"]);
assert.deepEqual(result.newTypingNames.sort(), ["node", "somename"]);
}
});
@@ -973,9 +945,156 @@ namespace ts.projectSystem {
};
const host = createServerHost([f, node]);
const cache = createMap<string>({ "node": node.path });
const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(<Path>f.path), /*safeListPath*/ undefined, cache, { enableAutoDiscovery: true }, ["fs", "bar"]);
const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(<Path>f.path), /*safeListPath*/ undefined, cache, { enable: true }, ["fs", "bar"]);
assert.deepEqual(result.cachedTypingPaths, [node.path]);
assert.deepEqual(result.newTypingNames, ["bar"]);
});
});
describe("telemetry events", () => {
it ("should be received", () => {
const f1 = {
path: "/a/app.js",
content: ""
};
const package = {
path: "/a/package.json",
content: JSON.stringify({ dependencies: { "commander": "1.0.0" } })
};
const cachePath = "/a/cache/";
const commander = {
path: cachePath + "node_modules/@types/commander/index.d.ts",
content: "export let x: number"
};
const host = createServerHost([f1, package]);
let seenTelemetryEvent = false;
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("commander") });
}
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/commander"];
const typingFiles = [commander];
executeCommand(this, host, installedTypings, typingFiles, cb);
}
sendResponse(response: server.SetTypings | server.InvalidateCachedTypings | server.BeginInstallTypes | server.EndInstallTypes) {
if (response.kind === server.EventBeginInstallTypes) {
return;
}
if (response.kind === server.EventEndInstallTypes) {
assert.deepEqual(response.packagesToInstall, ["@types/commander"]);
seenTelemetryEvent = true;
return;
}
super.sendResponse(response);
}
})();
const projectService = createProjectService(host, { typingsInstaller: installer });
projectService.openClientFile(f1.path);
installer.installAll(/*expectedCount*/ 1);
assert.isTrue(seenTelemetryEvent);
checkNumberOfProjects(projectService, { inferredProjects: 1 });
checkProjectActualFiles(projectService.inferredProjects[0], [f1.path, commander.path]);
});
});
describe("progress notifications", () => {
it ("should be sent for success", () => {
const f1 = {
path: "/a/app.js",
content: ""
};
const package = {
path: "/a/package.json",
content: JSON.stringify({ dependencies: { "commander": "1.0.0" } })
};
const cachePath = "/a/cache/";
const commander = {
path: cachePath + "node_modules/@types/commander/index.d.ts",
content: "export let x: number"
};
const host = createServerHost([f1, package]);
let beginEvent: server.BeginInstallTypes;
let endEvent: server.EndInstallTypes;
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("commander") });
}
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/commander"];
const typingFiles = [commander];
executeCommand(this, host, installedTypings, typingFiles, cb);
}
sendResponse(response: server.SetTypings | server.InvalidateCachedTypings | server.BeginInstallTypes | server.EndInstallTypes) {
if (response.kind === server.EventBeginInstallTypes) {
beginEvent = response;
return;
}
if (response.kind === server.EventEndInstallTypes) {
endEvent = response;
return;
}
super.sendResponse(response);
}
})();
const projectService = createProjectService(host, { typingsInstaller: installer });
projectService.openClientFile(f1.path);
installer.installAll(/*expectedCount*/ 1);
assert.isTrue(!!beginEvent);
assert.isTrue(!!endEvent);
assert.isTrue(beginEvent.eventId === endEvent.eventId);
assert.isTrue(endEvent.installSuccess);
checkNumberOfProjects(projectService, { inferredProjects: 1 });
checkProjectActualFiles(projectService.inferredProjects[0], [f1.path, commander.path]);
});
it ("should be sent for error", () => {
const f1 = {
path: "/a/app.js",
content: ""
};
const package = {
path: "/a/package.json",
content: JSON.stringify({ dependencies: { "commander": "1.0.0" } })
};
const cachePath = "/a/cache/";
const host = createServerHost([f1, package]);
let beginEvent: server.BeginInstallTypes;
let endEvent: server.EndInstallTypes;
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("commander") });
}
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeCommand(this, host, "", [], cb);
}
sendResponse(response: server.SetTypings | server.InvalidateCachedTypings | server.BeginInstallTypes | server.EndInstallTypes) {
if (response.kind === server.EventBeginInstallTypes) {
beginEvent = response;
return;
}
if (response.kind === server.EventEndInstallTypes) {
endEvent = response;
return;
}
super.sendResponse(response);
}
})();
const projectService = createProjectService(host, { typingsInstaller: installer });
projectService.openClientFile(f1.path);
installer.installAll(/*expectedCount*/ 1);
assert.isTrue(!!beginEvent);
assert.isTrue(!!endEvent);
assert.isTrue(beginEvent.eventId === endEvent.eventId);
assert.isFalse(endEvent.installSuccess);
checkNumberOfProjects(projectService, { inferredProjects: 1 });
checkProjectActualFiles(projectService.inferredProjects[0], [f1.path]);
});
});
}
+1689 -2601
View File
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -205,13 +205,13 @@ interface NumberConstructor {
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(value: any): value is number;
isFinite(number: number): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(value: any): value is number;
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
@@ -219,13 +219,13 @@ interface NumberConstructor {
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(value: any): value is number;
isNaN(number: number): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(value: any): value is number;
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
+3 -3
View File
@@ -1,5 +1,5 @@
interface ProxyHandler<T> {
getPrototypeOf? (target: T): any;
getPrototypeOf? (target: T): {} | null;
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
preventExtensions? (target: T): boolean;
@@ -12,11 +12,11 @@ interface ProxyHandler<T> {
enumerate? (target: T): PropertyKey[];
ownKeys? (target: T): PropertyKey[];
apply? (target: T, thisArg: any, argArray?: any): any;
construct? (target: T, thisArg: any, argArray?: any): any;
construct? (target: T, argArray: any, newTarget?: any): {};
}
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;
declare var Proxy: ProxyConstructor;
+9
View File
@@ -7,6 +7,15 @@ interface Array<T> {
includes(searchElement: T, fromIndex?: number): boolean;
}
interface ReadonlyArray<T> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: T, fromIndex?: number): boolean;
}
interface Int8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
+2 -1
View File
@@ -1,3 +1,4 @@
/// <reference path="lib.es2016.d.ts" />
/// <reference path="lib.es2017.object.d.ts" />
/// <reference path="lib.es2017.sharedmemory.d.ts" />
/// <reference path="lib.es2017.sharedmemory.d.ts" />
/// <reference path="lib.es2017.string.d.ts" />
+12 -1
View File
@@ -4,11 +4,22 @@ interface ObjectConstructor {
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values<T>(o: { [s: string]: T }): T[];
/**
* Returns an array of values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values(o: any): any[];
/**
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries<T>(o: { [s: string]: T }): [string, T][];
/**
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries(o: any): [string, any][];
}
}
+27
View File
@@ -0,0 +1,27 @@
interface String {
/**
* Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length.
* The padding is applied from the start (left) of the current string.
*
* @param maxLength The length of the resulting string once the current string has been padded.
* If this parameter is smaller than the current string's length, the current string will be returned as it is.
*
* @param fillString The string to pad the current string with.
* If this string is too long, it will be truncated and the left-most part will be applied.
* The default value for this parameter is " " (U+0020).
*/
padStart(maxLength: number, fillString?: string): string;
/**
* Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length.
* The padding is applied from the end (right) of the current string.
*
* @param maxLength The length of the resulting string once the current string has been padded.
* If this parameter is smaller than the current string's length, the current string will be returned as it is.
*
* @param fillString The string to pad the current string with.
* If this string is too long, it will be truncated and the left-most part will be applied.
* The default value for this parameter is " " (U+0020).
*/
padEnd(maxLength: number, fillString?: string): string;
}
+41 -1
View File
@@ -180,7 +180,19 @@ interface ObjectConstructor {
* Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
* @param o Object on which to lock the attributes.
*/
freeze<T>(o: T): T;
freeze<T>(a: T[]): ReadonlyArray<T>;
/**
* Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
* @param o Object on which to lock the attributes.
*/
freeze<T extends Function>(f: T): T;
/**
* Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
* @param o Object on which to lock the attributes.
*/
freeze<T>(o: T): Readonly<T>;
/**
* Prevents the addition of new properties to an object.
@@ -1343,6 +1355,34 @@ interface ArrayLike<T> {
readonly [n: number]: T;
}
/**
* Make all properties in T optional
*/
type Partial<T> = {
[P in keyof T]?: T[P];
};
/**
* Make all properties in T readonly
*/
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
/**
* From T pick a set of properties K
*/
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
}
/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends string, T> = {
[P in K]: T;
}
/**
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,
+133 -85
View File
@@ -8,6 +8,7 @@ interface Algorithm {
}
interface EventInit {
scoped?: boolean;
bubbles?: boolean;
cancelable?: boolean;
}
@@ -242,10 +243,12 @@ interface Event {
readonly target: EventTarget;
readonly timeStamp: number;
readonly type: string;
readonly scoped: boolean;
initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void;
preventDefault(): void;
stopImmediatePropagation(): void;
stopPropagation(): void;
deepPath(): EventTarget[];
readonly AT_TARGET: number;
readonly BUBBLING_PHASE: number;
readonly CAPTURING_PHASE: number;
@@ -298,6 +301,7 @@ interface FileReader extends EventTarget, MSBaseReader {
readAsBinaryString(blob: Blob): void;
readAsDataURL(blob: Blob): void;
readAsText(blob: Blob, encoding?: string): void;
addEventListener<K extends keyof MSBaseReaderEventMap>(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -339,11 +343,16 @@ declare var IDBCursorWithValue: {
new(): IDBCursorWithValue;
}
interface IDBDatabaseEventMap {
"abort": Event;
"error": ErrorEvent;
}
interface IDBDatabase extends EventTarget {
readonly name: string;
readonly objectStoreNames: string[];
onabort: (this: this, ev: Event) => any;
onerror: (this: this, ev: ErrorEvent) => any;
readonly objectStoreNames: DOMStringList;
onabort: (this: IDBDatabase, ev: Event) => any;
onerror: (this: IDBDatabase, ev: ErrorEvent) => any;
version: number;
onversionchange: (ev: IDBVersionChangeEvent) => any;
close(): void;
@@ -351,8 +360,7 @@ interface IDBDatabase extends EventTarget {
deleteObjectStore(name: string): void;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void;
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<K extends keyof IDBDatabaseEventMap>(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -407,7 +415,7 @@ declare var IDBKeyRange: {
}
interface IDBObjectStore {
readonly indexNames: string[];
readonly indexNames: DOMStringList;
keyPath: string | string[];
readonly name: string;
readonly transaction: IDBTransaction;
@@ -429,13 +437,15 @@ declare var IDBObjectStore: {
new(): IDBObjectStore;
}
interface IDBOpenDBRequestEventMap extends IDBRequestEventMap {
"blocked": Event;
"upgradeneeded": IDBVersionChangeEvent;
}
interface IDBOpenDBRequest extends IDBRequest {
onblocked: (this: this, ev: Event) => any;
onupgradeneeded: (this: this, ev: IDBVersionChangeEvent) => any;
addEventListener(type: "blocked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "upgradeneeded", listener: (this: this, ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void;
onblocked: (this: IDBOpenDBRequest, ev: Event) => any;
onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any;
addEventListener<K extends keyof IDBOpenDBRequestEventMap>(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -444,16 +454,20 @@ declare var IDBOpenDBRequest: {
new(): IDBOpenDBRequest;
}
interface IDBRequestEventMap {
"error": ErrorEvent;
"success": Event;
}
interface IDBRequest extends EventTarget {
readonly error: DOMError;
onerror: (this: this, ev: ErrorEvent) => any;
onsuccess: (this: this, ev: Event) => any;
onerror: (this: IDBRequest, ev: ErrorEvent) => any;
onsuccess: (this: IDBRequest, ev: Event) => any;
readonly readyState: string;
readonly result: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
readonly transaction: IDBTransaction;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener<K extends keyof IDBRequestEventMap>(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -462,21 +476,25 @@ declare var IDBRequest: {
new(): IDBRequest;
}
interface IDBTransactionEventMap {
"abort": Event;
"complete": Event;
"error": ErrorEvent;
}
interface IDBTransaction extends EventTarget {
readonly db: IDBDatabase;
readonly error: DOMError;
readonly mode: string;
onabort: (this: this, ev: Event) => any;
oncomplete: (this: this, ev: Event) => any;
onerror: (this: this, ev: ErrorEvent) => any;
onabort: (this: IDBTransaction, ev: Event) => any;
oncomplete: (this: IDBTransaction, ev: Event) => any;
onerror: (this: IDBTransaction, ev: ErrorEvent) => any;
abort(): void;
objectStore(name: string): IDBObjectStore;
readonly READ_ONLY: string;
readonly READ_WRITE: string;
readonly VERSION_CHANGE: string;
addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener<K extends keyof IDBTransactionEventMap>(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -533,18 +551,22 @@ interface MSApp {
}
declare var MSApp: MSApp;
interface MSAppAsyncOperationEventMap {
"complete": Event;
"error": ErrorEvent;
}
interface MSAppAsyncOperation extends EventTarget {
readonly error: DOMError;
oncomplete: (this: this, ev: Event) => any;
onerror: (this: this, ev: ErrorEvent) => any;
oncomplete: (this: MSAppAsyncOperation, ev: Event) => any;
onerror: (this: MSAppAsyncOperation, ev: ErrorEvent) => any;
readonly readyState: number;
readonly result: any;
start(): void;
readonly COMPLETED: number;
readonly ERROR: number;
readonly STARTED: number;
addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener<K extends keyof MSAppAsyncOperationEventMap>(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -584,6 +606,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader {
readAsBlob(stream: MSStream, size?: number): void;
readAsDataURL(stream: MSStream, size?: number): void;
readAsText(stream: MSStream, encoding?: string, size?: number): void;
addEventListener<K extends keyof MSBaseReaderEventMap>(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -627,12 +650,16 @@ declare var MessageEvent: {
new(type: string, eventInitDict?: MessageEventInit): MessageEvent;
}
interface MessagePortEventMap {
"message": MessageEvent;
}
interface MessagePort extends EventTarget {
onmessage: (this: this, ev: MessageEvent) => any;
onmessage: (this: MessagePort, ev: MessageEvent) => any;
close(): void;
postMessage(message?: any, ports?: any): void;
start(): void;
addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void;
addEventListener<K extends keyof MessagePortEventMap>(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -680,14 +707,21 @@ declare var ProgressEvent: {
new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent;
}
interface WebSocketEventMap {
"close": CloseEvent;
"error": ErrorEvent;
"message": MessageEvent;
"open": Event;
}
interface WebSocket extends EventTarget {
binaryType: string;
readonly bufferedAmount: number;
readonly extensions: string;
onclose: (this: this, ev: CloseEvent) => any;
onerror: (this: this, ev: ErrorEvent) => any;
onmessage: (this: this, ev: MessageEvent) => any;
onopen: (this: this, ev: Event) => any;
onclose: (this: WebSocket, ev: CloseEvent) => any;
onerror: (this: WebSocket, ev: ErrorEvent) => any;
onmessage: (this: WebSocket, ev: MessageEvent) => any;
onopen: (this: WebSocket, ev: Event) => any;
readonly protocol: string;
readonly readyState: number;
readonly url: string;
@@ -697,10 +731,7 @@ interface WebSocket extends EventTarget {
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
addEventListener(type: "close", listener: (this: this, ev: CloseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void;
addEventListener(type: "open", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -713,12 +744,15 @@ declare var WebSocket: {
readonly OPEN: number;
}
interface WorkerEventMap extends AbstractWorkerEventMap {
"message": MessageEvent;
}
interface Worker extends EventTarget, AbstractWorker {
onmessage: (this: this, ev: MessageEvent) => any;
onmessage: (this: Worker, ev: MessageEvent) => any;
postMessage(message: any, ports?: any): void;
terminate(): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void;
addEventListener<K extends keyof WorkerEventMap>(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -727,8 +761,12 @@ declare var Worker: {
new(stringUrl: string): Worker;
}
interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap {
"readystatechange": Event;
}
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
onreadystatechange: (this: this, ev: Event) => any;
onreadystatechange: (this: XMLHttpRequest, ev: Event) => any;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
@@ -755,14 +793,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
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: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "progress", 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<K extends keyof XMLHttpRequestEventMap>(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -778,6 +809,7 @@ declare var XMLHttpRequest: {
}
interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget {
addEventListener<K extends keyof XMLHttpRequestEventTargetEventMap>(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -786,31 +818,39 @@ declare var XMLHttpRequestUpload: {
new(): XMLHttpRequestUpload;
}
interface AbstractWorkerEventMap {
"error": ErrorEvent;
}
interface AbstractWorker {
onerror: (this: this, ev: ErrorEvent) => any;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
onerror: (this: AbstractWorker, ev: ErrorEvent) => any;
addEventListener<K extends keyof AbstractWorkerEventMap>(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
interface MSBaseReaderEventMap {
"abort": Event;
"error": ErrorEvent;
"load": Event;
"loadend": ProgressEvent;
"loadstart": Event;
"progress": ProgressEvent;
}
interface MSBaseReader {
onabort: (this: this, ev: Event) => any;
onerror: (this: this, ev: ErrorEvent) => any;
onload: (this: this, ev: Event) => any;
onloadend: (this: this, ev: ProgressEvent) => any;
onloadstart: (this: this, ev: Event) => any;
onprogress: (this: this, ev: ProgressEvent) => any;
onabort: (this: MSBaseReader, ev: Event) => any;
onerror: (this: MSBaseReader, ev: ErrorEvent) => any;
onload: (this: MSBaseReader, ev: Event) => any;
onloadend: (this: MSBaseReader, ev: ProgressEvent) => any;
onloadstart: (this: MSBaseReader, ev: Event) => any;
onprogress: (this: MSBaseReader, ev: ProgressEvent) => any;
readonly readyState: number;
readonly result: any;
abort(): void;
readonly DONE: number;
readonly EMPTY: number;
readonly LOADING: 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: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener<K extends keyof MSBaseReaderEventMap>(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -838,21 +878,25 @@ interface WindowConsole {
readonly console: Console;
}
interface XMLHttpRequestEventTargetEventMap {
"abort": Event;
"error": ErrorEvent;
"load": Event;
"loadend": ProgressEvent;
"loadstart": Event;
"progress": ProgressEvent;
"timeout": ProgressEvent;
}
interface XMLHttpRequestEventTarget {
onabort: (this: this, ev: Event) => any;
onerror: (this: this, ev: ErrorEvent) => any;
onload: (this: this, ev: Event) => any;
onloadend: (this: this, ev: ProgressEvent) => any;
onloadstart: (this: this, ev: Event) => any;
onprogress: (this: this, ev: ProgressEvent) => any;
ontimeout: (this: this, ev: ProgressEvent) => any;
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: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any;
onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any;
onload: (this: XMLHttpRequestEventTarget, ev: Event) => any;
onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any;
onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any;
onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any;
ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any;
addEventListener<K extends keyof XMLHttpRequestEventTargetEventMap>(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -868,15 +912,18 @@ declare var FileReaderSync: {
new(): FileReaderSync;
}
interface WorkerGlobalScopeEventMap extends DedicatedWorkerGlobalScopeEventMap {
"error": ErrorEvent;
}
interface WorkerGlobalScope extends EventTarget, WorkerUtils, DedicatedWorkerGlobalScope, WindowConsole {
readonly location: WorkerLocation;
onerror: (this: this, ev: ErrorEvent) => any;
onerror: (this: WorkerGlobalScope, ev: ErrorEvent) => any;
readonly self: WorkerGlobalScope;
close(): void;
msWriteProfilerMark(profilerMarkName: string): void;
toString(): string;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void;
addEventListener<K extends keyof WorkerGlobalScopeEventMap>(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -904,7 +951,6 @@ declare var WorkerLocation: {
interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine {
readonly hardwareConcurrency: number;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var WorkerNavigator: {
@@ -912,10 +958,14 @@ declare var WorkerNavigator: {
new(): WorkerNavigator;
}
interface DedicatedWorkerGlobalScopeEventMap {
"message": MessageEvent;
}
interface DedicatedWorkerGlobalScope {
onmessage: (this: this, ev: MessageEvent) => any;
onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any;
postMessage(data: any): void;
addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void;
addEventListener<K extends keyof DedicatedWorkerGlobalScopeEventMap>(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -1176,7 +1226,6 @@ declare var self: WorkerGlobalScope;
declare function close(): void;
declare function msWriteProfilerMark(profilerMarkName: string): void;
declare function toString(): string;
declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function dispatchEvent(evt: Event): boolean;
declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare var indexedDB: IDBFactory;
@@ -1197,8 +1246,7 @@ declare function btoa(rawString: string): string;
declare var onmessage: (this: WorkerGlobalScope, ev: MessageEvent) => any;
declare function postMessage(data: any): void;
declare var console: Console;
declare function addEventListener(type: "error", listener: (this: WorkerGlobalScope, ev: ErrorEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: "message", listener: (this: WorkerGlobalScope, ev: MessageEvent) => any, useCapture?: boolean): void;
declare function addEventListener<K extends keyof WorkerGlobalScopeEventMap>(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
type AlgorithmIdentifier = string | Algorithm;
type IDBKeyPath = string;
+1 -12
View File
@@ -5,15 +5,6 @@
namespace ts.server {
interface Hash {
update(data: any, input_encoding?: string): Hash;
digest(encoding: string): any;
}
const crypto: {
createHash(algorithm: string): Hash
} = require("crypto");
export function shouldEmitFile(scriptInfo: ScriptInfo) {
return !scriptInfo.hasMixedContent;
}
@@ -49,9 +40,7 @@ namespace ts.server {
}
private computeHash(text: string): string {
return crypto.createHash("md5")
.update(text)
.digest("base64");
return this.project.projectService.host.createHash(text);
}
private getSourceFile(): SourceFile {
+109 -33
View File
@@ -10,8 +10,26 @@
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[] } };
export const ContextEvent = "context";
export const ConfigFileDiagEvent = "configFileDiag";
export const ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
export interface ContextEvent {
eventName: typeof ContextEvent;
data: { project: Project; fileName: NormalizedPath };
}
export interface ConfigFileDiagEvent {
eventName: typeof ConfigFileDiagEvent;
data: { triggerFile: string, configFileName: string, diagnostics: Diagnostic[] };
}
export interface ProjectLanguageServiceStateEvent {
eventName: typeof ProjectLanguageServiceStateEvent;
data: { project: Project, languageServiceEnabled: boolean };
}
export type ProjectServiceEvent = ContextEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent;
export interface ProjectServiceEventHandler {
(event: ProjectServiceEvent): void;
@@ -239,7 +257,7 @@ namespace ts.server {
private changedFiles: ScriptInfo[];
private toCanonicalFileName: (f: string) => string;
readonly toCanonicalFileName: (f: string) => string;
public lastDeletedFile: ScriptInfo;
@@ -250,6 +268,8 @@ namespace ts.server {
readonly typingsInstaller: ITypingsInstaller = nullTypingsInstaller,
private readonly eventHandler?: ProjectServiceEventHandler) {
Debug.assert(!!host.createHash, "'ServerHost.createHash' is required for ProjectService");
this.toCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
this.directoryWatchers = new DirectoryWatchers(this);
this.throttledOperations = new ThrottledOperations(host);
@@ -280,16 +300,26 @@ namespace ts.server {
return this.compilerOptionsForInferredProjects;
}
onUpdateLanguageServiceStateForProject(project: Project, languageServiceEnabled: boolean) {
if (!this.eventHandler) {
return;
}
this.eventHandler(<ProjectLanguageServiceStateEvent>{
eventName: ProjectLanguageServiceStateEvent,
data: { project, languageServiceEnabled }
});
}
updateTypingsForProject(response: SetTypings | InvalidateCachedTypings): void {
const project = this.findProject(response.projectName);
if (!project) {
return;
}
switch (response.kind) {
case "set":
this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.unresolvedImports, response.typings);
case ActionSet:
this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings);
break;
case "invalidate":
case ActionInvalidate:
this.typingsCache.deleteTypingsForProject(response.projectName);
break;
}
@@ -428,7 +458,10 @@ namespace ts.server {
}
for (const openFile of this.openFiles) {
this.eventHandler({ eventName: "context", data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } });
this.eventHandler(<ContextEvent>{
eventName: ContextEvent,
data: { project: openFile.getDefaultProject(), fileName: openFile.fileName }
});
}
}
@@ -437,7 +470,7 @@ namespace ts.server {
private onTypeRootFileChanged(project: ConfiguredProject, fileName: string) {
this.logger.info(`Type root file ${fileName} changed`);
this.throttledOperations.schedule(project.configFileName + " * type root", /*delay*/ 250, () => {
this.throttledOperations.schedule(project.getConfigFilePath() + " * type root", /*delay*/ 250, () => {
project.updateTypes();
this.updateConfiguredProject(project); // TODO: Figure out why this is needed (should be redundant?)
this.refreshInferredProjects();
@@ -459,13 +492,13 @@ namespace ts.server {
this.logger.info(`Detected source file changes: ${fileName}`);
this.throttledOperations.schedule(
project.configFileName,
project.getConfigFilePath(),
/*delay*/250,
() => this.handleChangeInSourceFileForConfiguredProject(project, fileName));
}
private handleChangeInSourceFileForConfiguredProject(project: ConfiguredProject, triggerFile: string) {
const { projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.configFileName);
const { projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath());
this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors, triggerFile);
const newRootFiles = projectOptions.files.map((f => this.getCanonicalFileName(f)));
@@ -487,8 +520,10 @@ namespace ts.server {
}
private onConfigChangedForConfiguredProject(project: ConfiguredProject) {
this.logger.info(`Config file changed: ${project.configFileName}`);
this.updateConfiguredProject(project);
const configFileName = project.getConfigFilePath();
this.logger.info(`Config file changed: ${configFileName}`);
const configFileErrors = this.updateConfiguredProject(project);
this.reportConfigFileDiagnostics(configFileName, configFileErrors, /*triggerFile*/ configFileName);
this.refreshInferredProjects();
}
@@ -742,7 +777,13 @@ namespace ts.server {
}
private findConfiguredProjectByProjectName(configFileName: NormalizedPath) {
return findProjectByName(configFileName, this.configuredProjects);
// make sure that casing of config file name is consistent
configFileName = asNormalizedPath(this.toCanonicalFileName(configFileName));
for (const proj of this.configuredProjects) {
if (proj.canonicalConfigFilePath === configFileName) {
return proj;
}
}
}
private findExternalProjectByProjectName(projectFileName: string) {
@@ -788,7 +829,7 @@ namespace ts.server {
compilerOptions: parsedCommandLine.options,
configHasFilesProperty: config["files"] !== undefined,
wildcardDirectories: createMap(parsedCommandLine.wildcardDirectories),
typingOptions: parsedCommandLine.typingOptions,
typeAcquisition: parsedCommandLine.typeAcquisition,
compileOnSave: parsedCommandLine.compileOnSave
};
return { success: true, projectOptions, configFileErrors: errors };
@@ -812,7 +853,7 @@ namespace ts.server {
return false;
}
private createAndAddExternalProject(projectFileName: string, files: protocol.ExternalFile[], options: protocol.ExternalProjectCompilerOptions, typingOptions: TypingOptions) {
private createAndAddExternalProject(projectFileName: string, files: protocol.ExternalFile[], options: protocol.ExternalProjectCompilerOptions, typeAcquisition: TypeAcquisition) {
const compilerOptions = convertCompilerOptions(options);
const project = new ExternalProject(
projectFileName,
@@ -822,7 +863,7 @@ namespace ts.server {
/*languageServiceEnabled*/ !this.exceededTotalSizeLimitForNonTsFiles(compilerOptions, files, externalFilePropertyReader),
options.compileOnSave === undefined ? true : options.compileOnSave);
this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, /*clientFileName*/ undefined, typingOptions, /*configFileErrors*/ undefined);
this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, /*clientFileName*/ undefined, typeAcquisition, /*configFileErrors*/ undefined);
this.externalProjects.push(project);
return project;
}
@@ -832,8 +873,8 @@ namespace ts.server {
return;
}
this.eventHandler({
eventName: "configFileDiag",
this.eventHandler(<ConfigFileDiagEvent>{
eventName: ConfigFileDiagEvent,
data: { configFileName, diagnostics: diagnostics || [], triggerFile }
});
}
@@ -850,7 +891,7 @@ namespace ts.server {
/*languageServiceEnabled*/ !sizeLimitExceeded,
projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave);
this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions, configFileErrors);
this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typeAcquisition, configFileErrors);
project.watchConfigFile(project => this.onConfigChangedForConfiguredProject(project));
if (!sizeLimitExceeded) {
@@ -869,7 +910,7 @@ namespace ts.server {
}
}
private addFilesToProjectAndUpdateGraph<T>(project: ConfiguredProject | ExternalProject, files: T[], propertyReader: FilePropertyReader<T>, clientFileName: string, typingOptions: TypingOptions, configFileErrors: Diagnostic[]): void {
private addFilesToProjectAndUpdateGraph<T>(project: ConfiguredProject | ExternalProject, files: T[], propertyReader: FilePropertyReader<T>, clientFileName: string, typeAcquisition: TypeAcquisition, configFileErrors: Diagnostic[]): void {
let errors: Diagnostic[];
for (const f of files) {
const rootFilename = propertyReader.getFileName(f);
@@ -884,7 +925,7 @@ namespace ts.server {
}
}
project.setProjectErrors(concatenate(configFileErrors, errors));
project.setTypingOptions(typingOptions);
project.setTypeAcquisition(typeAcquisition);
project.updateGraph();
}
@@ -901,7 +942,7 @@ namespace ts.server {
};
}
private updateNonInferredProject<T>(project: ExternalProject | ConfiguredProject, newUncheckedFiles: T[], propertyReader: FilePropertyReader<T>, newOptions: CompilerOptions, newTypingOptions: TypingOptions, compileOnSave: boolean, configFileErrors: Diagnostic[]) {
private updateNonInferredProject<T>(project: ExternalProject | ConfiguredProject, newUncheckedFiles: T[], propertyReader: FilePropertyReader<T>, newOptions: CompilerOptions, newTypeAcquisition: TypeAcquisition, compileOnSave: boolean, configFileErrors: Diagnostic[]) {
const oldRootScriptInfos = project.getRootScriptInfos();
const newRootScriptInfos: ScriptInfo[] = [];
const newRootScriptInfoMap: NormalizedPathMap<ScriptInfo> = createNormalizedPathMap<ScriptInfo>();
@@ -963,7 +1004,7 @@ namespace ts.server {
}
project.setCompilerOptions(newOptions);
(<ExternalProject | ConfiguredProject>project).setTypingOptions(newTypingOptions);
(<ExternalProject | ConfiguredProject>project).setTypeAcquisition(newTypeAcquisition);
// VS only set the CompileOnSaveEnabled option in the request if the option was changed recently
// therefore if it is undefined, it should not be updated.
@@ -976,13 +1017,16 @@ namespace ts.server {
}
private updateConfiguredProject(project: ConfiguredProject) {
if (!this.host.fileExists(project.configFileName)) {
if (!this.host.fileExists(project.getConfigFilePath())) {
this.logger.info("Config file deleted");
this.removeProject(project);
return;
}
const { success, projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.configFileName);
// note: the returned "success" is true does not mean the "configFileErrors" is empty.
// because we might have tolerated the errors and kept going. So always return the configFileErrors
// regardless the "success" here is true or not.
const { success, projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath());
if (!success) {
// reset project settings to default
this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, /*compileOnSave*/false, configFileErrors);
@@ -993,7 +1037,7 @@ namespace ts.server {
project.setCompilerOptions(projectOptions.compilerOptions);
if (!project.languageServiceEnabled) {
// language service is already disabled
return;
return configFileErrors;
}
project.disableLanguageService();
project.stopWatchingDirectory();
@@ -1003,15 +1047,16 @@ namespace ts.server {
project.enableLanguageService();
}
this.watchConfigDirectoryForProject(project, projectOptions);
this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typingOptions, projectOptions.compileOnSave, configFileErrors);
this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave, configFileErrors);
}
return configFileErrors;
}
createInferredProjectWithRootFileIfNecessary(root: ScriptInfo) {
const useExistingProject = this.useSingleInferredProject && this.inferredProjects.length;
const project = useExistingProject
? this.inferredProjects[0]
: new InferredProject(this, this.documentRegistry, /*languageServiceEnabled*/ true, this.compilerOptionsForInferredProjects);
: new InferredProject(this, this.documentRegistry, this.compilerOptionsForInferredProjects);
project.addRoot(root);
@@ -1282,13 +1327,42 @@ namespace ts.server {
}
}
openExternalProject(proj: protocol.ExternalProject): void {
openExternalProjects(projects: protocol.ExternalProject[]): void {
// record project list before the update
const projectsToClose = arrayToMap(this.externalProjects, p => p.getProjectName(), _ => true);
for (const externalProjectName in this.externalProjectToConfiguredProjectMap) {
projectsToClose[externalProjectName] = true;
}
for (const externalProject of projects) {
this.openExternalProject(externalProject, /*suppressRefreshOfInferredProjects*/ true);
// delete project that is present in input list
delete projectsToClose[externalProject.projectFileName];
}
// close projects that were missing in the input list
for (const externalProjectName in projectsToClose) {
this.closeExternalProject(externalProjectName, /*suppressRefresh*/ true)
}
this.refreshInferredProjects();
}
openExternalProject(proj: protocol.ExternalProject, suppressRefreshOfInferredProjects = false): void {
// typingOptions has been deprecated and is only supported for backward compatibility
// purposes. It should be removed in future releases - use typeAcquisition instead.
if (proj.typingOptions && !proj.typeAcquisition) {
const typeAcquisition = convertEnableAutoDiscoveryToEnable(proj.typingOptions);
proj.typeAcquisition = typeAcquisition;
}
let tsConfigFiles: NormalizedPath[];
const rootFiles: protocol.ExternalFile[] = [];
for (const file of proj.rootFiles) {
const normalized = toNormalizedPath(file.fileName);
if (getBaseFileName(normalized) === "tsconfig.json") {
(tsConfigFiles || (tsConfigFiles = [])).push(normalized);
if (this.host.fileExists(normalized)) {
(tsConfigFiles || (tsConfigFiles = [])).push(normalized);
}
}
else {
rootFiles.push(file);
@@ -1305,7 +1379,7 @@ namespace ts.server {
if (externalProject) {
if (!tsConfigFiles) {
// external project already exists and not config files were added - update the project and return;
this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, convertCompilerOptions(proj.options), proj.typingOptions, proj.options.compileOnSave, /*configFileErrors*/ undefined);
this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, convertCompilerOptions(proj.options), proj.typeAcquisition, proj.options.compileOnSave, /*configFileErrors*/ undefined);
return;
}
// some config files were added to external project (that previously were not there)
@@ -1365,9 +1439,11 @@ namespace ts.server {
else {
// no config files - remove the item from the collection
delete this.externalProjectToConfiguredProjectMap[proj.projectFileName];
this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typingOptions);
this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition);
}
if (!suppressRefreshOfInferredProjects) {
this.refreshInferredProjects();
}
this.refreshInferredProjects();
}
}
}
+8 -3
View File
@@ -3,9 +3,9 @@
/// <reference path="scriptInfo.ts" />
namespace ts.server {
export class LSHost implements ts.LanguageServiceHost, ModuleResolutionHost, ServerLanguageServiceHost {
export class LSHost implements ts.LanguageServiceHost, ModuleResolutionHost {
private compilationSettings: ts.CompilerOptions;
private readonly resolvedModuleNames= createFileMap<Map<ResolvedModuleWithFailedLookupLocations>>();
private readonly resolvedModuleNames = createFileMap<Map<ResolvedModuleWithFailedLookupLocations>>();
private readonly resolvedTypeReferenceDirectives = createFileMap<Map<ResolvedTypeReferenceDirectiveWithFailedLookupLocations>>();
private readonly getCanonicalFileName: (fileName: string) => string;
@@ -13,6 +13,7 @@ namespace ts.server {
private readonly resolveModuleName: typeof resolveModuleName;
readonly trace: (s: string) => void;
readonly realpath?: (path: string) => string;
constructor(private readonly host: ServerHost, private readonly project: Project, private readonly cancellationToken: HostCancellationToken) {
this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames);
@@ -22,7 +23,7 @@ namespace ts.server {
}
this.resolveModuleName = (moduleName, containingFile, compilerOptions, host) => {
const globalCache = this.project.getTypingOptions().enableAutoDiscovery
const globalCache = this.project.getTypeAcquisition().enable
? this.project.projectService.typingsInstaller.globalTypingsCacheLocation
: undefined;
const primaryResult = resolveModuleName(moduleName, containingFile, compilerOptions, host);
@@ -39,6 +40,10 @@ namespace ts.server {
}
return primaryResult;
};
if (this.host.realpath) {
this.realpath = path => this.host.realpath(path);
}
}
public startRecordingFilesWithChangedResolutions() {
+179 -74
View File
@@ -90,16 +90,102 @@ namespace ts.server {
}
}
const emptyResult: any[] = [];
const getEmptyResult = () => emptyResult;
const getUndefined = () => <any>undefined;
const emptyEncodedSemanticClassifications = { spans: emptyResult, endOfLineState: EndOfLineState.None };
export function createNoSemanticFeaturesWrapper(realLanguageService: LanguageService): LanguageService {
return {
cleanupSemanticCache: noop,
getSyntacticDiagnostics: (fileName) =>
fileName ? realLanguageService.getSyntacticDiagnostics(fileName) : emptyResult,
getSemanticDiagnostics: getEmptyResult,
getCompilerOptionsDiagnostics: () =>
realLanguageService.getCompilerOptionsDiagnostics(),
getSyntacticClassifications: (fileName, span) =>
realLanguageService.getSyntacticClassifications(fileName, span),
getEncodedSyntacticClassifications: (fileName, span) =>
realLanguageService.getEncodedSyntacticClassifications(fileName, span),
getSemanticClassifications: getEmptyResult,
getEncodedSemanticClassifications: () =>
emptyEncodedSemanticClassifications,
getCompletionsAtPosition: getUndefined,
findReferences: getEmptyResult,
getCompletionEntryDetails: getUndefined,
getQuickInfoAtPosition: getUndefined,
findRenameLocations: getEmptyResult,
getNameOrDottedNameSpan: (fileName, startPos, endPos) =>
realLanguageService.getNameOrDottedNameSpan(fileName, startPos, endPos),
getBreakpointStatementAtPosition: (fileName, position) =>
realLanguageService.getBreakpointStatementAtPosition(fileName, position),
getBraceMatchingAtPosition: (fileName, position) =>
realLanguageService.getBraceMatchingAtPosition(fileName, position),
getSignatureHelpItems: getUndefined,
getDefinitionAtPosition: getEmptyResult,
getRenameInfo: () => ({
canRename: false,
localizedErrorMessage: getLocaleSpecificMessage(Diagnostics.Language_service_is_disabled),
displayName: undefined,
fullDisplayName: undefined,
kind: undefined,
kindModifiers: undefined,
triggerSpan: undefined
}),
getTypeDefinitionAtPosition: getUndefined,
getReferencesAtPosition: getEmptyResult,
getDocumentHighlights: getEmptyResult,
getOccurrencesAtPosition: getEmptyResult,
getNavigateToItems: getEmptyResult,
getNavigationBarItems: fileName =>
realLanguageService.getNavigationBarItems(fileName),
getNavigationTree: fileName =>
realLanguageService.getNavigationTree(fileName),
getOutliningSpans: fileName =>
realLanguageService.getOutliningSpans(fileName),
getTodoComments: getEmptyResult,
getIndentationAtPosition: (fileName, position, options) =>
realLanguageService.getIndentationAtPosition(fileName, position, options),
getFormattingEditsForRange: (fileName, start, end, options) =>
realLanguageService.getFormattingEditsForRange(fileName, start, end, options),
getFormattingEditsForDocument: (fileName, options) =>
realLanguageService.getFormattingEditsForDocument(fileName, options),
getFormattingEditsAfterKeystroke: (fileName, position, key, options) =>
realLanguageService.getFormattingEditsAfterKeystroke(fileName, position, key, options),
getDocCommentTemplateAtPosition: (fileName, position) =>
realLanguageService.getDocCommentTemplateAtPosition(fileName, position),
isValidBraceCompletionAtPosition: (fileName, position, openingBrace) =>
realLanguageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace),
getEmitOutput: getUndefined,
getProgram: () =>
realLanguageService.getProgram(),
getNonBoundSourceFile: fileName =>
realLanguageService.getNonBoundSourceFile(fileName),
dispose: () =>
realLanguageService.dispose(),
getCompletionEntrySymbol: getUndefined,
getImplementationAtPosition: getEmptyResult,
getSourceFile: fileName =>
realLanguageService.getSourceFile(fileName),
getCodeFixesAtPosition: getEmptyResult
};
}
export abstract class Project {
private rootFiles: ScriptInfo[] = [];
private rootFilesMap: FileMap<ScriptInfo> = createFileMap<ScriptInfo>();
private lsHost: ServerLanguageServiceHost;
private lsHost: LSHost;
private program: ts.Program;
private cachedUnresolvedImportsPerFile = new UnresolvedImportsMap();
private lastCachedUnresolvedImportsList: SortedReadonlyArray<string>;
private languageService: LanguageService;
private readonly languageService: LanguageService;
// wrapper over the real language service that will suppress all semantic operations
private readonly noSemanticFeaturesLanguageService: LanguageService;
public languageServiceEnabled = true;
builder: Builder;
/**
* Set of files that was returned from the last call to getChangesSinceVersion.
@@ -143,11 +229,12 @@ namespace ts.server {
}
constructor(
private readonly projectName: string,
readonly projectKind: ProjectKind,
readonly projectService: ProjectService,
private documentRegistry: ts.DocumentRegistry,
hasExplicitListOfFiles: boolean,
public languageServiceEnabled: boolean,
languageServiceEnabled: boolean,
private compilerOptions: CompilerOptions,
public compileOnSaveEnabled: boolean) {
@@ -161,10 +248,15 @@ namespace ts.server {
this.compilerOptions.allowNonTsExtensions = true;
}
if (languageServiceEnabled) {
this.enableLanguageService();
}
else {
this.setInternalCompilerOptionsForEmittingJsFiles();
this.lsHost = new LSHost(this.projectService.host, this, this.projectService.cancellationToken);
this.lsHost.setCompilationSettings(this.compilerOptions);
this.languageService = ts.createLanguageService(this.lsHost, this.documentRegistry);
this.noSemanticFeaturesLanguageService = createNoSemanticFeaturesWrapper(this.languageService);
if (!languageServiceEnabled) {
this.disableLanguageService();
}
@@ -172,6 +264,12 @@ namespace ts.server {
this.markAsDirty();
}
private setInternalCompilerOptionsForEmittingJsFiles() {
if (this.projectKind === ProjectKind.Inferred || this.projectKind === ProjectKind.External) {
this.compilerOptions.noEmitForJsFiles = true;
}
}
getProjectErrors() {
return this.projectErrors;
}
@@ -180,7 +278,9 @@ namespace ts.server {
if (ensureSynchronized) {
this.updateGraph();
}
return this.languageService;
return this.languageServiceEnabled
? this.languageService
: this.noSemanticFeaturesLanguageService;
}
getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[] {
@@ -196,23 +296,27 @@ namespace ts.server {
}
enableLanguageService() {
const lsHost = new LSHost(this.projectService.host, this, this.projectService.cancellationToken);
lsHost.setCompilationSettings(this.compilerOptions);
this.languageService = ts.createLanguageService(lsHost, this.documentRegistry);
this.lsHost = lsHost;
if (this.languageServiceEnabled) {
return;
}
this.languageServiceEnabled = true;
this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ true);
}
disableLanguageService() {
this.languageService = nullLanguageService;
this.lsHost = nullLanguageServiceHost;
if (!this.languageServiceEnabled) {
return;
}
this.languageService.cleanupSemanticCache();
this.languageServiceEnabled = false;
this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false);
}
abstract getProjectName(): string;
getProjectName() {
return this.projectName;
}
abstract getProjectRootPath(): string | undefined;
abstract getTypingOptions(): TypingOptions;
abstract getTypeAcquisition(): TypeAcquisition;
getSourceFile(path: Path) {
if (!this.program) {
@@ -297,7 +401,7 @@ namespace ts.server {
return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles);
}
getFileNames() {
getFileNames(excludeFilesFromExternalLibraries?: boolean) {
if (!this.program) {
return [];
}
@@ -313,8 +417,14 @@ namespace ts.server {
}
return rootFiles;
}
const sourceFiles = this.program.getSourceFiles();
return sourceFiles.map(sourceFile => asNormalizedPath(sourceFile.fileName));
const result: NormalizedPath[] = [];
for (const f of this.program.getSourceFiles()) {
if (excludeFilesFromExternalLibraries && this.program.isSourceFileFromExternalLibrary(f)) {
continue;
}
result.push(asNormalizedPath(f.fileName));
}
return result;
}
getAllEmittableFiles() {
@@ -531,6 +641,7 @@ namespace ts.server {
this.lastCachedUnresolvedImportsList = undefined;
}
this.compilerOptions = compilerOptions;
this.setInternalCompilerOptionsForEmittingJsFiles();
this.lsHost.setCompilationSettings(compilerOptions);
this.markAsDirty();
@@ -656,31 +767,27 @@ namespace ts.server {
export class InferredProject extends Project {
private static NextId = 1;
/**
* Unique name that identifies this particular inferred project
*/
private readonly inferredProjectName: string;
private static newName = (() => {
let nextId = 1;
return () => {
const id = nextId;
nextId++;
return makeInferredProjectName(id);
}
})();
// Used to keep track of what directories are watched for this project
directoriesWatchedForTsconfig: string[] = [];
constructor(projectService: ProjectService, documentRegistry: ts.DocumentRegistry, languageServiceEnabled: boolean, compilerOptions: CompilerOptions) {
super(ProjectKind.Inferred,
constructor(projectService: ProjectService, documentRegistry: ts.DocumentRegistry, compilerOptions: CompilerOptions) {
super(InferredProject.newName(),
ProjectKind.Inferred,
projectService,
documentRegistry,
/*files*/ undefined,
languageServiceEnabled,
/*languageServiceEnabled*/ true,
compilerOptions,
/*compileOnSaveEnabled*/ false);
this.inferredProjectName = makeInferredProjectName(InferredProject.NextId);
InferredProject.NextId++;
}
getProjectName() {
return this.inferredProjectName;
}
getProjectRootPath() {
@@ -700,9 +807,9 @@ namespace ts.server {
}
}
getTypingOptions(): TypingOptions {
getTypeAcquisition(): TypeAcquisition {
return {
enableAutoDiscovery: allRootFilesAreJsOrDts(this),
enable: allRootFilesAreJsOrDts(this),
include: [],
exclude: []
};
@@ -710,16 +817,17 @@ namespace ts.server {
}
export class ConfiguredProject extends Project {
private typingOptions: TypingOptions;
private typeAcquisition: TypeAcquisition;
private projectFileWatcher: FileWatcher;
private directoryWatcher: FileWatcher;
private directoriesWatchedForWildcards: Map<FileWatcher>;
private typeRootsWatchers: FileWatcher[];
readonly canonicalConfigFilePath: NormalizedPath;
/** Used for configured projects which may have multiple open roots */
openRefCount = 0;
constructor(readonly configFileName: NormalizedPath,
constructor(configFileName: NormalizedPath,
projectService: ProjectService,
documentRegistry: ts.DocumentRegistry,
hasExplicitListOfFiles: boolean,
@@ -727,31 +835,32 @@ namespace ts.server {
private wildcardDirectories: Map<WatchDirectoryFlags>,
languageServiceEnabled: boolean,
public compileOnSaveEnabled: boolean) {
super(ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled);
super(configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled);
this.canonicalConfigFilePath = asNormalizedPath(projectService.toCanonicalFileName(configFileName));
}
getConfigFilePath() {
return this.getProjectName();
}
getProjectRootPath() {
return getDirectoryPath(this.configFileName);
return getDirectoryPath(this.getConfigFilePath());
}
setProjectErrors(projectErrors: Diagnostic[]) {
this.projectErrors = projectErrors;
}
setTypingOptions(newTypingOptions: TypingOptions): void {
this.typingOptions = newTypingOptions;
setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void {
this.typeAcquisition = newTypeAcquisition;
}
getTypingOptions() {
return this.typingOptions;
}
getProjectName() {
return this.configFileName;
getTypeAcquisition() {
return this.typeAcquisition;
}
watchConfigFile(callback: (project: ConfiguredProject) => void) {
this.projectFileWatcher = this.projectService.host.watchFile(this.configFileName, _ => callback(this));
this.projectFileWatcher = this.projectService.host.watchFile(this.getConfigFilePath(), _ => callback(this));
}
watchTypeRoots(callback: (project: ConfiguredProject, path: string) => void) {
@@ -769,7 +878,7 @@ namespace ts.server {
return;
}
const directoryToWatch = getDirectoryPath(this.configFileName);
const directoryToWatch = getDirectoryPath(this.getConfigFilePath());
this.projectService.logger.info(`Add recursive watcher for: ${directoryToWatch}`);
this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, path => callback(this, path), /*recursive*/ true);
}
@@ -778,7 +887,7 @@ namespace ts.server {
if (!this.wildcardDirectories) {
return;
}
const configDirectoryPath = getDirectoryPath(this.configFileName);
const configDirectoryPath = getDirectoryPath(this.getConfigFilePath());
this.directoriesWatchedForWildcards = reduceProperties(this.wildcardDirectories, (watchers, flag, directory) => {
if (comparePaths(configDirectoryPath, directory, ".", !this.projectService.host.useCaseSensitiveFileNames) !== Comparison.EqualTo) {
const recursive = (flag & WatchDirectoryFlags.Recursive) !== 0;
@@ -837,15 +946,15 @@ namespace ts.server {
}
export class ExternalProject extends Project {
private typingOptions: TypingOptions;
constructor(readonly externalProjectName: string,
private typeAcquisition: TypeAcquisition;
constructor(externalProjectName: string,
projectService: ProjectService,
documentRegistry: ts.DocumentRegistry,
compilerOptions: CompilerOptions,
languageServiceEnabled: boolean,
public compileOnSaveEnabled: boolean,
private readonly projectFilePath?: string) {
super(ProjectKind.External, projectService, documentRegistry, /*hasExplicitListOfFiles*/ true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled);
super(externalProjectName, ProjectKind.External, projectService, documentRegistry, /*hasExplicitListOfFiles*/ true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled);
}
getProjectRootPath() {
@@ -855,43 +964,39 @@ namespace ts.server {
// if the projectFilePath is not given, we make the assumption that the project name
// is the path of the project file. AS the project name is provided by VS, we need to
// normalize slashes before using it as a file name.
return getDirectoryPath(normalizeSlashes(this.externalProjectName));
return getDirectoryPath(normalizeSlashes(this.getProjectName()));
}
getTypingOptions() {
return this.typingOptions;
getTypeAcquisition() {
return this.typeAcquisition;
}
setProjectErrors(projectErrors: Diagnostic[]) {
this.projectErrors = projectErrors;
}
setTypingOptions(newTypingOptions: TypingOptions): void {
if (!newTypingOptions) {
setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void {
if (!newTypeAcquisition) {
// set default typings options
newTypingOptions = {
enableAutoDiscovery: allRootFilesAreJsOrDts(this),
newTypeAcquisition = {
enable: allRootFilesAreJsOrDts(this),
include: [],
exclude: []
};
}
else {
if (newTypingOptions.enableAutoDiscovery === undefined) {
if (newTypeAcquisition.enable === undefined) {
// if autoDiscovery was not specified by the caller - set it based on the content of the project
newTypingOptions.enableAutoDiscovery = allRootFilesAreJsOrDts(this);
newTypeAcquisition.enable = allRootFilesAreJsOrDts(this);
}
if (!newTypingOptions.include) {
newTypingOptions.include = [];
if (!newTypeAcquisition.include) {
newTypeAcquisition.include = [];
}
if (!newTypingOptions.exclude) {
newTypingOptions.exclude = [];
if (!newTypeAcquisition.exclude) {
newTypeAcquisition.exclude = [];
}
}
this.typingOptions = newTypingOptions;
}
getProjectName() {
return this.externalProjectName;
this.typeAcquisition = newTypeAcquisition;
}
}
}
+96 -2
View File
@@ -861,9 +861,13 @@ namespace ts.server.protocol {
*/
options: ExternalProjectCompilerOptions;
/**
* Explicitly specified typing options for the project
* @deprecated typingOptions. Use typeAcquisition instead
*/
typingOptions?: TypingOptions;
typingOptions?: TypeAcquisition;
/**
* Explicitly specified type acquisition for the project
*/
typeAcquisition?: TypeAcquisition;
}
export interface CompileOnSaveMixin {
@@ -1814,6 +1818,27 @@ namespace ts.server.protocol {
event: "configFileDiag";
}
export type ProjectLanguageServiceStateEventName = "projectLanguageServiceState";
export interface ProjectLanguageServiceStateEvent extends Event {
event: ProjectLanguageServiceStateEventName;
body?: ProjectLanguageServiceStateEventBody;
}
export interface ProjectLanguageServiceStateEventBody {
/**
* Project name that has changes in the state of language service.
* For configured projects this will be the config file path.
* For external projects this will be the name of the projects specified when project was open.
* For inferred projects this event is not raised.
*/
projectName: string;
/**
* True if language service state switched from disabled to enabled
* and false otherwise.
*/
languageServiceEnabled: boolean;
}
/**
* Arguments for reload request.
*/
@@ -2057,6 +2082,75 @@ namespace ts.server.protocol {
childItems?: NavigationTree[];
}
export type TelemetryEventName = "telemetry";
export interface TelemetryEvent extends Event {
event: TelemetryEventName;
body: TelemetryEventBody;
}
export interface TelemetryEventBody {
telemetryEventName: string;
payload: any;
}
export type TypingsInstalledTelemetryEventName = "typingsInstalled";
export interface TypingsInstalledTelemetryEventBody extends TelemetryEventBody {
telemetryEventName: TypingsInstalledTelemetryEventName;
payload: TypingsInstalledTelemetryEventPayload;
}
export interface TypingsInstalledTelemetryEventPayload {
/**
* Comma separated list of installed typing packages
*/
installedPackages: string;
/**
* true if install request succeeded, otherwise - false
*/
installSuccess: boolean;
/**
* version of typings installer
*/
typingsInstallerVersion: string;
}
export type BeginInstallTypesEventName = "beginInstallTypes";
export type EndInstallTypesEventName = "endInstallTypes";
export interface BeginInstallTypesEvent extends Event {
event: BeginInstallTypesEventName;
body: BeginInstallTypesEventBody;
}
export interface EndInstallTypesEvent extends Event {
event: EndInstallTypesEventName;
body: EndInstallTypesEventBody;
}
export interface InstallTypesEventBody {
/**
* correlation id to match begin and end events
*/
eventId: number;
/**
* list of packages to install
*/
packages: ReadonlyArray<string>;
}
export interface BeginInstallTypesEventBody extends InstallTypesEventBody {
}
export interface EndInstallTypesEventBody extends InstallTypesEventBody {
/**
* true if installation succeeded, otherwise false
*/
success: boolean;
}
export interface NavBarResponse extends Response {
body?: NavigationBarItem[];
}

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