[Release-2.0] Merge master into Release-2.0 (#10347)

* Change getUnionType to default to no subtype reduction

* Remove unnecessary subtype reduction operations

* Use binary searching in union types to improve performance

* Optimize type inference

* Fixed broken singleAsteriskRegex. Fixes #9918 (#9920)

* Lock ts-node to 1.1.0 while perf issue is investigated (#9933)

* Fix typo in comment for MAX_SAFE_INTEGER

* In ts.performance.now, bind window.performance.now

Using an arrow function. Previously, it was set directly to
window.performance.now, which fails when used on Chrome.

* Add lint enforcing line endings (#9942)

* Add servicesSources to the list of prerequisites for running tests

* Support emitting static properties for classes with no name

* Add assertion whitespace lint rule (#9931)

* Add assertion whitespace lint rule

* Fix typo

* Add the word `Rule` to Jakefile

* Limit travis build matrix (#9968)

* Convert getErrorBaseline to use canonical diagnostic formatting (#9708)

* Convert getErrorBaseline to use canonical diagnostic formatting

* Fix lint

* Found another clone of format diagnostic - consolidate

* Fully declone

* Unify nodeKind implementations for navigationBar and navigateTo

* Fix test and rename a function

* Fix lint errors

* Remove hardcoded port, use the custom port

* Unlock ts-node version (#9960)

* Allow an abstract class to appear in a local scope

* JSDoc understands string literal types

Unfortunately, I didn't find a way to reuse the normal string literal
type, so I had to extend the existing JSDoc type hierarchy. Otherwise,
this feature is very simple.

* Update baselines to be current

* Add find and findIndex to ReadonlyArray

* The optional this should be readonly too.

* Update baseline source location

* Re-add concat overload to support inferring tuples

* Update baselines with new concat overload

* Update LastJSDoc[Tag]Node

* Display enum member types using qualified names

* Accept new baselines

* Fix lint error

* null/undefined are allowed as index expressions

`null` and `undefined` are not allowed with `--strictNullChecks` turned
on. Previously, they were disallowed whether or not it was on.

* Use correct nullable terminology

* Get rid of port parameter

* Remove [port] in usage message

* Properly reset type guards in loops

* Add regression test

* Introduce the `EntityNameExpression` type

* Allow `export =` and `export default` to alias any EntityNameExpression, not just identifiers.

* Lint tests helper files

* recreate program if baseUrl or paths changed in tsconfig

* Simplify some code

* Have travis use a newer image for the OSX build (#10034)

Suggested by travis support for stopping the randomly-halting-builds issue.

* Correctly check for ambient class flag

* Use "best choice type" for || and ?: operators

* jsx opening element formatting

* change error message for unused parameter property

fix

* Fix issue related to this and #8383

* Add additional tests

* Accept new baselines

* Provide `realpath` for module resolution in LSHost

* Add test

* Add test baselines

* Accept new baselines

* CR feedback

* Remove `SupportedExpressionWithTypeArguments` type; just check that the expression of each `ExpressionWithTypeArguments` is an `EntityNameExpression`.

* Fix bug

* Fix #10083 - allowSyntheticDefaultImports alters getExternalModuleMember (#10096)

* Use recursion, and fix error for undefined node

* Rename function

* Fix lint error

* Narrowing type parameter intersects w/narrowed types

This makes sure that a union type that includes a type parameter is
still usable as the actual type that the type guard narrows to.

* Add a helper function `getOrUpdateProperty` to prevent unprotected access to Maps.

* Limit type guards as assertions to incomplete types in loops

* Accept new baselines

* Fix linting error

* Allow JS multiple declarations of ctor properties

When a property is declared in the constructor and on the prototype of
an ES6 class, the property's symbol is discarded in favour of the
method's symbol. That because the usual use for this pattern is to bind
an instance function: `this.m = this.m.bind(this)`. In this case the
type you want really is the method's type.

* Use {} type facts for unconstrained type params

Previously it was using TypeFacts.All. But the constraint of an
unconstrained type parameter is actually {}.

* Fix newline lint

* Test that declares conflicting method first

* [Release-2.0] Fix 9662: Visual Studio 2015 with TS2.0 gives incorrect @types path resolution errors (#9867)

* Change the shape of the shim layer to support getAutomaticTypeDirectives

* Change the key for looking up automatic type-directives

* Update baselines from change look-up name of type-directives

* Add @currentDirectory into the test

* Update baselines

* Fix linting error

* Address PR: fix spelling mistake

* Instead of return path of the type directive names just return type directive names

* Remove unused reference files: these tests produce erros so they will not produce these files (#9233)

* Add string-literal completion test for jsdoc

* Support other (new) literal types in jsdoc

* Don't allow properties inherited from Object to be automatically included in TSX attributes

* Add new test baseline and delete else in binder

The extra `else` caused a ton of test failures!

* Fix lint

* Port PR #10016 to Master (#10100)

* Treat namespaceExportDeclaration as declaration

* Update baselines

* wip - add tests

* Add tests

* Show "export namespace" for quick-info

* Fix more lint

* Try using runtests-parallel for CI (#9970)

* Try using runtests-parallel for CI

* Put worker count setting into .travis.yml

* Reduce worker count to 4 - 8 wasnt much different from 4-6 but had contention issues causing timeouts

* Fix lssl task (#9967)

* Surface noErrorTruncation option

* Stricter check for discriminant properties in type guards

* Add tests

* Emit more efficient/concise "empty" ES6 ctor

When there are property assignments in a the class body of an inheriting
class, tsc current emit the following compilation:

```ts
class Foo extends Bar {
  public foo = 1;
}
```

```js
class Foo extends Bar {
  constructor(…args) {
    super(…args);
    this.foo = 1;
  }
}
```

This introduces an unneeded local variable and might force a reification
of the `arguments` object (or otherwise reify the arguments into an
array).

This is particularly bad when that output is fed into another transpiler
like Babel. In Babel, you get something like this today:


```js
var Foo = (function (_Bar) {
  _inherits(Foo, _Bar);

  function Foo() {
    _classCallCheck(this, Foo);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _Bar.call.apply(_Bar, [this].concat(args));
    this.foo = 1;
  }

  return Foo;
})(Bar);
```

This causes a lot of needless work/allocations and some very strange
code (`.call.apply` o_0).

Admittedly, this is not strictly tsc’s problem; it could have done a
deeper analysis of the code and optimized out the extra dance. However,
tsc could also have emitted this simpler, more concise and semantically
equivalent code in the first place:


```js
class Foo extends Bar {
  constructor() {
    super(…arguments);
    this.foo = 1;
  }
}
```

Which compiles into the following in Babel:

```js
var Foo = (function (_Bar) {
  _inherits(Foo, _Bar);

  function Foo() {
    _classCallCheck(this, Foo);

    _Bar.apply(this, arguments);
    this.foo = 1;
  }

  return Foo;
})(Bar);
```

Which is well-optimized (today) in most engines and much less confusing
to read.

As far as I can tell, the proposed compilation has exactly the same
semantics as before.

Fixes #10175

* Fix instanceof operator narrowing issues

* Accept new baselines

* Add regression test

* Improve naming and documentation from PR

* Update comment

* Add more tests

* Accept new baselines

* Reduce worker count to 3 (#10210)

Since we saw a starvation issue on one of @sandersn's PRs.

* Speed up fourslash tests

* Duh

* Make baselines faster by not writing out unneeded files

* Fix non-strict-compliant test

* Fix 10076: Fix Tuple Destructing with "this" (#10208)

* Call checkExpression eventhough there is no appropriate type from destructuring of array

* Add tests and baselines

* use transpileModule

* Remove use strict

* Improve instanceof for structurally identical types

* Introduce isTypeInstanceOf function

* Add test

* Accept new baselines

* Fix loop over array to use for-of instead of for-in

* Use correct this in tuple type parameter constraints

Instantiate this in tuple types used as type parameter constraints

* Add explanatory comment to resolveTupleTypeMembers

* Ignore null, undefined, void when checking for discriminant property

* Add regression test

* Delay tuple type constraint resolution

Create a new tuple that stores the this-type.

* Always use thisType when generating tuple id

* Optimize format of type list id strings used in maps

* Make ReadonlyArray iterable.

* Allow OSX to fail while we investigate (#10255)

The random test timeouts are an issue.

* avoid using the global name

* Fix single-quote lint

* Optimize performance of maps

* Update API sample

* Fix processDiagnosticMessages script

* Have travis take shallow clones of the repo (#10275)

Just cloning TS on travis takes 23 seconds on linux (68 seconds on mac), hopefully having it do a shallow clone will help.

We don't rely on any tagging/artifacts from the travis servers which clone depth could impact, so this shouldn't impact anything other than build speed.

* Add folds to travis log (#10269)

* Optimize filterType to only call getUnionType if necessary

* Add shorthand types declaration for travis-fold (#10293)

* Optimize getTypeWithFacts

* Filter out nullable and primitive types in isDiscriminantProperty

* Fix typo

* Add regression tests

* Optimize core filter function to only allocate when necessary

* Address CR comments + more optimizations

* Faster path for creating union types from filterType

* Allow an @types direcotry to have a package.json which specifies `"typings": null` to disclude it from automatically included typings.

* Lint

* Collect timing information for commands running on travis (#10308)

* Simplifies performance API

* Use 'MapLike' instead of 'Map' in 'preferConstRule.ts'.

* narrow from 'any' in most situations

instanceof and user-defined typeguards narrow from 'any' unless the narrowed-to type is exactly 'Object' or 'Function'. This is a breaking change.

* Update instanceof conformance tests

* accept new baselines

* add tests

* accept new baselines

* Use lowercase names for type reference directives

* Use proper response codes in web tests

* Treat ambient shorthand declarations as explicit uses of the `any` type

* Parallel linting (#10313)

* A perilous thing, a parallel lint

* Use work queue rather than scheduling work

* Dont read files for lint on main thread

* Fix style

* Fix the style fix (#10344)

* Aligned mark names with values used by ts-perf.

* Use an enum in checkClassForDuplicateDeclarations to aid readability

* Rename to Accessor

* Correctly update package.json version

* Migrated more MapLikes to Maps

* Add ES2015 Date constructor signature that accepts another Date (#10353)

* Parameters with no assignments implicitly considered const

* Add tests

* Migrate additional MapLikes to Maps.

* Fix 10625: JSX Not validating when index signature is present  (#10352)

* Check for type of property declaration before using index signature

* Add tests and baselines

* fix linting error

* Adding more comments

* Clean up/move some Map helper functions.

* Revert some formatting changes.

* Improve ReadonlyArray<T>.concat to match Array<T>

The Array-based signature was incorrect and also out-of-date.

* Fix link to blog

* Remove old assertion about when we're allowed to use fileExists

* Set isNewIdentifierLocation to true for JavaScript files

* Update error message for conflicting type definitions

Fixes #10370

* Explain why we lower-case type reference directives

* Correctly merge bindThisPropertyAssignment

Also simply it considerably after noticing that it's *only* called for
Javascript files, so there was a lot of dead code for TS cases that
never happened.

* Fix comment

* Property handle imcomplete control flow types in nested loops

* Update due to CR suggestion

* Add regression test

* Fix 10289: correctly generate tsconfig.json with --lib (#10355)

* Separate generate tsconfig into its own function and implement init with --lib

# Conflicts:
#	src/compiler/tsc.ts

* Add tests and baselines; Update function name

Add unittests and baselines
Add unittests and baselines for generating tsconfig

Move unittest into harness folder

Update harness tsconfig.json

USe correct function name

* Use new MapLike interstead. Update unittest

# Conflicts:
#	src/compiler/commandLineParser.ts

* Update JakeFile

* Add tests for incorrect cases

* Address PR : remove explicity write node_modules

* Add more tests for `export = foo.bar`.

* Output test baselines to tests/baselines/local instead of root
This commit is contained in:
Yui 2016-08-18 14:49:09 -07:00 committed by GitHub
parent 5d0e1994f4
commit 1d9124eb7c
896 changed files with 27734 additions and 37775 deletions

1
.gitignore vendored
View File

@ -17,6 +17,7 @@ tests/baselines/reference/projectOutput/*
tests/baselines/local/projectOutput/*
tests/services/baselines/prototyping/local/*
tests/services/browser/typescriptServices.js
scripts/authors.js
scripts/configureNightly.js
scripts/processDiagnosticMessages.d.ts
scripts/processDiagnosticMessages.js

146
.mailmap Normal file
View File

@ -0,0 +1,146 @@

Alexander <alexander@kuvaev.me># Alexander Kuvaev
AbubakerB <abubaker_bashir@hotmail.com> # Abubaker Bashir
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>
Alex Eagle <alexeagle@google.com>
Anders Hejlsberg <andersh@microsoft.com> unknown <andersh@AndersX1.NOE.Nokia.com> unknown <andersh@andersh-yoga.redmond.corp.microsoft.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>
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>
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
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>
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>
David Li <jiawei.davidli@gmail.com>
David Souther <davidsouther@gmail.com>
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>
Doug Ilijev <dilijev@users.noreply.github.com>
Erik Edrosa <erik.edrosa@gmail.com>
Ethan Rubio <ethanrubio@users.noreply.github.com>
Evan Martin <martine@danga.com>
Evan Sebastian <evanlhoini@gmail.com>
Eyas <eyas.sharaiha@gmail.com> # Eyas Sharaiha
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>
Gabriel Isenberg <gisenberg@gmail.com>
Gilad Peleg <giladp007@gmail.com>
Graeme Wicksted <graeme.wicksted@gmail.com>
Guillaume Salles <guillaume.salles@me.com>
Guy Bedford <guybedford@gmail.com> guybedford <guybedford@gmail.com>
Harald Niesche <harald@niesche.de>
Iain Monro <iain.monro@softwire.com>
Ingvar Stepanyan <me@rreverser.com>
impinball <impinball@gmail.com> # Isiah Meadows
Ivo Gabe de Wolff <ivogabe@ivogabe.nl>
James Whitney <james@whitney.io>
Jason Freeman <jfreeman@microsoft.com> Jason Freeman <JsonFreeman@users.noreply.github.com>
Jason Killian <jkillian@palantir.com>
Jason Ramsay <jasonra@microsoft.com> jramsay <jramsay@users.noreply.github.com>
Jed Mao <jed.hunsaker@gmail.com>
Jeffrey Morlan <jmmorlan@sonic.net>
tobisek <jiri@wix.com> # Jiri Tobisek
Johannes Rieken <jrieken@microsoft.com>
John Vilk <jvilk@cs.umass.edu>
jbondc <jbondc@gdesolutions.com> jbondc <jbondc@golnetwork.com> jbondc <jbondc@openmv.com> # Jonathan Bond-Caron
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 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>
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>
Kanchalai Tanglertsampan <yuisu@microsoft.com> Yui <yuit@users.noreply.github.com>
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>
kimamula <kenji.imamula@gmail.com> # Kenji Imamula
Kyle Kelley <rgbkrk@gmail.com>
Lorant Pinter <lorant.pinter@prezi.com>
Lucien Greathouse <me@lpghatguy.com>
Martin Vseticka <vseticka.martin@gmail.com> Martin Všeticka <vseticka.martin@gmail.com> MartyIX <vseticka.martin@gmail.com>
vvakame <vvakame+dev@gmail.com> # Masahiro Wakame
Matt McCutchen <rmccutch@mit.edu>
Max Deepfield <maxdeepfield@absolutefreakout.com>
Micah Zoltu <micah@zoltu.net>
Mohamed Hegazy <mhegazy@microsoft.com>
Nathan Shively-Sanders <nathansa@microsoft.com>
Nathan Yee <ny.nathan.yee@gmail.com>
Nima Zahedi <nima.zahedee@gmail.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>
Oskar Segersva¨rd <oskar.segersvard@widespace.com>
pcan <piero.cangianiello@gmail.com> # Piero Cangianiello
pcbro <2bux89+dk3zspjmuh16o@sharklasers.com> # @pcbro
Pedro Maltez <pedro@pedro.ac> # Pedro Maltez
piloopin <piloopin@gmail.com> # @piloopin
milkisevil <philip@milkisevil.com> # Philip Bulley
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>
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>
Sheetal Nandi <shkamat@microsoft.com>
Shengping Zhong <zhongsp@users.noreply.github.com>
shyyko.serhiy@gmail.com <shyyko.serhiy@gmail.com> # Shyyko Serhiy
Simon Hürlimann <simon.huerlimann@cyt.ch>
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>
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
Tim Perry <pimterry@gmail.com>
Tim Viiding-Spader <viispade@users.noreply.github.com>
Tingan Ho <tingan87@gmail.com>
togru <v3nomzxgt8@gmail.com> # togru
Tomas Grubliauskas <tgrubliauskas@gmail.com>
ToddThomson <achilles@telus.net> # Todd Thomson
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>
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>
zhongsp <patrick.zhongsp@gmail.com> # Patrick Zhong
T18970237136 <T18970237136@users.noreply.github.com> # @T18970237136
JBerger <JBerger@melco.com>

View File

@ -6,3 +6,34 @@ node_js:
- '0.10'
sudo: false
env:
- workerCount=3
matrix:
fast_finish: true
include:
- os: osx
node_js: stable
osx_image: xcode7.3
env: workerCount=2
allow_failures:
- os: osx
branches:
only:
- master
- transforms
install:
- npm uninstall typescript
- npm uninstall tslint
- npm install
- npm update
cache:
directories:
- node_modules
git:
depth: 1

View File

@ -1,105 +1,141 @@
TypeScript is authored by:
* Abubaker Bashir
* Adam Freidin
* Ahmad Farid
* Akshar Patel
* Adi Dahiya
* Ahmad Farid
* Alex Eagle
* Alexander Kuvaev
* Anders Hejlsberg
* Andrew Z Allen
* Andy Hanson
* Anil Anar
* Anton Tolmachev
* Arnav Singh
* Arthur Ozga
* Asad Saeeduddin
* Basarat Ali Syed
* Avery Morin
* Basarat Ali Syed
* Ben Duffield
* Bill Ticehurst
* Bill Ticehurst
* Blake Embrey
* Bowden Kelly
* Brett Mayen
* Bryan Forbes
* Caitlin Potter
* Bryan Forbes
* Caitlin Potter
* Chris Bubernak
* Colby Russell
* Chuck Jazdzewski
* Colby Russell
* Colin Snover
* Cyrus Najmabadi
* Dan Corder
* Dan Quirk
* Dan Quirk
* Daniel Rosenwasser
* @dashaus
* David Li
* David Li
* David Souther
* Denis Nedelyaev
* Dick van den Brink
* Dirk Bäumer
* Dirk Holtwick
* Doug Ilijev
* Erik Edrosa
* Ethan Rubio
* Evan Martin
* Evan Sebastian
* Eyas Sharaiha
* @falsandtru
* Frank Wallis
* Frank Wallis
* František Žiačik
* Gabriel Isenberg
* Gilad Peleg
* Gilad Peleg
* Graeme Wicksted
* Guillaume Salles
* Guillaume Salles
* Guy Bedford
* Harald Niesche
* Herrington Darkholme
* Iain Monro
* Ingvar Stepanyan
* Ivo Gabe de Wolff
* James Whitney
* Isiah Meadows
* Ivo Gabe de Wolff
* James Whitney
* Jason Freeman
* Jason Killian
* Jason Ramsay
* Jason Ramsay
* JBerger
* Jed Mao
* Jeffrey Morlan
* Johannes Rieken
* Jesse Schalken
* Jiri Tobisek
* Johannes Rieken
* John Vilk
* Jonathan Bond-Caron
* Jonathan Park
* Jonathan Toland
* Jonathan Turner
* Jonathon Smith
* Josh Kalderimis
* Josh Soref
* Juan Luis Boya García
* Julian Williams
* Kagami Sascha Rosylight
* Kanchalai Tanglertsampan
* Keith Mashinter
* Ken Howard
* Kenji Imamula
* Lorant Pinter
* Kyle Kelley
* Lorant Pinter
* Lucien Greathouse
* Martin Všetička
* Martin Vseticka
* Masahiro Wakame
* Mattias Buelens
* Matt McCutchen
* Max Deepfield
* Micah Zoltu
* Mohamed Hegazy
* Micah Zoltu
* Mohamed Hegazy
* Nathan Shively-Sanders
* Nathan Yee
* Nima Zahedi
* Noj Vek
* Oleg Mihailik
* Oleksandr Chekhovskyi
* Paul van Brenk
* Oleksandr Chekhovskyi
* Oskar Segersva¨rd
* Patrick Zhong
* Paul van Brenk
* @pcbro
* Pedro Maltez
* Pedro Maltez
* Philip Bulley
* piloopin
* Piero Cangianiello
* @piloopin
* Prayag Verma
* @progre
* Punya Biswal
* Richard Sentino
* Ron Buckton
* Rado Kirov
* Richard Knoll
* Ron Buckton
* Rowan Wyborn
* Ryan Cavanaugh
* Ryan Cavanaugh
* Ryohei Ikegami
* Sébastien Arod
* Sarangan Rajamanickam
* Sheetal Nandi
* Shengping Zhong
* Shyyko Serhiy
* Simon Hürlimann
* Solal Pirelli
* Stan Thomas
* Stanislav Sysoev
* Steve Lucco
* Thomas Loubiou
* Sébastien Arod
* @T18970237136
* Tarik Ozket
* Tien Hoanhtien
* Tim Perry
* Tim Viiding-Spader
* Tingan Ho
* Todd Thomson
* togru
* Tomas Grubliauskas
* TruongSinh Tran-Nguyen
* Viliv Vane
* Vilic Vane
* Vladimir Matveev
* Wesley Wigham
* York Yao
* Yui Tanglertsampan
* Yuichi Nukiyama
* Zev Spitz
* Zhengbo Li
* Zev Spitz
* Zhengbo Li

View File

@ -1,6 +1,4 @@
/// <reference path="scripts/types/ambient.d.ts" />
/// <reference types="q" />
import * as cp from "child_process";
import * as path from "path";
import * as fs from "fs";
@ -13,17 +11,19 @@ import newer = require("gulp-newer");
import tsc = require("gulp-typescript");
declare module "gulp-typescript" {
interface Settings {
stripInternal?: boolean;
pretty?: boolean;
newLine?: string;
noImplicitThis?: boolean;
stripInternal?: boolean;
types?: string[];
}
interface CompileStream extends NodeJS.ReadWriteStream {} // Either gulp or gulp-typescript has some odd typings which don't reflect reality, making this required
interface CompileStream extends NodeJS.ReadWriteStream { } // Either gulp or gulp-typescript has some odd typings which don't reflect reality, making this required
}
import * as insert from "gulp-insert";
import * as sourcemaps from "gulp-sourcemaps";
import Q = require("q");
declare global {
// This is silly. We include Q because orchestrator (a part of gulp) depends on it, but its not included.
// `del` further depends on `Promise` (and is also not included), so we just, patch the global scope's Promise to Q's
// `del` further depends on `Promise` (and is also not included), so we just, patch the global scope's Promise to Q's (which we already include in our deps because gulp depends on it)
type Promise<T> = Q.Promise<T>;
}
import del = require("del");
@ -34,7 +34,7 @@ import through2 = require("through2");
import merge2 = require("merge2");
import intoStream = require("into-stream");
import * as os from "os";
import Linter = require("tslint");
import fold = require("travis-fold");
const gulp = helpMaker(originalGulp);
const mochaParallel = require("./scripts/mocha-parallel.js");
const {runTestsInParallel} = mochaParallel;
@ -59,14 +59,13 @@ const cmdLineOptions = minimist(process.argv.slice(2), {
browser: process.env.browser || process.env.b || "IE",
tests: process.env.test || process.env.tests || process.env.t,
light: process.env.light || false,
port: process.env.port || process.env.p || "8888",
reporter: process.env.reporter || process.env.r,
lint: process.env.lint || true,
files: process.env.f || process.env.file || process.env.files || "",
}
});
function exec(cmd: string, args: string[], complete: () => void = (() => {}), error: (e: any, status: number) => void = (() => {})) {
function exec(cmd: string, args: string[], complete: () => void = (() => { }), error: (e: any, status: number) => void = (() => { })) {
console.log(`${cmd} ${args.join(" ")}`);
// TODO (weswig): Update child_process types to add windowsVerbatimArguments to the type definition
const subshellFlag = isWin ? "/c" : "-c";
@ -85,12 +84,9 @@ let host = cmdLineOptions["host"];
// Constants
const compilerDirectory = "src/compiler/";
const servicesDirectory = "src/services/";
const serverDirectory = "src/server/";
const harnessDirectory = "src/harness/";
const libraryDirectory = "src/lib/";
const scriptsDirectory = "scripts/";
const unittestsDirectory = "tests/cases/unittests/";
const docDirectory = "doc/";
const builtDirectory = "built/";
@ -107,69 +103,6 @@ const nodeModulesPathPrefix = path.resolve("./node_modules/.bin/");
const isWin = /^win/.test(process.platform);
const mocha = path.join(nodeModulesPathPrefix, "mocha") + (isWin ? ".cmd" : "");
const compilerSources = require("./src/compiler/tsconfig.json").files.map((file) => path.join(compilerDirectory, file));
const servicesSources = require("./src/services/tsconfig.json").files.map((file) => path.join(servicesDirectory, file));
const serverCoreSources = require("./src/server/tsconfig.json").files.map((file) => path.join(serverDirectory, file));
const languageServiceLibrarySources = [
"editorServices.ts",
"protocol.d.ts",
"session.ts"
].map(function (f) {
return path.join(serverDirectory, f);
}).concat(servicesSources);
const harnessCoreSources = [
"harness.ts",
"sourceMapRecorder.ts",
"harnessLanguageService.ts",
"fourslash.ts",
"runnerbase.ts",
"compilerRunner.ts",
"typeWriter.ts",
"fourslashRunner.ts",
"projectsRunner.ts",
"loggedIO.ts",
"rwcRunner.ts",
"test262Runner.ts",
"runner.ts"
].map(function (f) {
return path.join(harnessDirectory, f);
});
const harnessSources = harnessCoreSources.concat([
"incrementalParser.ts",
"jsDocParsing.ts",
"services/colorization.ts",
"services/documentRegistry.ts",
"services/preProcessFile.ts",
"services/patternMatcher.ts",
"session.ts",
"versionCache.ts",
"convertToBase64.ts",
"transpile.ts",
"reuseProgramStructure.ts",
"cachingInServerLSHost.ts",
"moduleResolution.ts",
"tsconfigParsing.ts",
"commandLineParsing.ts",
"convertCompilerOptionsFromJson.ts",
"convertTypingOptionsFromJson.ts",
"tsserverProjectSystem.ts",
"matchFiles.ts",
].map(function (f) {
return path.join(unittestsDirectory, f);
})).concat([
"protocol.d.ts",
"session.ts",
"client.ts",
"editorServices.ts"
].map(function (f) {
return path.join(serverDirectory, f);
}));
const es2015LibrarySources = [
"es2015.core.d.ts",
"es2015.collection.d.ts",
@ -183,12 +116,12 @@ const es2015LibrarySources = [
];
const es2015LibrarySourceMap = es2015LibrarySources.map(function(source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
return { target: "lib." + source, sources: ["header.d.ts", source] };
});
const es2016LibrarySource = [ "es2016.array.include.d.ts" ];
const es2016LibrarySource = ["es2016.array.include.d.ts"];
const es2016LibrarySourceMap = es2016LibrarySource.map(function (source) {
const es2016LibrarySourceMap = es2016LibrarySource.map(function(source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
});
@ -197,38 +130,38 @@ const es2017LibrarySource = [
"es2017.sharedmemory.d.ts"
];
const es2017LibrarySourceMap = es2017LibrarySource.map(function (source) {
const es2017LibrarySourceMap = es2017LibrarySource.map(function(source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
});
const hostsLibrarySources = ["dom.generated.d.ts", "webworker.importscripts.d.ts", "scripthost.d.ts"];
const librarySourceMap = [
// Host library
{ target: "lib.dom.d.ts", sources: ["header.d.ts", "dom.generated.d.ts"] },
{ target: "lib.dom.iterable.d.ts", sources: ["header.d.ts", "dom.iterable.d.ts"] },
{ target: "lib.webworker.d.ts", sources: ["header.d.ts", "webworker.generated.d.ts"] },
{ target: "lib.scripthost.d.ts", sources: ["header.d.ts", "scripthost.d.ts"] },
// Host library
{ target: "lib.dom.d.ts", sources: ["header.d.ts", "dom.generated.d.ts"] },
{ target: "lib.dom.iterable.d.ts", sources: ["header.d.ts", "dom.iterable.d.ts"] },
{ target: "lib.webworker.d.ts", sources: ["header.d.ts", "webworker.generated.d.ts"] },
{ target: "lib.scripthost.d.ts", sources: ["header.d.ts", "scripthost.d.ts"] },
// JavaScript library
{ target: "lib.es5.d.ts", sources: ["header.d.ts", "es5.d.ts"] },
{ target: "lib.es2015.d.ts", sources: ["header.d.ts", "es2015.d.ts"] },
{ target: "lib.es2016.d.ts", sources: ["header.d.ts", "es2016.d.ts"] },
{ target: "lib.es2017.d.ts", sources: ["header.d.ts", "es2017.d.ts"] },
// JavaScript library
{ target: "lib.es5.d.ts", sources: ["header.d.ts", "es5.d.ts"] },
{ target: "lib.es2015.d.ts", sources: ["header.d.ts", "es2015.d.ts"] },
{ target: "lib.es2016.d.ts", sources: ["header.d.ts", "es2016.d.ts"] },
{ target: "lib.es2017.d.ts", sources: ["header.d.ts", "es2017.d.ts"] },
// JavaScript + all host library
{ target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources) },
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") }
// JavaScript + all host library
{ target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources) },
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") }
].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap);
const libraryTargets = librarySourceMap.map(function (f) {
const libraryTargets = librarySourceMap.map(function(f) {
return path.join(builtLocalDirectory, f.target);
});
for (const i in libraryTargets) {
const entry = librarySourceMap[i];
const target = libraryTargets[i];
const sources = [copyright].concat(entry.sources.map(function (s) {
const sources = [copyright].concat(entry.sources.map(function(s) {
return path.join(libraryDirectory, s);
}));
gulp.task(target, false, [], function() {
@ -309,6 +242,11 @@ function needsUpdate(source: string | string[], dest: string | string[]): boolea
function getCompilerSettings(base: tsc.Settings, useBuiltCompiler?: boolean): tsc.Settings {
const copy: tsc.Settings = {};
copy.noEmitOnError = true;
copy.noImplicitAny = true;
copy.noImplicitThis = true;
copy.pretty = true;
copy.types = [];
for (const key in base) {
copy[key] = base[key];
}
@ -453,7 +391,7 @@ gulp.task(servicesFile, false, ["lib", "generate-diagnostics"], () => {
.pipe(sourcemaps.init())
.pipe(tsc(servicesProject));
const completedJs = js.pipe(prependCopyright())
.pipe(sourcemaps.write("."));
.pipe(sourcemaps.write("."));
const completedDts = dts.pipe(prependCopyright(/*outputCopyright*/true))
.pipe(insert.transform((contents, file) => {
file.path = standaloneDefinitionsFile;
@ -495,26 +433,23 @@ const tsserverLibraryFile = path.join(builtLocalDirectory, "tsserverlibrary.js")
const tsserverLibraryDefinitionFile = path.join(builtLocalDirectory, "tsserverlibrary.d.ts");
gulp.task(tsserverLibraryFile, false, [servicesFile], (done) => {
const settings: tsc.Settings = getCompilerSettings({
declaration: true,
outFile: tsserverLibraryFile
}, /*useBuiltCompiler*/ true);
const {js, dts}: {js: NodeJS.ReadableStream, dts: NodeJS.ReadableStream} = gulp.src(languageServiceLibrarySources)
const serverLibraryProject = tsc.createProject("src/server/tsconfig.library.json", getCompilerSettings({}, /*useBuiltCompiler*/ true));
const {js, dts}: { js: NodeJS.ReadableStream, dts: NodeJS.ReadableStream } = serverLibraryProject.src()
.pipe(sourcemaps.init())
.pipe(newer(tsserverLibraryFile))
.pipe(tsc(settings));
.pipe(tsc(serverLibraryProject));
return merge2([
js.pipe(prependCopyright())
.pipe(sourcemaps.write("."))
.pipe(gulp.dest(".")),
.pipe(sourcemaps.write("."))
.pipe(gulp.dest(builtLocalDirectory)),
dts.pipe(prependCopyright())
.pipe(gulp.dest("."))
.pipe(gulp.dest(builtLocalDirectory))
]);
});
gulp.task("lssl", "Builds language service server library", [tsserverLibraryFile]);
gulp.task("local", "Builds the full compiler and services", [builtLocalCompiler, servicesFile, serverFile, builtGeneratedDiagnosticMessagesJSON]);
gulp.task("local", "Builds the full compiler and services", [builtLocalCompiler, servicesFile, serverFile, builtGeneratedDiagnosticMessagesJSON, tsserverLibraryFile]);
gulp.task("tsc", "Builds only the compiler", [builtLocalCompiler]);
@ -541,7 +476,7 @@ gulp.task(specMd, false, [word2mdJs], (done) => {
const specMDFullPath = path.resolve(specMd);
const cmd = "cscript //nologo " + word2mdJs + " \"" + specWordFullPath + "\" " + "\"" + specMDFullPath + "\"";
console.log(cmd);
cp.exec(cmd, function () {
cp.exec(cmd, function() {
done();
});
});
@ -557,18 +492,18 @@ gulp.task("dontUseDebugMode", false, [], (done) => { useDebugMode = false; done(
gulp.task("VerifyLKG", false, [], () => {
const expectedFiles = [builtLocalCompiler, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile].concat(libraryTargets);
const missingFiles = expectedFiles.filter(function (f) {
const missingFiles = expectedFiles.filter(function(f) {
return !fs.existsSync(f);
});
if (missingFiles.length > 0) {
throw new Error("Cannot replace the LKG unless all built targets are present in directory " + builtLocalDirectory +
". The following files are missing:\n" + missingFiles.join("\n"));
". The following files are missing:\n" + missingFiles.join("\n"));
}
// Copy all the targets into the LKG directory
return gulp.src(expectedFiles).pipe(gulp.dest(LKGDirectory));
});
gulp.task("LKGInternal", false, ["lib", "local", "lssl"]);
gulp.task("LKGInternal", false, ["lib", "local"]);
gulp.task("LKG", "Makes a new LKG out of the built js files", ["clean", "dontUseDebugMode"], () => {
return runSequence("LKGInternal", "VerifyLKG");
@ -578,15 +513,13 @@ gulp.task("LKG", "Makes a new LKG out of the built js files", ["clean", "dontUse
// Task to build the tests infrastructure using the built compiler
const run = path.join(builtLocalDirectory, "run.js");
gulp.task(run, false, [servicesFile], () => {
const settings: tsc.Settings = getCompilerSettings({
outFile: run
}, /*useBuiltCompiler*/ true);
return gulp.src(harnessSources)
const testProject = tsc.createProject("src/harness/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/true));
return testProject.src()
.pipe(newer(run))
.pipe(sourcemaps.init())
.pipe(tsc(settings))
.pipe(tsc(testProject))
.pipe(sourcemaps.write(".", { includeContent: false, sourceRoot: "../../" }))
.pipe(gulp.dest("."));
.pipe(gulp.dest(builtLocalDirectory));
});
const internalTests = "internal/";
@ -598,8 +531,6 @@ const localRwcBaseline = path.join(internalTests, "baselines/rwc/local");
const refRwcBaseline = path.join(internalTests, "baselines/rwc/reference");
const localTest262Baseline = path.join(internalTests, "baselines/test262/local");
const refTest262Baseline = path.join(internalTests, "baselines/test262/reference");
gulp.task("tests", "Builds the test infrastructure using the built compiler", [run]);
gulp.task("tests-debug", "Builds the test sources and automation in debug mode", () => {
@ -694,7 +625,7 @@ function runConsoleTests(defaultReporter: string, runInParallel: boolean, done:
}
args.push(run);
setNodeEnvToDevelopment();
runTestsInParallel(taskConfigsFolder, run, { testTimeout: testTimeout, noColors: colors === " --no-colors " }, function (err) {
runTestsInParallel(taskConfigsFolder, run, { testTimeout: testTimeout, noColors: colors === " --no-colors " }, function(err) {
// last worker clean everything and runs linter in case if there were no errors
del(taskConfigsFolder).then(() => {
if (!err) {
@ -746,7 +677,7 @@ gulp.task("runtests",
["build-rules", "tests"],
(done) => {
runConsoleTests("mocha-fivemat-progress-reporter", /*runInParallel*/ false, done);
});
});
const nodeServerOutFile = "tests/webTestServer.js";
const nodeServerInFile = "tests/webTestServer.ts";
@ -760,23 +691,50 @@ gulp.task(nodeServerOutFile, false, [servicesFile], () => {
.pipe(gulp.dest(path.dirname(nodeServerOutFile)));
});
import convertMap = require("convert-source-map");
import sorcery = require("sorcery");
declare module "convert-source-map" {
export function fromSource(source: string, largeSource?: boolean): SourceMapConverter;
}
gulp.task("browserify", "Runs browserify on run.js to produce a file suitable for running tests in the browser", [servicesFile], (done) => {
const settings: tsc.Settings = getCompilerSettings({
outFile: "built/local/bundle.js"
}, /*useBuiltCompiler*/ true);
return gulp.src(harnessSources)
const testProject = tsc.createProject("src/harness/tsconfig.json", getCompilerSettings({ outFile: "built/local/bundle.js" }, /*useBuiltCompiler*/ true));
return testProject.src()
.pipe(newer("built/local/bundle.js"))
.pipe(sourcemaps.init())
.pipe(tsc(settings))
.pipe(tsc(testProject))
.pipe(through2.obj((file, enc, next) => {
browserify(intoStream(file.contents))
const originalMap = file.sourceMap;
const prebundledContent = file.contents.toString();
// Make paths absolute to help sorcery deal with all the terrible paths being thrown around
originalMap.sources = originalMap.sources.map(s => path.resolve("src", s));
// intoStream (below) makes browserify think the input file is named this, so this is what it puts in the sourcemap
originalMap.file = "built/local/_stream_0.js";
browserify(intoStream(file.contents), { debug: true })
.bundle((err, res) => {
// assumes file.contents is a Buffer
file.contents = res;
const maps = JSON.parse(convertMap.fromSource(res.toString(), /*largeSource*/true).toJSON());
delete maps.sourceRoot;
maps.sources = maps.sources.map(s => path.resolve(s === "_stream_0.js" ? "built/local/_stream_0.js" : s));
// Strip browserify's inline comments away (could probably just let sorcery do this, but then we couldn't fix the paths)
file.contents = new Buffer(convertMap.removeComments(res.toString()));
const chain = sorcery.loadSync("built/local/bundle.js", {
content: {
"built/local/_stream_0.js": prebundledContent,
"built/local/bundle.js": file.contents.toString()
},
sourcemaps: {
"built/local/_stream_0.js": originalMap,
"built/local/bundle.js": maps,
}
});
const finalMap = chain.apply();
file.sourceMap = finalMap;
next(undefined, file);
});
}))
.pipe(sourcemaps.write(".", { includeContent: false, sourceRoot: "../../" }))
.pipe(sourcemaps.write(".", { includeContent: false }))
.pipe(gulp.dest("."));
});
@ -805,7 +763,7 @@ function writeTestConfigFile(tests: string, light: boolean, taskConfigsFolder?:
}
gulp.task("runtests-browser", "Runs the tests using the built run.js file like 'gulp runtests'. Syntax is gulp runtests-browser. Additional optional parameters --tests=[regex], --port=, --browser=[chrome|IE]", ["browserify", nodeServerOutFile], (done) => {
gulp.task("runtests-browser", "Runs the tests using the built run.js file like 'gulp runtests'. Syntax is gulp runtests-browser. Additional optional parameters --tests=[regex], --browser=[chrome|IE]", ["browserify", nodeServerOutFile], (done) => {
cleanTestDirs((err) => {
if (err) { console.error(err); done(err); process.exit(1); }
host = "node";
@ -820,9 +778,6 @@ gulp.task("runtests-browser", "Runs the tests using the built run.js file like '
}
const args = [nodeServerOutFile];
if (cmdLineOptions["port"]) {
args.push(cmdLineOptions["port"]);
}
if (cmdLineOptions["browser"]) {
args.push(cmdLineOptions["browser"]);
}
@ -854,32 +809,36 @@ gulp.task("diff-rwc", "Diffs the RWC baselines using the diff tool specified by
exec(getDiffTool(), [refRwcBaseline, localRwcBaseline], done, done);
});
gulp.task("baseline-accept", "Makes the most recent test results the new baseline, overwriting the old baseline", () => {
return baselineAccept("");
});
function baselineAccept(subfolder = "") {
return merge2(baselineCopy(subfolder), baselineDelete(subfolder));
}
function baselineCopy(subfolder = "") {
return gulp.src([`tests/baselines/local/${subfolder}/**`, `!tests/baselines/local/${subfolder}/**/*.delete`])
.pipe(gulp.dest(refBaseline));
}
function baselineDelete(subfolder = "") {
return gulp.src(["tests/baselines/local/**/*.delete"])
.pipe(insert.transform((content, fileObj) => {
const target = path.join(refBaseline, fileObj.relative.substr(0, fileObj.relative.length - ".delete".length));
del.sync(target);
del.sync(fileObj.path);
return "";
}));
}
gulp.task("baseline-accept", "Makes the most recent test results the new baseline, overwriting the old baseline", (done) => {
const softAccept = cmdLineOptions["soft"];
if (!softAccept) {
del(refBaseline).then(() => {
fs.renameSync(localBaseline, refBaseline);
done();
}, done);
}
else {
gulp.src(localBaseline)
.pipe(gulp.dest(refBaseline))
.on("end", () => {
del(path.join(refBaseline, "local")).then(() => done(), done);
});
}
});
gulp.task("baseline-accept-rwc", "Makes the most recent rwc test results the new baseline, overwriting the old baseline", () => {
return del(refRwcBaseline).then(() => {
fs.renameSync(localRwcBaseline, refRwcBaseline);
});
return baselineAccept("rwc");
});
gulp.task("baseline-accept-test262", "Makes the most recent test262 test results the new baseline, overwriting the old baseline", () => {
return del(refTest262Baseline).then(() => {
fs.renameSync(localTest262Baseline, refTest262Baseline);
});
return baselineAccept("test262");
});
@ -957,87 +916,97 @@ gulp.task("update-sublime", "Updates the sublime plugin's tsserver", ["local", s
return gulp.src([serverFile, serverFile + ".map"]).pipe(gulp.dest("../TypeScript-Sublime-Plugin/tsserver/"));
});
gulp.task("build-rules", "Compiles tslint rules to js", () => {
const settings: tsc.Settings = getCompilerSettings({ module: "commonjs" }, /*useBuiltCompiler*/ false);
const dest = path.join(builtLocalDirectory, "tslint");
return gulp.src("scripts/tslint/**/*.ts")
.pipe(newer({
dest,
ext: ".js"
}))
.pipe(sourcemaps.init())
.pipe(tsc(settings))
.pipe(sourcemaps.write("."))
.pipe(gulp.dest(dest));
});
const tslintRuleDir = "scripts/tslint";
const tslintRules = [
"nextLineRule",
"preferConstRule",
"booleanTriviaRule",
"typeOperatorSpacingRule",
"noInOperatorRule",
"noIncrementDecrementRule",
"objectLiteralSurroundingSpaceRule",
const lintTargets = [
"Gulpfile.ts",
"src/compiler/**/*.ts",
"src/harness/**/*.ts",
"!src/harness/unittests/services/formatting/**/*.ts",
"src/server/**/*.ts",
"scripts/tslint/**/*.ts",
"src/services/**/*.ts",
"tests/*.ts", "tests/webhost/*.ts" // Note: does *not* descend recursively
];
const tslintRulesFiles = tslintRules.map(function(p) {
return path.join(tslintRuleDir, p + ".ts");
});
const tslintRulesOutFiles = tslintRules.map(function(p, i) {
const pathname = path.join(builtLocalDirectory, "tslint", p + ".js");
gulp.task(pathname, false, [], () => {
const settings: tsc.Settings = getCompilerSettings({ module: "commonjs" }, /*useBuiltCompiler*/ false);
return gulp.src(tslintRulesFiles[i])
.pipe(newer(pathname))
.pipe(sourcemaps.init())
.pipe(tsc(settings))
.pipe(sourcemaps.write("."))
.pipe(gulp.dest(path.join(builtLocalDirectory, "tslint")));
function sendNextFile(files: {path: string}[], child: cp.ChildProcess, callback: (failures: number) => void, failures: number) {
const file = files.pop();
if (file) {
console.log(`Linting '${file.path}'.`);
child.send({ kind: "file", name: file.path });
}
else {
child.send({ kind: "close" });
callback(failures);
}
}
function spawnLintWorker(files: {path: string}[], callback: (failures: number) => void) {
const child = cp.fork("./scripts/parallel-lint");
let failures = 0;
child.on("message", function(data) {
switch (data.kind) {
case "result":
if (data.failures > 0) {
failures += data.failures;
console.log(data.output);
}
sendNextFile(files, child, callback, failures);
break;
case "error":
console.error(data.error);
failures++;
sendNextFile(files, child, callback, failures);
break;
}
});
return pathname;
});
gulp.task("build-rules", "Compiles tslint rules to js", tslintRulesOutFiles);
function getLinterOptions() {
return {
configuration: require("./tslint.json"),
formatter: "prose",
formattersDirectory: undefined,
rulesDirectory: "built/local/tslint"
};
sendNextFile(files, child, callback, failures);
}
function lintFileContents(options, path, contents) {
const ll = new Linter(path, contents, options);
console.log("Linting '" + path + "'.");
return ll.lint();
}
function lintFile(options, path) {
const contents = fs.readFileSync(path, "utf8");
return lintFileContents(options, path, contents);
}
const lintTargets = ["Gulpfile.ts"]
.concat(compilerSources)
.concat(harnessSources)
// Other harness sources
.concat(["instrumenter.ts"].map(function(f) { return path.join(harnessDirectory, f); }))
.concat(serverCoreSources)
.concat(tslintRulesFiles)
.concat(servicesSources);
gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are: --f[iles]=regex", ["build-rules"], () => {
const lintOptions = getLinterOptions();
let failed = 0;
const fileMatcher = RegExp(cmdLineOptions["files"]);
const done = {};
for (const i in lintTargets) {
const target = lintTargets[i];
if (!done[target] && fileMatcher.test(target)) {
const result = lintFile(lintOptions, target);
if (result.failureCount > 0) {
console.log(result.output);
failed += result.failureCount;
if (fold.isTravis()) console.log(fold.start("lint"));
let files: {stat: fs.Stats, path: string}[] = [];
return gulp.src(lintTargets, { read: false })
.pipe(through2.obj((chunk, enc, cb) => {
files.push(chunk);
cb();
}, (cb) => {
files = files.filter(file => fileMatcher.test(file.path)).sort((filea, fileb) => filea.stat.size - fileb.stat.size);
const workerCount = (process.env.workerCount && +process.env.workerCount) || os.cpus().length;
for (let i = 0; i < workerCount; i++) {
spawnLintWorker(files, finished);
}
done[target] = true;
}
}
if (failed > 0) {
console.error("Linter errors.");
process.exit(1);
}
let completed = 0;
let failures = 0;
function finished(fails) {
completed++;
failures += fails;
if (completed === workerCount) {
if (fold.isTravis()) console.log(fold.end("lint"));
if (failures > 0) {
throw new Error(`Linter errors: ${failures}`);
}
else {
cb();
}
}
}
}));
});

View File

@ -4,7 +4,7 @@ var fs = require("fs");
var os = require("os");
var path = require("path");
var child_process = require("child_process");
var Linter = require("tslint");
var fold = require("travis-fold");
var runTestsInParallel = require("./scripts/mocha-parallel").runTestsInParallel;
// Variables
@ -14,7 +14,7 @@ var serverDirectory = "src/server/";
var harnessDirectory = "src/harness/";
var libraryDirectory = "src/lib/";
var scriptsDirectory = "scripts/";
var unittestsDirectory = "tests/cases/unittests/";
var unittestsDirectory = "src/harness/unittests/";
var docDirectory = "doc/";
var builtDirectory = "built/";
@ -32,8 +32,31 @@ if (process.env.path !== undefined) {
process.env.PATH = nodeModulesPathPrefix + process.env.PATH;
}
function toNs(diff) {
return diff[0] * 1e9 + diff[1];
}
function mark() {
if (!fold.isTravis()) return;
var stamp = process.hrtime();
var id = Math.floor(Math.random() * 0xFFFFFFFF).toString(16);
console.log("travis_time:start:" + id + "\r");
return {
stamp: stamp,
id: id
};
}
function measure(marker) {
if (!fold.isTravis()) return;
var diff = process.hrtime(marker.stamp);
var total = [marker.stamp[0] + diff[0], marker.stamp[1] + diff[1]];
console.log("travis_time:end:" + marker.id + ":start=" + toNs(marker.stamp) + ",finish=" + toNs(total) + ",duration=" + toNs(diff) + "\r");
}
var compilerSources = [
"core.ts",
"performance.ts",
"sys.ts",
"types.ts",
"scanner.ts",
@ -54,6 +77,7 @@ var compilerSources = [
var servicesSources = [
"core.ts",
"performance.ts",
"sys.ts",
"types.ts",
"scanner.ts",
@ -100,7 +124,6 @@ var servicesSources = [
}));
var serverCoreSources = [
"node.d.ts",
"editorServices.ts",
"protocol.d.ts",
"session.ts",
@ -157,7 +180,8 @@ var harnessSources = harnessCoreSources.concat([
"convertCompilerOptionsFromJson.ts",
"convertTypingOptionsFromJson.ts",
"tsserverProjectSystem.ts",
"matchFiles.ts"
"matchFiles.ts",
"initializeTSConfig.ts",
].map(function (f) {
return path.join(unittestsDirectory, f);
})).concat([
@ -279,13 +303,19 @@ var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
* @param {boolean} opts.stripInternal: true if compiler should remove declarations marked as @internal
* @param {boolean} opts.noMapRoot: true if compiler omit mapRoot option
* @param {boolean} opts.inlineSourceMap: true if compiler should inline sourceMap
* @param {Array} opts.types: array of types to include in compilation
* @param callback: a function to execute after the compilation process ends
*/
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts, callback) {
file(outFile, prereqs, function() {
var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler;
var options = "--noImplicitAny --noEmitOnError --types --pretty";
var startCompileTime = mark();
opts = opts || {};
var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler;
var options = "--noImplicitAny --noImplicitThis --noEmitOnError --types "
if (opts.types) {
options += opts.types.join(",");
}
options += " --pretty";
// Keep comments when specifically requested
// or when in debug mode.
if (!(opts.keepComments || useDebugMode)) {
@ -355,11 +385,13 @@ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts
callback();
}
measure(startCompileTime);
complete();
});
ex.addListener("error", function() {
fs.unlinkSync(outFile);
fail("Compilation of " + outFile + " unsuccessful");
measure(startCompileTime);
});
ex.run();
}, {async: true});
@ -462,15 +494,6 @@ task("publish-nightly", ["configure-nightly", "LKG", "clean", "setDebugMode", "r
exec(cmd);
});
var scriptsTsdJson = path.join(scriptsDirectory, "tsd.json");
file(scriptsTsdJson);
task("tsd-scripts", [scriptsTsdJson], function () {
var cmd = "tsd --config " + scriptsTsdJson + " install";
console.log(cmd);
exec(cmd);
}, { async: true });
var importDefinitelyTypedTestsDirectory = path.join(scriptsDirectory, "importDefinitelyTypedTests");
var importDefinitelyTypedTestsJs = path.join(importDefinitelyTypedTestsDirectory, "importDefinitelyTypedTests.js");
var importDefinitelyTypedTestsTs = path.join(importDefinitelyTypedTestsDirectory, "importDefinitelyTypedTests.ts");
@ -548,14 +571,13 @@ compileFile(
});
var serverFile = path.join(builtLocalDirectory, "tsserver.js");
compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true);
compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, { types: ["node"] });
var tsserverLibraryFile = path.join(builtLocalDirectory, "tsserverlibrary.js");
var tsserverLibraryDefinitionFile = path.join(builtLocalDirectory, "tsserverlibrary.d.ts");
compileFile(
tsserverLibraryFile,
languageServiceLibrarySources,
[builtLocalDirectory, copyright].concat(languageServiceLibrarySources),
[builtLocalDirectory, copyright, builtLocalCompiler].concat(languageServiceLibrarySources).concat(libraryTargets),
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
{ noOutFile: false, generateDeclarations: true });
@ -564,9 +586,19 @@ compileFile(
desc("Builds language service server library");
task("lssl", [tsserverLibraryFile, tsserverLibraryDefinitionFile]);
desc("Emit the start of the build fold");
task("build-fold-start", [] , function() {
if (fold.isTravis()) console.log(fold.start("build"));
});
desc("Emit the end of the build fold");
task("build-fold-end", [] , function() {
if (fold.isTravis()) console.log(fold.end("build"));
});
// Local target to build the compiler and services
desc("Builds the full compiler and services");
task("local", ["generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile, builtGeneratedDiagnosticMessagesJSON]);
task("local", ["build-fold-start", "generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile, builtGeneratedDiagnosticMessagesJSON, "lssl", "build-fold-end"]);
// Local target to build only tsc.js
desc("Builds only the compiler");
@ -621,7 +653,7 @@ task("generate-spec", [specMd]);
// Makes a new LKG. This target does not build anything, but errors if not all the outputs are present in the built/local directory
desc("Makes a new LKG out of the built js files");
task("LKG", ["clean", "release", "local", "lssl"].concat(libraryTargets), function() {
task("LKG", ["clean", "release", "local"].concat(libraryTargets), function() {
var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile].concat(libraryTargets);
var missingFiles = expectedFiles.filter(function (f) {
return !fs.existsSync(f);
@ -649,10 +681,10 @@ var run = path.join(builtLocalDirectory, "run.js");
compileFile(
/*outFile*/ run,
/*source*/ harnessSources,
/*prereqs*/ [builtLocalDirectory, tscFile].concat(libraryTargets).concat(harnessSources),
/*prereqs*/ [builtLocalDirectory, tscFile].concat(libraryTargets).concat(servicesSources).concat(harnessSources),
/*prefixes*/ [],
/*useBuiltCompiler:*/ true,
/*opts*/ { inlineSourceMap: true });
/*opts*/ { inlineSourceMap: true, types: ["node", "mocha", "chai"] });
var internalTests = "internal/";
@ -762,6 +794,7 @@ function runConsoleTests(defaultReporter, runInParallel) {
// timeout normally isn't necessary but Travis-CI has been timing out on compiler baselines occasionally
// default timeout is 2sec which really should be enough, but maybe we just need a small amount longer
if(!runInParallel) {
var startTime = mark();
tests = tests ? ' -g "' + tests + '"' : '';
var cmd = "mocha" + (debug ? " --debug-brk" : "") + " -R " + reporter + tests + colors + bail + ' -t ' + testTimeout + ' ' + run;
console.log(cmd);
@ -770,10 +803,12 @@ function runConsoleTests(defaultReporter, runInParallel) {
process.env.NODE_ENV = "development";
exec(cmd, function () {
process.env.NODE_ENV = savedNodeEnv;
measure(startTime);
runLinter();
finish();
}, function(e, status) {
process.env.NODE_ENV = savedNodeEnv;
measure(startTime);
finish(status);
});
@ -781,9 +816,10 @@ function runConsoleTests(defaultReporter, runInParallel) {
else {
var savedNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
var startTime = mark();
runTestsInParallel(taskConfigsFolder, run, { testTimeout: testTimeout, noColors: colors === " --no-colors " }, function (err) {
process.env.NODE_ENV = savedNodeEnv;
measure(startTime);
// last worker clean everything and runs linter in case if there were no errors
deleteTemporaryProjectOutput();
jake.rmRf(taskConfigsFolder);
@ -851,11 +887,10 @@ task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function()
exec(cmd);
}, {async: true});
desc("Runs the tests using the built run.js file like 'jake runtests'. Syntax is jake runtests-browser. Additional optional parameters tests=[regex], port=, browser=[chrome|IE]");
desc("Runs the tests using the built run.js file like 'jake runtests'. Syntax is jake runtests-browser. Additional optional parameters tests=[regex], browser=[chrome|IE]");
task("runtests-browser", ["tests", "browserify", builtLocalDirectory, servicesFileInBrowserTest], function() {
cleanTestDirs();
host = "node";
port = process.env.port || process.env.p || '8888';
browser = process.env.browser || process.env.b || "IE";
tests = process.env.test || process.env.tests || process.env.t;
var light = process.env.light || false;
@ -868,7 +903,7 @@ task("runtests-browser", ["tests", "browserify", builtLocalDirectory, servicesFi
}
tests = tests ? tests : '';
var cmd = host + " tests/webTestServer.js " + port + " " + browser + " " + JSON.stringify(tests);
var cmd = host + " tests/webTestServer.js " + browser + " " + JSON.stringify(tests);
console.log(cmd);
exec(cmd);
}, {async: true});
@ -903,16 +938,16 @@ 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(hardOrSoft) {
if (!hardOrSoft || hardOrSoft === "hard") {
jake.rmRf(refBaseline);
fs.renameSync(localBaseline, refBaseline);
}
else if (hardOrSoft === "soft") {
var files = jake.readdirR(localBaseline);
for (var i in files) {
var files = jake.readdirR(localBaseline);
var deleteEnding = '.delete';
for (var i in files) {
if (files[i].substr(files[i].length - deleteEnding.length) === deleteEnding) {
var filename = path.basename(files[i]);
filename = filename.substr(0, filename.length - deleteEnding.length);
fs.unlink(path.join(refBaseline, filename));
} else {
jake.cpR(files[i], refBaseline);
}
jake.rmRf(path.join(refBaseline, "local"));
}
});
@ -994,6 +1029,7 @@ var tslintRules = [
"noInOperatorRule",
"noIncrementDecrementRule",
"objectLiteralSurroundingSpaceRule",
"noTypeAssertionWhitespaceRule"
];
var tslintRulesFiles = tslintRules.map(function(p) {
return path.join(tslintRuleDir, p + ".ts");
@ -1002,41 +1038,21 @@ var tslintRulesOutFiles = tslintRules.map(function(p) {
return path.join(builtLocalDirectory, "tslint", p + ".js");
});
desc("Compiles tslint rules to js");
task("build-rules", tslintRulesOutFiles);
task("build-rules", ["build-rules-start"].concat(tslintRulesOutFiles).concat(["build-rules-end"]));
tslintRulesFiles.forEach(function(ruleFile, i) {
compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false,
{ noOutFile: true, generateDeclarations: false, outDir: path.join(builtLocalDirectory, "tslint")});
});
function getLinterOptions() {
return {
configuration: require("./tslint.json"),
formatter: "prose",
formattersDirectory: undefined,
rulesDirectory: "built/local/tslint"
};
}
desc("Emit the start of the build-rules fold");
task("build-rules-start", [] , function() {
if (fold.isTravis()) console.log(fold.start("build-rules"));
});
function lintFileContents(options, path, contents) {
var ll = new Linter(path, contents, options);
console.log("Linting '" + path + "'.");
return ll.lint();
}
function lintFile(options, path) {
var contents = fs.readFileSync(path, "utf8");
return lintFileContents(options, path, contents);
}
function lintFileAsync(options, path, cb) {
fs.readFile(path, "utf8", function(err, contents) {
if (err) {
return cb(err);
}
var result = lintFileContents(options, path, contents);
cb(undefined, result);
});
}
desc("Emit the end of the build-rules fold");
task("build-rules-end", [] , function() {
if (fold.isTravis()) console.log(fold.end("build-rules"));
});
var lintTargets = compilerSources
.concat(harnessSources)
@ -1045,73 +1061,81 @@ var lintTargets = compilerSources
.concat(serverCoreSources)
.concat(tslintRulesFiles)
.concat(servicesSources)
.concat(["Gulpfile.ts"]);
.concat(["Gulpfile.ts"])
.concat([nodeServerInFile, perftscPath, "tests/perfsys.ts", webhostPath]);
function sendNextFile(files, child, callback, failures) {
var file = files.pop();
if (file) {
console.log("Linting '" + file + "'.");
child.send({kind: "file", name: file});
}
else {
child.send({kind: "close"});
callback(failures);
}
}
function spawnLintWorker(files, callback) {
var child = child_process.fork("./scripts/parallel-lint");
var failures = 0;
child.on("message", function(data) {
switch (data.kind) {
case "result":
if (data.failures > 0) {
failures += data.failures;
console.log(data.output);
}
sendNextFile(files, child, callback, failures);
break;
case "error":
console.error(data.error);
failures++;
sendNextFile(files, child, callback, failures);
break;
}
});
sendNextFile(files, child, callback, failures);
}
desc("Runs tslint on the compiler sources. Optional arguments are: f[iles]=regex");
task("lint", ["build-rules"], function() {
var lintOptions = getLinterOptions();
if (fold.isTravis()) console.log(fold.start("lint"));
var startTime = mark();
var failed = 0;
var fileMatcher = RegExp(process.env.f || process.env.file || process.env.files || "");
var done = {};
for (var i in lintTargets) {
var target = lintTargets[i];
if (!done[target] && fileMatcher.test(target)) {
var result = lintFile(lintOptions, target);
if (result.failureCount > 0) {
console.log(result.output);
failed += result.failureCount;
}
done[target] = true;
done[target] = fs.statSync(target).size;
}
}
if (failed > 0) {
fail('Linter errors.', failed);
}
});
/**
* This is required because file watches on Windows get fires _twice_
* when a file changes on some node/windows version configuations
* (node v4 and win 10, for example). By not running a lint for a file
* which already has a pending lint, we avoid duplicating our work.
* (And avoid printing duplicate results!)
*/
var lintSemaphores = {};
var workerCount = (process.env.workerCount && +process.env.workerCount) || os.cpus().length;
function lintWatchFile(filename) {
fs.watch(filename, {persistent: true}, function(event) {
if (event !== "change") {
return;
}
if (!lintSemaphores[filename]) {
lintSemaphores[filename] = true;
lintFileAsync(getLinterOptions(), filename, function(err, result) {
delete lintSemaphores[filename];
if (err) {
console.log(err);
return;
}
if (result.failureCount > 0) {
console.log("***Lint failure***");
for (var i = 0; i < result.failures.length; i++) {
var failure = result.failures[i];
var start = failure.startPosition.lineAndCharacter;
var end = failure.endPosition.lineAndCharacter;
console.log("warning " + filename + " (" + (start.line + 1) + "," + (start.character + 1) + "," + (end.line + 1) + "," + (end.character + 1) + "): " + failure.failure);
}
console.log("*** Total " + result.failureCount + " failures.");
}
});
}
var names = Object.keys(done).sort(function(namea, nameb) {
return done[namea] - done[nameb];
});
}
desc("Watches files for changes to rerun a lint pass");
task("lint-server", ["build-rules"], function() {
console.log("Watching ./src for changes to linted files");
for (var i = 0; i < lintTargets.length; i++) {
lintWatchFile(lintTargets[i]);
for (var i = 0; i < workerCount; i++) {
spawnLintWorker(names, finished);
}
});
var completed = 0;
var failures = 0;
function finished(fails) {
completed++;
failures += fails;
if (completed === workerCount) {
measure(startTime);
if (fold.isTravis()) console.log(fold.end("lint"));
if (failures > 0) {
fail('Linter errors.', failed);
}
else {
complete();
}
}
}
}, {async: true});

View File

@ -6,7 +6,7 @@
[![Join the chat at https://gitter.im/Microsoft/TypeScript](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Microsoft/TypeScript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[TypeScript](http://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](http://www.typescriptlang.org/Playground), and stay up to date via [our blog](http://blogs.msdn.com/typescript) and [Twitter account](https://twitter.com/typescriptlang).
[TypeScript](http://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](http://www.typescriptlang.org/Playground), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescriptlang).
## Installing

2
lib/lib.d.ts vendored
View File

@ -987,7 +987,7 @@ interface JSON {
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer An array of strings and numbers that acts as a white list for selecting the object properties that will be stringified.
* @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;

2
lib/lib.es5.d.ts vendored
View File

@ -987,7 +987,7 @@ interface JSON {
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer An array of strings and numbers that acts as a white list for selecting the object properties that will be stringified.
* @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;

2
lib/lib.es6.d.ts vendored
View File

@ -987,7 +987,7 @@ interface JSON {
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer An array of strings and numbers that acts as a white list for selecting the object properties that will be stringified.
* @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;

View File

@ -825,10 +825,17 @@ var ts;
return true;
}
ts.containsPath = containsPath;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
function fileExtensionIs(path, extension) {
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
return path.length > extension.length && endsWith(path, extension);
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@ -1093,6 +1100,8 @@ var ts;
}
ts.objectAllocator = {
getNodeConstructor: function () { return Node; },
getTokenConstructor: function () { return Node; },
getIdentifierConstructor: function () { return Node; },
getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
@ -1224,7 +1233,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
return {
var wscriptSystem = {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@ -1243,7 +1252,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!wscriptSystem.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@ -1263,6 +1272,7 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@ -1435,7 +1445,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); });
}
return {
var nodeSystem = {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@ -1485,7 +1495,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@ -1533,6 +1543,7 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@ -2282,8 +2293,8 @@ var ts;
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
@ -4836,7 +4847,7 @@ var ts;
}
ts.isExpression = isExpression;
function isExternalModuleNameRelative(moduleName) {
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
return /^\.\.?($|[\\/])/.test(moduleName);
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@ -6344,25 +6355,24 @@ var ts;
return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent);
}
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
})(ts || (ts = {}));
var ts;
(function (ts) {
ts.parseTime = 0;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
if (kind === 256) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 69) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
else if (kind < 139) {
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
}
@ -6785,6 +6795,8 @@ var ts;
var scanner = ts.createScanner(2, true);
var disallowInAndDecoratorContext = 4194304 | 16777216;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@ -6810,6 +6822,8 @@ var ts;
}
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
NodeConstructor = ts.objectAllocator.getNodeConstructor();
TokenConstructor = ts.objectAllocator.getTokenConstructor();
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
@ -7116,7 +7130,9 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return new NodeConstructor(kind, pos, pos);
return kind >= 139 ? new NodeConstructor(kind, pos, pos) :
kind === 69 ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@ -10892,6 +10908,9 @@ var ts;
case 55:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@ -15418,17 +15437,18 @@ var ts;
if (declaration.kind === 235) {
return links.type = checkExpression(declaration.expression);
}
if (declaration.flags & 134217728 && declaration.kind === 280 && declaration.typeExpression) {
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
}
if (!pushTypeResolution(symbol, 0)) {
return unknownType;
}
var type = undefined;
if (declaration.kind === 187) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
}
else if (declaration.kind === 172) {
if (declaration.parent.kind === 187) {
type = checkExpressionCached(declaration.parent.right);
}
if (declaration.kind === 187 ||
declaration.kind === 172 && declaration.parent.kind === 187) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ?
checkExpressionCached(decl.right) :
checkExpressionCached(decl.parent.right); }));
}
if (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, true);
@ -21935,7 +21955,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined);
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined);
}
return links.inferredClassType;
}
@ -23155,7 +23175,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (!node.body) {
if (noUnusedIdentifiers && !node.body) {
checkUnusedTypeParameters(node);
}
}
@ -24098,9 +24118,14 @@ var ts;
function checkUnusedTypeParameters(node) {
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
if (node.typeParameters) {
var symbol = getSymbolOfNode(node);
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
if (lastDeclaration !== node) {
return;
}
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
var typeParameter = _a[_i];
if (!typeParameter.symbol.isReferenced) {
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@ -25177,7 +25202,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
checkUnusedTypeParameters(node);
registerForUnusedIdentifiersCheck(node);
}
}
function checkTypeAliasDeclaration(node) {
@ -29900,7 +29925,7 @@ var ts;
writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write("//# sourceMappingURL=" + sourceMappingURL);
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL);
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles);
sourceMap.reset();
@ -33550,13 +33575,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("" + decoratedClassAlias);
write("let " + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@ -35800,7 +35825,7 @@ var ts;
ts.emitTime = 0;
ts.ioReadTime = 0;
ts.ioWriteTime = 0;
ts.version = "2.0.0";
ts.version = "2.1.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@ -35880,12 +35905,7 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46);
return !startsWithDotSlashOrDotDotSlash;
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@ -36541,6 +36561,22 @@ var ts;
return ts.sortAndDeduplicateDiagnostics(diagnostics);
}
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
function formatDiagnostics(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
}
return output;
}
ts.formatDiagnostics = formatDiagnostics;
function flattenDiagnosticMessageText(messageText, newLine) {
if (typeof messageText === "string") {
return messageText;
@ -36616,7 +36652,7 @@ var ts;
var resolvedTypeReferenceDirectives = {};
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesJsDepth = 0;
var currentNodeModulesDepth = 0;
var modulesWithElidedImports = {};
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
@ -36840,8 +36876,7 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@ -37248,8 +37283,17 @@ var ts;
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
}
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
if (!options.noResolve) {
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
processTypeReferenceDirectives(file_1);
}
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@ -37266,6 +37310,7 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
var existingFile = filesByNameIgnoreCase.get(path);
@ -37366,12 +37411,9 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
currentNodeModulesDepth++;
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@ -37379,8 +37421,8 @@ var ts;
else if (shouldAddFile) {
findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
}
}
}
@ -37699,12 +37741,12 @@ var ts;
{
name: "noUnusedLocals",
type: "boolean",
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
description: ts.Diagnostics.Report_errors_on_unused_locals
},
{
name: "noUnusedParameters",
type: "boolean",
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
description: ts.Diagnostics.Report_errors_on_unused_parameters
},
{
name: "noLib",
@ -38483,10 +38525,18 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
var reportDiagnostic = reportDiagnosticSimply;
var defaultFormatDiagnosticsHost = {
getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
getNewLine: function () { return ts.sys.newLine; },
getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
};
var reportDiagnosticWorker = reportDiagnosticSimply;
function reportDiagnostic(diagnostic, host) {
reportDiagnosticWorker(diagnostic, host || defaultFormatDiagnosticsHost);
}
function reportDiagnostics(diagnostics, host) {
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
var diagnostic = diagnostics_2[_i];
reportDiagnostic(diagnostic, host);
}
}
@ -38557,19 +38607,8 @@ var ts;
var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
return diagnostic.messageText;
}
function getRelativeFileName(fileName, host) {
return host ? ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : fileName;
}
function reportDiagnosticSimply(diagnostic, host) {
var output = "";
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var relativeFileName = getRelativeFileName(diagnostic.file.fileName, host);
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine) + ts.sys.newLine;
ts.sys.write(output);
ts.sys.write(ts.formatDiagnostics([diagnostic], host));
}
var redForegroundEscapeSequence = "\u001b[91m";
var yellowForegroundEscapeSequence = "\u001b[93m";
@ -38594,7 +38633,7 @@ var ts;
var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
var _b = ts.getLineAndCharacterOfPosition(file, start + length_3), lastLine = _b.line, lastLineChar = _b.character;
var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
var relativeFileName = getRelativeFileName(file.fileName, host);
var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
var gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
@ -38783,7 +38822,8 @@ var ts;
ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), ts.sys.getCurrentDirectory()), commandLine.options, configFileName);
var cwd = ts.sys.getCurrentDirectory();
var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), commandLine.options, ts.getNormalizedAbsolutePath(configFileName, cwd));
if (configParseResult.errors.length > 0) {
reportDiagnostics(configParseResult.errors, undefined);
ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
@ -38820,7 +38860,7 @@ var ts;
compilerHost.fileExists = cachedFileExists;
}
if (compilerOptions.pretty) {
reportDiagnostic = reportDiagnosticWithColorAndContext;
reportDiagnosticWorker = reportDiagnosticWithColorAndContext;
}
cachedExistingFiles = {};
var compileResult = compile(rootFileNames, compilerOptions, compilerHost);
@ -38983,7 +39023,7 @@ var ts;
output += ts.sys.newLine + ts.sys.newLine;
var padding = makePadding(marginLength);
output += getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine;
output += padding + "tsc --out file.js file.ts" + ts.sys.newLine;
output += padding + "tsc --outFile file.js file.ts" + ts.sys.newLine;
output += padding + "tsc @args.txt" + ts.sys.newLine;
output += ts.sys.newLine;
output += getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine;

View File

@ -830,10 +830,17 @@ var ts;
return true;
}
ts.containsPath = containsPath;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
function fileExtensionIs(path, extension) {
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
return path.length > extension.length && endsWith(path, extension);
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@ -1098,6 +1105,8 @@ var ts;
}
ts.objectAllocator = {
getNodeConstructor: function () { return Node; },
getTokenConstructor: function () { return Node; },
getIdentifierConstructor: function () { return Node; },
getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
@ -1229,7 +1238,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
return {
var wscriptSystem = {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@ -1248,7 +1257,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!wscriptSystem.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@ -1268,6 +1277,7 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@ -1440,7 +1450,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); });
}
return {
var nodeSystem = {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@ -1490,7 +1500,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@ -1538,6 +1548,7 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@ -2287,8 +2298,8 @@ var ts;
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
@ -3966,12 +3977,12 @@ var ts;
{
name: "noUnusedLocals",
type: "boolean",
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
description: ts.Diagnostics.Report_errors_on_unused_locals
},
{
name: "noUnusedParameters",
type: "boolean",
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
description: ts.Diagnostics.Report_errors_on_unused_parameters
},
{
name: "noLib",
@ -5754,7 +5765,7 @@ var ts;
}
ts.isExpression = isExpression;
function isExternalModuleNameRelative(moduleName) {
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
return /^\.\.?($|[\\/])/.test(moduleName);
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@ -7262,25 +7273,24 @@ var ts;
return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent);
}
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
})(ts || (ts = {}));
var ts;
(function (ts) {
ts.parseTime = 0;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
if (kind === 256) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 69) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
else if (kind < 139) {
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
}
@ -7703,6 +7713,8 @@ var ts;
var scanner = ts.createScanner(2, true);
var disallowInAndDecoratorContext = 4194304 | 16777216;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@ -7728,6 +7740,8 @@ var ts;
}
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
NodeConstructor = ts.objectAllocator.getNodeConstructor();
TokenConstructor = ts.objectAllocator.getTokenConstructor();
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
@ -8034,7 +8048,9 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return new NodeConstructor(kind, pos, pos);
return kind >= 139 ? new NodeConstructor(kind, pos, pos) :
kind === 69 ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@ -11810,6 +11826,9 @@ var ts;
case 55:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@ -16336,17 +16355,18 @@ var ts;
if (declaration.kind === 235) {
return links.type = checkExpression(declaration.expression);
}
if (declaration.flags & 134217728 && declaration.kind === 280 && declaration.typeExpression) {
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
}
if (!pushTypeResolution(symbol, 0)) {
return unknownType;
}
var type = undefined;
if (declaration.kind === 187) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
}
else if (declaration.kind === 172) {
if (declaration.parent.kind === 187) {
type = checkExpressionCached(declaration.parent.right);
}
if (declaration.kind === 187 ||
declaration.kind === 172 && declaration.parent.kind === 187) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ?
checkExpressionCached(decl.right) :
checkExpressionCached(decl.parent.right); }));
}
if (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, true);
@ -22853,7 +22873,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined);
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined);
}
return links.inferredClassType;
}
@ -24073,7 +24093,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (!node.body) {
if (noUnusedIdentifiers && !node.body) {
checkUnusedTypeParameters(node);
}
}
@ -25016,9 +25036,14 @@ var ts;
function checkUnusedTypeParameters(node) {
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
if (node.typeParameters) {
var symbol = getSymbolOfNode(node);
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
if (lastDeclaration !== node) {
return;
}
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
var typeParameter = _a[_i];
if (!typeParameter.symbol.isReferenced) {
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@ -26095,7 +26120,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
checkUnusedTypeParameters(node);
registerForUnusedIdentifiersCheck(node);
}
}
function checkTypeAliasDeclaration(node) {
@ -30818,7 +30843,7 @@ var ts;
writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write("//# sourceMappingURL=" + sourceMappingURL);
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL);
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles);
sourceMap.reset();
@ -34468,13 +34493,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("" + decoratedClassAlias);
write("let " + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@ -36718,7 +36743,7 @@ var ts;
ts.emitTime = 0;
ts.ioReadTime = 0;
ts.ioWriteTime = 0;
ts.version = "2.0.0";
ts.version = "2.1.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@ -36798,12 +36823,7 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46);
return !startsWithDotSlashOrDotDotSlash;
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@ -37459,6 +37479,22 @@ var ts;
return ts.sortAndDeduplicateDiagnostics(diagnostics);
}
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
function formatDiagnostics(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
}
return output;
}
ts.formatDiagnostics = formatDiagnostics;
function flattenDiagnosticMessageText(messageText, newLine) {
if (typeof messageText === "string") {
return messageText;
@ -37534,7 +37570,7 @@ var ts;
var resolvedTypeReferenceDirectives = {};
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesJsDepth = 0;
var currentNodeModulesDepth = 0;
var modulesWithElidedImports = {};
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
@ -37758,8 +37794,7 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@ -38166,8 +38201,17 @@ var ts;
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
}
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
if (!options.noResolve) {
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
processTypeReferenceDirectives(file_1);
}
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@ -38184,6 +38228,7 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
var existingFile = filesByNameIgnoreCase.get(path);
@ -38284,12 +38329,9 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
currentNodeModulesDepth++;
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@ -38297,8 +38339,8 @@ var ts;
else if (shouldAddFile) {
findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
}
}
}
@ -39891,7 +39933,7 @@ var ts;
return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text);
}
else {
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, startsWith(candidate, chunk.text));
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
@ -40063,14 +40105,6 @@ var ts;
var str = String.fromCharCode(ch);
return str === str.toLowerCase();
}
function startsWith(string, search) {
for (var i = 0, n = search.length; i < n; i++) {
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
return false;
}
}
return true;
}
function indexOfIgnoringCase(string, value) {
for (var i = 0, n = string.length - value.length; i <= n; i++) {
if (startsWithIgnoringCase(string, value, i)) {
@ -41555,6 +41589,9 @@ var ts;
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 244;
}
function shouldRescanSlashToken(container) {
return container.kind === 10;
}
@ -41582,7 +41619,9 @@ var ts;
? 3
: shouldRescanJsxIdentifier(n)
? 4
: 0;
: shouldRescanJsxText(n)
? 5
: 0;
if (lastTokenInfo && expectedScanAction === lastScanAction) {
return fixTokenKind(lastTokenInfo, n);
}
@ -41610,6 +41649,10 @@ var ts;
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4;
}
else if (expectedScanAction === 5) {
currentToken = scanner.reScanJsxToken();
lastScanAction = 5;
}
else {
lastScanAction = 0;
}
@ -43858,19 +43901,20 @@ var ts;
"version"
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, flags, parent) {
var node = new NodeObject(kind, pos, end);
node.flags = flags;
function createNode(kind, pos, end, parent) {
var node = kind >= 139 ? new NodeObject(kind, pos, end) :
kind === 69 ? new IdentifierObject(kind, pos, end) :
new TokenObject(kind, pos, end);
node.parent = parent;
return node;
}
var NodeObject = (function () {
function NodeObject(kind, pos, end) {
this.kind = kind;
this.pos = pos;
this.end = end;
this.flags = 0;
this.parent = undefined;
this.kind = kind;
}
NodeObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
@ -43905,14 +43949,14 @@ var ts;
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
var textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, 0, this));
nodes.push(createNode(token, pos, textPos, this));
}
pos = textPos;
}
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
var list = createNode(282, nodes.pos, nodes.end, 0, this);
var list = createNode(282, nodes.pos, nodes.end, this);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
@ -43997,6 +44041,73 @@ var ts;
};
return NodeObject;
}());
var TokenOrIdentifierObject = (function () {
function TokenOrIdentifierObject(pos, end) {
this.pos = pos;
this.end = end;
this.flags = 0;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
};
TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
};
TokenOrIdentifierObject.prototype.getFullStart = function () {
return this.pos;
};
TokenOrIdentifierObject.prototype.getEnd = function () {
return this.end;
};
TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
return this.getEnd() - this.getStart(sourceFile);
};
TokenOrIdentifierObject.prototype.getFullWidth = function () {
return this.end - this.pos;
};
TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
return this.getStart(sourceFile) - this.pos;
};
TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
};
TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
};
TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) {
return 0;
};
TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) {
return emptyArray;
};
TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) {
return undefined;
};
return TokenOrIdentifierObject;
}());
var TokenObject = (function (_super) {
__extends(TokenObject, _super);
function TokenObject(kind, pos, end) {
_super.call(this, pos, end);
this.kind = kind;
}
return TokenObject;
}(TokenOrIdentifierObject));
var IdentifierObject = (function (_super) {
__extends(IdentifierObject, _super);
function IdentifierObject(kind, pos, end) {
_super.call(this, pos, end);
}
return IdentifierObject;
}(TokenOrIdentifierObject));
IdentifierObject.prototype.kind = 69;
var SymbolObject = (function () {
function SymbolObject(flags, name) {
this.flags = flags;
@ -49677,6 +49788,8 @@ var ts;
function initializeServices() {
ts.objectAllocator = {
getNodeConstructor: function () { return NodeObject; },
getTokenConstructor: function () { return TokenObject; },
getIdentifierConstructor: function () { return IdentifierObject; },
getSourceFileConstructor: function () { return SourceFileObject; },
getSymbolConstructor: function () { return SymbolObject; },
getTypeConstructor: function () { return TypeObject; },
@ -52422,7 +52535,7 @@ var ts;
done: false,
leaf: function (relativeStart, relativeLength, ll) {
if (!f(ll, relativeStart, relativeLength)) {
this.done = true;
walkFns.done = true;
}
}
};
@ -53072,7 +53185,7 @@ var ts;
ioSession.listen();
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
var debugObjectHost = this;
var debugObjectHost = new Function("return this")();
var ts;
(function (ts) {
function logInternalError(logger, err) {

View File

@ -405,7 +405,10 @@ declare namespace ts {
interface ModifiersArray extends NodeArray<Modifier> {
flags: NodeFlags;
}
interface Modifier extends Node {
interface Token extends Node {
__tokenTag: any;
}
interface Modifier extends Token {
}
interface Identifier extends PrimaryExpression {
text: string;
@ -2050,7 +2053,6 @@ declare namespace ts {
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
getDefaultTypeDirectiveNames?(rootPath: string): string[];
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getDirectories(path: string): string[];
@ -2156,6 +2158,8 @@ declare namespace ts {
function ensureTrailingDirectorySeparator(path: string): string;
function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison;
function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
function fileExtensionIs(path: string, extension: string): boolean;
function fileExtensionIsAny(path: string, extensions: string[]): boolean;
function getRegularExpressionForWildcard(specs: string[], basePath: string, usage: "files" | "directories" | "exclude"): string;
@ -2193,6 +2197,8 @@ declare namespace ts {
function changeExtension<T extends string | Path>(path: T, newExtension: string): T;
interface ObjectAllocator {
getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node;
getTokenConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token;
getIdentifierConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token;
getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile;
getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol;
getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type;
@ -6456,13 +6462,13 @@ declare namespace ts {
key: string;
message: string;
};
Report_Errors_on_Unused_Locals: {
Report_errors_on_unused_locals: {
code: number;
category: DiagnosticCategory;
key: string;
message: string;
};
Report_Errors_on_Unused_Parameters: {
Report_errors_on_unused_parameters: {
code: number;
category: DiagnosticCategory;
key: string;
@ -7143,8 +7149,6 @@ declare namespace ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
}
declare namespace ts {
let parseTime: number;
@ -7225,6 +7229,12 @@ declare namespace ts {
const defaultInitCompilerOptions: CompilerOptions;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
interface FormatDiagnosticsHost {
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
}
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[];
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;

View File

@ -830,10 +830,17 @@ var ts;
return true;
}
ts.containsPath = containsPath;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
function fileExtensionIs(path, extension) {
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
return path.length > extension.length && endsWith(path, extension);
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@ -1098,6 +1105,8 @@ var ts;
}
ts.objectAllocator = {
getNodeConstructor: function () { return Node; },
getTokenConstructor: function () { return Node; },
getIdentifierConstructor: function () { return Node; },
getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
@ -1229,7 +1238,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
return {
var wscriptSystem = {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@ -1248,7 +1257,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!wscriptSystem.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@ -1268,6 +1277,7 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@ -1440,7 +1450,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); });
}
return {
var nodeSystem = {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@ -1490,7 +1500,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@ -1538,6 +1548,7 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@ -2287,8 +2298,8 @@ var ts;
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
@ -3966,12 +3977,12 @@ var ts;
{
name: "noUnusedLocals",
type: "boolean",
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
description: ts.Diagnostics.Report_errors_on_unused_locals
},
{
name: "noUnusedParameters",
type: "boolean",
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
description: ts.Diagnostics.Report_errors_on_unused_parameters
},
{
name: "noLib",
@ -5754,7 +5765,7 @@ var ts;
}
ts.isExpression = isExpression;
function isExternalModuleNameRelative(moduleName) {
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
return /^\.\.?($|[\\/])/.test(moduleName);
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@ -7262,25 +7273,24 @@ var ts;
return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent);
}
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
})(ts || (ts = {}));
var ts;
(function (ts) {
ts.parseTime = 0;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
if (kind === 256) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 69) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
else if (kind < 139) {
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
}
@ -7703,6 +7713,8 @@ var ts;
var scanner = ts.createScanner(2, true);
var disallowInAndDecoratorContext = 4194304 | 16777216;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@ -7728,6 +7740,8 @@ var ts;
}
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
NodeConstructor = ts.objectAllocator.getNodeConstructor();
TokenConstructor = ts.objectAllocator.getTokenConstructor();
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
@ -8034,7 +8048,9 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return new NodeConstructor(kind, pos, pos);
return kind >= 139 ? new NodeConstructor(kind, pos, pos) :
kind === 69 ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@ -11810,6 +11826,9 @@ var ts;
case 55:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@ -16336,17 +16355,18 @@ var ts;
if (declaration.kind === 235) {
return links.type = checkExpression(declaration.expression);
}
if (declaration.flags & 134217728 && declaration.kind === 280 && declaration.typeExpression) {
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
}
if (!pushTypeResolution(symbol, 0)) {
return unknownType;
}
var type = undefined;
if (declaration.kind === 187) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
}
else if (declaration.kind === 172) {
if (declaration.parent.kind === 187) {
type = checkExpressionCached(declaration.parent.right);
}
if (declaration.kind === 187 ||
declaration.kind === 172 && declaration.parent.kind === 187) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ?
checkExpressionCached(decl.right) :
checkExpressionCached(decl.parent.right); }));
}
if (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, true);
@ -22853,7 +22873,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined);
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined);
}
return links.inferredClassType;
}
@ -24073,7 +24093,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (!node.body) {
if (noUnusedIdentifiers && !node.body) {
checkUnusedTypeParameters(node);
}
}
@ -25016,9 +25036,14 @@ var ts;
function checkUnusedTypeParameters(node) {
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
if (node.typeParameters) {
var symbol = getSymbolOfNode(node);
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
if (lastDeclaration !== node) {
return;
}
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
var typeParameter = _a[_i];
if (!typeParameter.symbol.isReferenced) {
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@ -26095,7 +26120,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
checkUnusedTypeParameters(node);
registerForUnusedIdentifiersCheck(node);
}
}
function checkTypeAliasDeclaration(node) {
@ -30818,7 +30843,7 @@ var ts;
writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write("//# sourceMappingURL=" + sourceMappingURL);
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL);
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles);
sourceMap.reset();
@ -34468,13 +34493,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("" + decoratedClassAlias);
write("let " + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@ -36718,7 +36743,7 @@ var ts;
ts.emitTime = 0;
ts.ioReadTime = 0;
ts.ioWriteTime = 0;
ts.version = "2.0.0";
ts.version = "2.1.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@ -36798,12 +36823,7 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46);
return !startsWithDotSlashOrDotDotSlash;
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@ -37459,6 +37479,22 @@ var ts;
return ts.sortAndDeduplicateDiagnostics(diagnostics);
}
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
function formatDiagnostics(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
}
return output;
}
ts.formatDiagnostics = formatDiagnostics;
function flattenDiagnosticMessageText(messageText, newLine) {
if (typeof messageText === "string") {
return messageText;
@ -37534,7 +37570,7 @@ var ts;
var resolvedTypeReferenceDirectives = {};
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesJsDepth = 0;
var currentNodeModulesDepth = 0;
var modulesWithElidedImports = {};
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
@ -37758,8 +37794,7 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@ -38166,8 +38201,17 @@ var ts;
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
}
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
if (!options.noResolve) {
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
processTypeReferenceDirectives(file_1);
}
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@ -38184,6 +38228,7 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
var existingFile = filesByNameIgnoreCase.get(path);
@ -38284,12 +38329,9 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
currentNodeModulesDepth++;
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@ -38297,8 +38339,8 @@ var ts;
else if (shouldAddFile) {
findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
}
}
}
@ -39891,7 +39933,7 @@ var ts;
return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text);
}
else {
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, startsWith(candidate, chunk.text));
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
@ -40063,14 +40105,6 @@ var ts;
var str = String.fromCharCode(ch);
return str === str.toLowerCase();
}
function startsWith(string, search) {
for (var i = 0, n = search.length; i < n; i++) {
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
return false;
}
}
return true;
}
function indexOfIgnoringCase(string, value) {
for (var i = 0, n = string.length - value.length; i <= n; i++) {
if (startsWithIgnoringCase(string, value, i)) {
@ -41555,6 +41589,9 @@ var ts;
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 244;
}
function shouldRescanSlashToken(container) {
return container.kind === 10;
}
@ -41582,7 +41619,9 @@ var ts;
? 3
: shouldRescanJsxIdentifier(n)
? 4
: 0;
: shouldRescanJsxText(n)
? 5
: 0;
if (lastTokenInfo && expectedScanAction === lastScanAction) {
return fixTokenKind(lastTokenInfo, n);
}
@ -41610,6 +41649,10 @@ var ts;
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4;
}
else if (expectedScanAction === 5) {
currentToken = scanner.reScanJsxToken();
lastScanAction = 5;
}
else {
lastScanAction = 0;
}
@ -43858,19 +43901,20 @@ var ts;
"version"
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, flags, parent) {
var node = new NodeObject(kind, pos, end);
node.flags = flags;
function createNode(kind, pos, end, parent) {
var node = kind >= 139 ? new NodeObject(kind, pos, end) :
kind === 69 ? new IdentifierObject(kind, pos, end) :
new TokenObject(kind, pos, end);
node.parent = parent;
return node;
}
var NodeObject = (function () {
function NodeObject(kind, pos, end) {
this.kind = kind;
this.pos = pos;
this.end = end;
this.flags = 0;
this.parent = undefined;
this.kind = kind;
}
NodeObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
@ -43905,14 +43949,14 @@ var ts;
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
var textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, 0, this));
nodes.push(createNode(token, pos, textPos, this));
}
pos = textPos;
}
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
var list = createNode(282, nodes.pos, nodes.end, 0, this);
var list = createNode(282, nodes.pos, nodes.end, this);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
@ -43997,6 +44041,73 @@ var ts;
};
return NodeObject;
}());
var TokenOrIdentifierObject = (function () {
function TokenOrIdentifierObject(pos, end) {
this.pos = pos;
this.end = end;
this.flags = 0;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
};
TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
};
TokenOrIdentifierObject.prototype.getFullStart = function () {
return this.pos;
};
TokenOrIdentifierObject.prototype.getEnd = function () {
return this.end;
};
TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
return this.getEnd() - this.getStart(sourceFile);
};
TokenOrIdentifierObject.prototype.getFullWidth = function () {
return this.end - this.pos;
};
TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
return this.getStart(sourceFile) - this.pos;
};
TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
};
TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
};
TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) {
return 0;
};
TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) {
return emptyArray;
};
TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) {
return undefined;
};
return TokenOrIdentifierObject;
}());
var TokenObject = (function (_super) {
__extends(TokenObject, _super);
function TokenObject(kind, pos, end) {
_super.call(this, pos, end);
this.kind = kind;
}
return TokenObject;
}(TokenOrIdentifierObject));
var IdentifierObject = (function (_super) {
__extends(IdentifierObject, _super);
function IdentifierObject(kind, pos, end) {
_super.call(this, pos, end);
}
return IdentifierObject;
}(TokenOrIdentifierObject));
IdentifierObject.prototype.kind = 69;
var SymbolObject = (function () {
function SymbolObject(flags, name) {
this.flags = flags;
@ -49677,6 +49788,8 @@ var ts;
function initializeServices() {
ts.objectAllocator = {
getNodeConstructor: function () { return NodeObject; },
getTokenConstructor: function () { return TokenObject; },
getIdentifierConstructor: function () { return IdentifierObject; },
getSourceFileConstructor: function () { return SourceFileObject; },
getSymbolConstructor: function () { return SymbolObject; },
getTypeConstructor: function () { return TypeObject; },
@ -52422,7 +52535,7 @@ var ts;
done: false,
leaf: function (relativeStart, relativeLength, ll) {
if (!f(ll, relativeStart, relativeLength)) {
this.done = true;
walkFns.done = true;
}
}
};
@ -52838,7 +52951,7 @@ var ts;
server.LineLeaf = LineLeaf;
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
var debugObjectHost = this;
var debugObjectHost = new Function("return this")();
var ts;
(function (ts) {
function logInternalError(logger, err) {

14
lib/typescript.d.ts vendored
View File

@ -409,7 +409,10 @@ declare namespace ts {
interface ModifiersArray extends NodeArray<Modifier> {
flags: NodeFlags;
}
interface Modifier extends Node {
interface Token extends Node {
__tokenTag: any;
}
interface Modifier extends Token {
}
interface Identifier extends PrimaryExpression {
text: string;
@ -1696,7 +1699,6 @@ declare namespace ts {
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
getDefaultTypeDirectiveNames?(rootPath: string): string[];
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getDirectories(path: string): string[];
@ -1842,8 +1844,6 @@ declare namespace ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
@ -1868,6 +1868,12 @@ declare namespace ts {
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
interface FormatDiagnosticsHost {
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
}
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
/**
* Given a set of options and a set of root files, returns the set of type directive names

View File

@ -1756,10 +1756,19 @@ var ts;
return true;
}
ts.containsPath = containsPath;
/* @internal */
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
/* @internal */
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
function fileExtensionIs(path, extension) {
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
return path.length > extension.length && endsWith(path, extension);
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@ -2070,6 +2079,8 @@ var ts;
}
ts.objectAllocator = {
getNodeConstructor: function () { return Node; },
getTokenConstructor: function () { return Node; },
getIdentifierConstructor: function () { return Node; },
getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
@ -2216,7 +2227,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
return {
var wscriptSystem = {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@ -2235,7 +2246,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!wscriptSystem.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@ -2255,6 +2266,7 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@ -2444,7 +2456,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); });
}
return {
var nodeSystem = {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@ -2500,7 +2512,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@ -2548,6 +2560,7 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@ -3304,8 +3317,8 @@ var ts;
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
@ -6153,7 +6166,7 @@ var ts;
function isExternalModuleNameRelative(moduleName) {
// TypeScript 1.0 spec (April 2014): 11.2.1
// An external module name is "relative" if the first term is "." or "..".
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
return /^\.\.?($|[\\/])/.test(moduleName);
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@ -7916,15 +7929,6 @@ var ts;
return node.flags & 92 /* ParameterPropertyModifier */ && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent);
}
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
})(ts || (ts = {}));
/// <reference path="utilities.ts"/>
/// <reference path="scanner.ts"/>
@ -7932,11 +7936,19 @@ var ts;
(function (ts) {
/* @internal */ ts.parseTime = 0;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
if (kind === 256 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 69 /* Identifier */) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
else if (kind < 139 /* FirstNode */) {
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
}
@ -8386,6 +8398,8 @@ var ts;
var disallowInAndDecoratorContext = 4194304 /* DisallowInContext */ | 16777216 /* DecoratorContext */;
// capture constructors in 'initializeState' to avoid null checks
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@ -8485,6 +8499,8 @@ var ts;
}
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
NodeConstructor = ts.objectAllocator.getNodeConstructor();
TokenConstructor = ts.objectAllocator.getTokenConstructor();
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
@ -8855,7 +8871,9 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return new NodeConstructor(kind, pos, pos);
return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) :
kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@ -13524,6 +13542,9 @@ var ts;
case 55 /* AtToken */:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@ -18991,22 +19012,24 @@ var ts;
if (declaration.kind === 235 /* ExportAssignment */) {
return links.type = checkExpression(declaration.expression);
}
if (declaration.flags & 134217728 /* JavaScriptFile */ && declaration.kind === 280 /* JSDocPropertyTag */ && declaration.typeExpression) {
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
}
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, 0 /* Type */)) {
return unknownType;
}
var type = undefined;
// Handle module.exports = expr or this.p = expr
if (declaration.kind === 187 /* BinaryExpression */) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
}
else if (declaration.kind === 172 /* PropertyAccessExpression */) {
// Declarations only exist for property access expressions for certain
// special assignment kinds
if (declaration.parent.kind === 187 /* BinaryExpression */) {
// Handle exports.p = expr or className.prototype.method = expr
type = checkExpressionCached(declaration.parent.right);
}
// Handle certain special assignment kinds, which happen to union across multiple declarations:
// * module.exports = expr
// * exports.p = expr
// * this.p = expr
// * className.prototype.method = expr
if (declaration.kind === 187 /* BinaryExpression */ ||
declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ?
checkExpressionCached(decl.right) :
checkExpressionCached(decl.parent.right); }));
}
if (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true);
@ -26761,7 +26784,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
}
return links.inferredClassType;
}
@ -28202,7 +28225,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (!node.body) {
if (noUnusedIdentifiers && !node.body) {
checkUnusedTypeParameters(node);
}
}
@ -29388,9 +29411,16 @@ var ts;
function checkUnusedTypeParameters(node) {
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
if (node.typeParameters) {
// Only report errors on the last declaration for the type parameter container;
// this ensures that all uses have been accounted for.
var symbol = getSymbolOfNode(node);
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
if (lastDeclaration !== node) {
return;
}
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
var typeParameter = _a[_i];
if (!typeParameter.symbol.isReferenced) {
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@ -30723,7 +30753,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
checkUnusedTypeParameters(node);
registerForUnusedIdentifiersCheck(node);
}
}
function checkTypeAliasDeclaration(node) {
@ -35987,7 +36017,7 @@ var ts;
writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write("//# sourceMappingURL=" + sourceMappingURL);
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles);
// reset the state
@ -37884,7 +37914,7 @@ var ts;
* if we should also export the value after its it changed
* - check if node is a source level declaration to emit it differently,
* i.e non-exported variable statement 'var x = 1' is hoisted so
* we we emit variable statement 'var' should be dropped.
* when we emit variable statement 'var' should be dropped.
*/
function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) {
if (!node || !isCurrentFileSystemExternalModule()) {
@ -40351,13 +40381,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("" + decoratedClassAlias);
write("let " + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@ -40376,7 +40406,9 @@ var ts;
//
// We'll emit:
//
// (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp)
// let C_1 = class C{};
// C_1.a = 1;
// C_1.b = 2; // so forth and so on
//
// This keeps the expression as an expression, while ensuring that the static parts
// of it have been initialized by the time it is used.
@ -42940,7 +42972,7 @@ var ts;
/* @internal */ ts.ioReadTime = 0;
/* @internal */ ts.ioWriteTime = 0;
/** The version of the TypeScript compiler release */
ts.version = "2.0.0";
ts.version = "2.1.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@ -43029,12 +43061,7 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46 /* dot */);
return !startsWithDotSlashOrDotDotSlash;
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@ -43801,6 +43828,22 @@ var ts;
return ts.sortAndDeduplicateDiagnostics(diagnostics);
}
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
function formatDiagnostics(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
}
return output;
}
ts.formatDiagnostics = formatDiagnostics;
function flattenDiagnosticMessageText(messageText, newLine) {
if (typeof messageText === "string") {
return messageText;
@ -43893,11 +43936,11 @@ var ts;
// As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
// The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesJsDepth = 0;
var currentNodeModulesDepth = 0;
// If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
// this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
var modulesWithElidedImports = {};
// Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled.
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
host = host || createCompilerHost(options);
@ -44154,8 +44197,7 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@ -44607,9 +44649,19 @@ var ts;
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
}
// See if we need to reprocess the imports due to prior skipped imports
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
// If the file was previously found via a node_modules search, but is now being processed as a root file,
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
if (!options.noResolve) {
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
processTypeReferenceDirectives(file_1);
}
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@ -44627,6 +44679,7 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
@ -44741,12 +44794,9 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
currentNodeModulesDepth++;
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@ -44755,8 +44805,8 @@ var ts;
findSourceFile(resolution.resolvedFileName, resolvedPath,
/*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
}
}
}
@ -45094,12 +45144,12 @@ var ts;
{
name: "noUnusedLocals",
type: "boolean",
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
description: ts.Diagnostics.Report_errors_on_unused_locals
},
{
name: "noUnusedParameters",
type: "boolean",
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
description: ts.Diagnostics.Report_errors_on_unused_parameters
},
{
name: "noLib",
@ -47091,7 +47141,7 @@ var ts;
else {
// b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive
// manner. If it does, return that there was a prefix match.
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ startsWith(candidate, chunk.text));
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
@ -47357,14 +47407,6 @@ var ts;
var str = String.fromCharCode(ch);
return str === str.toLowerCase();
}
function startsWith(string, search) {
for (var i = 0, n = search.length; i < n; i++) {
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
return false;
}
}
return true;
}
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(string, value) {
for (var i = 0, n = string.length - value.length; i <= n; i++) {
@ -49209,6 +49251,7 @@ var ts;
ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken";
ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken";
ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier";
ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText";
})(ScanAction || (ScanAction = {}));
function getFormattingScanner(sourceFile, startPos, endPos) {
ts.Debug.assert(scanner === undefined);
@ -49300,6 +49343,9 @@ var ts;
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 244 /* JsxText */;
}
function shouldRescanSlashToken(container) {
return container.kind === 10 /* RegularExpressionLiteral */;
}
@ -49330,7 +49376,9 @@ var ts;
? 3 /* RescanTemplateToken */
: shouldRescanJsxIdentifier(n)
? 4 /* RescanJsxIdentifier */
: 0 /* Scan */;
: shouldRescanJsxText(n)
? 5 /* RescanJsxText */
: 0 /* Scan */;
if (lastTokenInfo && expectedScanAction === lastScanAction) {
// readTokenInfo was called before with the same expected scan action.
// No need to re-scan text, return existing 'lastTokenInfo'
@ -49365,6 +49413,10 @@ var ts;
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4 /* RescanJsxIdentifier */;
}
else if (expectedScanAction === 5 /* RescanJsxText */) {
currentToken = scanner.reScanJsxToken();
lastScanAction = 5 /* RescanJsxText */;
}
else {
lastScanAction = 0 /* Scan */;
}
@ -52037,19 +52089,20 @@ var ts;
"version"
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, flags, parent) {
var node = new NodeObject(kind, pos, end);
node.flags = flags;
function createNode(kind, pos, end, parent) {
var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) :
kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) :
new TokenObject(kind, pos, end);
node.parent = parent;
return node;
}
var NodeObject = (function () {
function NodeObject(kind, pos, end) {
this.kind = kind;
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
this.parent = undefined;
this.kind = kind;
}
NodeObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
@ -52084,14 +52137,14 @@ var ts;
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
var textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, 0, this));
nodes.push(createNode(token, pos, textPos, this));
}
pos = textPos;
}
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this);
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, this);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
@ -52177,6 +52230,74 @@ var ts;
};
return NodeObject;
}());
var TokenOrIdentifierObject = (function () {
function TokenOrIdentifierObject(pos, end) {
// Set properties in same order as NodeObject
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
};
TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
};
TokenOrIdentifierObject.prototype.getFullStart = function () {
return this.pos;
};
TokenOrIdentifierObject.prototype.getEnd = function () {
return this.end;
};
TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
return this.getEnd() - this.getStart(sourceFile);
};
TokenOrIdentifierObject.prototype.getFullWidth = function () {
return this.end - this.pos;
};
TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
return this.getStart(sourceFile) - this.pos;
};
TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
};
TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
};
TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) {
return 0;
};
TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) {
return emptyArray;
};
TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) {
return undefined;
};
return TokenOrIdentifierObject;
}());
var TokenObject = (function (_super) {
__extends(TokenObject, _super);
function TokenObject(kind, pos, end) {
_super.call(this, pos, end);
this.kind = kind;
}
return TokenObject;
}(TokenOrIdentifierObject));
var IdentifierObject = (function (_super) {
__extends(IdentifierObject, _super);
function IdentifierObject(kind, pos, end) {
_super.call(this, pos, end);
}
return IdentifierObject;
}(TokenOrIdentifierObject));
IdentifierObject.prototype.kind = 69 /* Identifier */;
var SymbolObject = (function () {
function SymbolObject(flags, name) {
this.flags = flags;
@ -58941,6 +59062,8 @@ var ts;
function initializeServices() {
ts.objectAllocator = {
getNodeConstructor: function () { return NodeObject; },
getTokenConstructor: function () { return TokenObject; },
getIdentifierConstructor: function () { return IdentifierObject; },
getSourceFileConstructor: function () { return SourceFileObject; },
getSymbolConstructor: function () { return SymbolObject; },
getTypeConstructor: function () { return TypeObject; },
@ -59566,7 +59689,7 @@ var ts;
//
/// <reference path='services.ts' />
/* @internal */
var debugObjectHost = this;
var debugObjectHost = new Function("return this")();
// We need to use 'null' to interface with the managed side.
/* tslint:disable:no-null-keyword */
/* tslint:disable:no-in-operator */

View File

@ -409,7 +409,10 @@ declare namespace ts {
interface ModifiersArray extends NodeArray<Modifier> {
flags: NodeFlags;
}
interface Modifier extends Node {
interface Token extends Node {
__tokenTag: any;
}
interface Modifier extends Token {
}
interface Identifier extends PrimaryExpression {
text: string;
@ -1696,7 +1699,6 @@ declare namespace ts {
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
getDefaultTypeDirectiveNames?(rootPath: string): string[];
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getDirectories(path: string): string[];
@ -1842,8 +1844,6 @@ declare namespace ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
@ -1868,6 +1868,12 @@ declare namespace ts {
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
interface FormatDiagnosticsHost {
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
}
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
/**
* Given a set of options and a set of root files, returns the set of type directive names

View File

@ -1756,10 +1756,19 @@ var ts;
return true;
}
ts.containsPath = containsPath;
/* @internal */
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
/* @internal */
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
function fileExtensionIs(path, extension) {
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
return path.length > extension.length && endsWith(path, extension);
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@ -2070,6 +2079,8 @@ var ts;
}
ts.objectAllocator = {
getNodeConstructor: function () { return Node; },
getTokenConstructor: function () { return Node; },
getIdentifierConstructor: function () { return Node; },
getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
@ -2216,7 +2227,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
return {
var wscriptSystem = {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@ -2235,7 +2246,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!wscriptSystem.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@ -2255,6 +2266,7 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@ -2444,7 +2456,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); });
}
return {
var nodeSystem = {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@ -2500,7 +2512,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@ -2548,6 +2560,7 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@ -3304,8 +3317,8 @@ var ts;
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
@ -6153,7 +6166,7 @@ var ts;
function isExternalModuleNameRelative(moduleName) {
// TypeScript 1.0 spec (April 2014): 11.2.1
// An external module name is "relative" if the first term is "." or "..".
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
return /^\.\.?($|[\\/])/.test(moduleName);
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@ -7916,15 +7929,6 @@ var ts;
return node.flags & 92 /* ParameterPropertyModifier */ && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent);
}
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
})(ts || (ts = {}));
/// <reference path="utilities.ts"/>
/// <reference path="scanner.ts"/>
@ -7932,11 +7936,19 @@ var ts;
(function (ts) {
/* @internal */ ts.parseTime = 0;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
if (kind === 256 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 69 /* Identifier */) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
else if (kind < 139 /* FirstNode */) {
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
}
@ -8386,6 +8398,8 @@ var ts;
var disallowInAndDecoratorContext = 4194304 /* DisallowInContext */ | 16777216 /* DecoratorContext */;
// capture constructors in 'initializeState' to avoid null checks
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@ -8485,6 +8499,8 @@ var ts;
}
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
NodeConstructor = ts.objectAllocator.getNodeConstructor();
TokenConstructor = ts.objectAllocator.getTokenConstructor();
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
@ -8855,7 +8871,9 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return new NodeConstructor(kind, pos, pos);
return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) :
kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@ -13524,6 +13542,9 @@ var ts;
case 55 /* AtToken */:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@ -18991,22 +19012,24 @@ var ts;
if (declaration.kind === 235 /* ExportAssignment */) {
return links.type = checkExpression(declaration.expression);
}
if (declaration.flags & 134217728 /* JavaScriptFile */ && declaration.kind === 280 /* JSDocPropertyTag */ && declaration.typeExpression) {
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
}
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, 0 /* Type */)) {
return unknownType;
}
var type = undefined;
// Handle module.exports = expr or this.p = expr
if (declaration.kind === 187 /* BinaryExpression */) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
}
else if (declaration.kind === 172 /* PropertyAccessExpression */) {
// Declarations only exist for property access expressions for certain
// special assignment kinds
if (declaration.parent.kind === 187 /* BinaryExpression */) {
// Handle exports.p = expr or className.prototype.method = expr
type = checkExpressionCached(declaration.parent.right);
}
// Handle certain special assignment kinds, which happen to union across multiple declarations:
// * module.exports = expr
// * exports.p = expr
// * this.p = expr
// * className.prototype.method = expr
if (declaration.kind === 187 /* BinaryExpression */ ||
declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ?
checkExpressionCached(decl.right) :
checkExpressionCached(decl.parent.right); }));
}
if (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true);
@ -26761,7 +26784,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
}
return links.inferredClassType;
}
@ -28202,7 +28225,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (!node.body) {
if (noUnusedIdentifiers && !node.body) {
checkUnusedTypeParameters(node);
}
}
@ -29388,9 +29411,16 @@ var ts;
function checkUnusedTypeParameters(node) {
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
if (node.typeParameters) {
// Only report errors on the last declaration for the type parameter container;
// this ensures that all uses have been accounted for.
var symbol = getSymbolOfNode(node);
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
if (lastDeclaration !== node) {
return;
}
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
var typeParameter = _a[_i];
if (!typeParameter.symbol.isReferenced) {
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@ -30723,7 +30753,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
checkUnusedTypeParameters(node);
registerForUnusedIdentifiersCheck(node);
}
}
function checkTypeAliasDeclaration(node) {
@ -35987,7 +36017,7 @@ var ts;
writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write("//# sourceMappingURL=" + sourceMappingURL);
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles);
// reset the state
@ -37884,7 +37914,7 @@ var ts;
* if we should also export the value after its it changed
* - check if node is a source level declaration to emit it differently,
* i.e non-exported variable statement 'var x = 1' is hoisted so
* we we emit variable statement 'var' should be dropped.
* when we emit variable statement 'var' should be dropped.
*/
function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) {
if (!node || !isCurrentFileSystemExternalModule()) {
@ -40351,13 +40381,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("" + decoratedClassAlias);
write("let " + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@ -40376,7 +40406,9 @@ var ts;
//
// We'll emit:
//
// (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp)
// let C_1 = class C{};
// C_1.a = 1;
// C_1.b = 2; // so forth and so on
//
// This keeps the expression as an expression, while ensuring that the static parts
// of it have been initialized by the time it is used.
@ -42940,7 +42972,7 @@ var ts;
/* @internal */ ts.ioReadTime = 0;
/* @internal */ ts.ioWriteTime = 0;
/** The version of the TypeScript compiler release */
ts.version = "2.0.0";
ts.version = "2.1.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@ -43029,12 +43061,7 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46 /* dot */);
return !startsWithDotSlashOrDotDotSlash;
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@ -43801,6 +43828,22 @@ var ts;
return ts.sortAndDeduplicateDiagnostics(diagnostics);
}
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
function formatDiagnostics(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
}
return output;
}
ts.formatDiagnostics = formatDiagnostics;
function flattenDiagnosticMessageText(messageText, newLine) {
if (typeof messageText === "string") {
return messageText;
@ -43893,11 +43936,11 @@ var ts;
// As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
// The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesJsDepth = 0;
var currentNodeModulesDepth = 0;
// If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
// this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
var modulesWithElidedImports = {};
// Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled.
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
host = host || createCompilerHost(options);
@ -44154,8 +44197,7 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@ -44607,9 +44649,19 @@ var ts;
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
}
// See if we need to reprocess the imports due to prior skipped imports
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
// If the file was previously found via a node_modules search, but is now being processed as a root file,
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
if (!options.noResolve) {
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
processTypeReferenceDirectives(file_1);
}
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@ -44627,6 +44679,7 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
@ -44741,12 +44794,9 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
currentNodeModulesDepth++;
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@ -44755,8 +44805,8 @@ var ts;
findSourceFile(resolution.resolvedFileName, resolvedPath,
/*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
}
}
}
@ -45094,12 +45144,12 @@ var ts;
{
name: "noUnusedLocals",
type: "boolean",
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
description: ts.Diagnostics.Report_errors_on_unused_locals
},
{
name: "noUnusedParameters",
type: "boolean",
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
description: ts.Diagnostics.Report_errors_on_unused_parameters
},
{
name: "noLib",
@ -47091,7 +47141,7 @@ var ts;
else {
// b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive
// manner. If it does, return that there was a prefix match.
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ startsWith(candidate, chunk.text));
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
@ -47357,14 +47407,6 @@ var ts;
var str = String.fromCharCode(ch);
return str === str.toLowerCase();
}
function startsWith(string, search) {
for (var i = 0, n = search.length; i < n; i++) {
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
return false;
}
}
return true;
}
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(string, value) {
for (var i = 0, n = string.length - value.length; i <= n; i++) {
@ -49209,6 +49251,7 @@ var ts;
ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken";
ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken";
ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier";
ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText";
})(ScanAction || (ScanAction = {}));
function getFormattingScanner(sourceFile, startPos, endPos) {
ts.Debug.assert(scanner === undefined);
@ -49300,6 +49343,9 @@ var ts;
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 244 /* JsxText */;
}
function shouldRescanSlashToken(container) {
return container.kind === 10 /* RegularExpressionLiteral */;
}
@ -49330,7 +49376,9 @@ var ts;
? 3 /* RescanTemplateToken */
: shouldRescanJsxIdentifier(n)
? 4 /* RescanJsxIdentifier */
: 0 /* Scan */;
: shouldRescanJsxText(n)
? 5 /* RescanJsxText */
: 0 /* Scan */;
if (lastTokenInfo && expectedScanAction === lastScanAction) {
// readTokenInfo was called before with the same expected scan action.
// No need to re-scan text, return existing 'lastTokenInfo'
@ -49365,6 +49413,10 @@ var ts;
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4 /* RescanJsxIdentifier */;
}
else if (expectedScanAction === 5 /* RescanJsxText */) {
currentToken = scanner.reScanJsxToken();
lastScanAction = 5 /* RescanJsxText */;
}
else {
lastScanAction = 0 /* Scan */;
}
@ -52037,19 +52089,20 @@ var ts;
"version"
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, flags, parent) {
var node = new NodeObject(kind, pos, end);
node.flags = flags;
function createNode(kind, pos, end, parent) {
var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) :
kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) :
new TokenObject(kind, pos, end);
node.parent = parent;
return node;
}
var NodeObject = (function () {
function NodeObject(kind, pos, end) {
this.kind = kind;
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
this.parent = undefined;
this.kind = kind;
}
NodeObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
@ -52084,14 +52137,14 @@ var ts;
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
var textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, 0, this));
nodes.push(createNode(token, pos, textPos, this));
}
pos = textPos;
}
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this);
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, this);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
@ -52177,6 +52230,74 @@ var ts;
};
return NodeObject;
}());
var TokenOrIdentifierObject = (function () {
function TokenOrIdentifierObject(pos, end) {
// Set properties in same order as NodeObject
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
};
TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
};
TokenOrIdentifierObject.prototype.getFullStart = function () {
return this.pos;
};
TokenOrIdentifierObject.prototype.getEnd = function () {
return this.end;
};
TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
return this.getEnd() - this.getStart(sourceFile);
};
TokenOrIdentifierObject.prototype.getFullWidth = function () {
return this.end - this.pos;
};
TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
return this.getStart(sourceFile) - this.pos;
};
TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
};
TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
};
TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) {
return 0;
};
TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) {
return emptyArray;
};
TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) {
return undefined;
};
return TokenOrIdentifierObject;
}());
var TokenObject = (function (_super) {
__extends(TokenObject, _super);
function TokenObject(kind, pos, end) {
_super.call(this, pos, end);
this.kind = kind;
}
return TokenObject;
}(TokenOrIdentifierObject));
var IdentifierObject = (function (_super) {
__extends(IdentifierObject, _super);
function IdentifierObject(kind, pos, end) {
_super.call(this, pos, end);
}
return IdentifierObject;
}(TokenOrIdentifierObject));
IdentifierObject.prototype.kind = 69 /* Identifier */;
var SymbolObject = (function () {
function SymbolObject(flags, name) {
this.flags = flags;
@ -58941,6 +59062,8 @@ var ts;
function initializeServices() {
ts.objectAllocator = {
getNodeConstructor: function () { return NodeObject; },
getTokenConstructor: function () { return TokenObject; },
getIdentifierConstructor: function () { return IdentifierObject; },
getSourceFileConstructor: function () { return SourceFileObject; },
getSymbolConstructor: function () { return SymbolObject; },
getTypeConstructor: function () { return TypeObject; },
@ -59566,7 +59689,7 @@ var ts;
//
/// <reference path='services.ts' />
/* @internal */
var debugObjectHost = this;
var debugObjectHost = new Function("return this")();
// We need to use 'null' to interface with the managed side.
/* tslint:disable:no-null-keyword */
/* tslint:disable:no-in-operator */

View File

@ -2,7 +2,7 @@
"name": "typescript",
"author": "Microsoft Corp.",
"homepage": "http://typescriptlang.org/",
"version": "2.0.0",
"version": "2.0.1",
"license": "Apache-2.0",
"description": "TypeScript is a language for application scale JavaScript development",
"keywords": [
@ -30,6 +30,8 @@
},
"devDependencies": {
"@types/browserify": "latest",
"@types/chai": "latest",
"@types/convert-source-map": "latest",
"@types/del": "latest",
"@types/glob": "latest",
"@types/gulp": "latest",
@ -42,12 +44,14 @@
"@types/minimatch": "latest",
"@types/minimist": "latest",
"@types/mkdirp": "latest",
"@types/mocha": "latest",
"@types/node": "latest",
"@types/q": "latest",
"@types/run-sequence": "latest",
"@types/through2": "latest",
"browserify": "latest",
"chai": "latest",
"convert-source-map": "latest",
"del": "latest",
"gulp": "latest",
"gulp-clone": "latest",
@ -65,16 +69,18 @@
"mkdirp": "latest",
"mocha": "latest",
"mocha-fivemat-progress-reporter": "latest",
"q": "latest",
"run-sequence": "latest",
"sorcery": "latest",
"through2": "latest",
"travis-fold": "latest",
"ts-node": "latest",
"tsd": "latest",
"tslint": "next",
"typescript": "next"
},
"scripts": {
"pretest": "jake tests",
"test": "jake runtests",
"test": "jake runtests-parallel",
"build": "npm run build:compiler && npm run build:tests",
"build:compiler": "jake local",
"build:tests": "jake tests",

182
scripts/authors.ts Normal file
View File

@ -0,0 +1,182 @@
import fs = require('fs');
import path = require('path');
import child_process = require("child_process");
type Author = {
displayNames: string[];
preferedName?: string;
emails: string[];
};
type AuthorMap = { [s: string]: Author };
type Command = {
(...arg: string[]): void;
description?: string;
};
const mailMapPath = path.resolve("../.mailmap");
const authorsPath = path.resolve("../AUTHORS.md");
function getKnownAuthors(): Author[] {
const segmentRegExp = /\s?([^<]+)\s+<([^>]+)>/g;
const preferedNameRegeExp = /\s?#\s?([^#]+)$/;
const knownAuthors: Author[] = [];
if (!fs.existsSync(mailMapPath)) {
throw new Error(`Could not load known users form .mailmap file at: ${mailMapPath}`);
}
const mailMap = fs.readFileSync(mailMapPath).toString();
for (const line of mailMap.split("\r\n")) {
const author: Author = { displayNames: [], emails: [] };
let match: RegExpMatchArray | null;
while (match = segmentRegExp.exec(line)) {
author.displayNames.push(match[1]);
author.emails.push(match[2]);
}
if (match = preferedNameRegeExp.exec(line)) {
author.preferedName = match[1];
}
if (!author.emails) continue;
knownAuthors.push(author);
if (line.indexOf("#") > 0 && !author.preferedName) {
throw new Error("Could not match prefered name for: " + line);
}
// console.log("===> line: " + line);
// console.log(JSON.stringify(author, undefined, 2));
}
return knownAuthors;
}
function getAuthorName(author: Author) {
return author.preferedName || author.displayNames[0];
}
function getKnownAuthorMaps() {
const knownAuthors = getKnownAuthors();
const authorsByName: AuthorMap = {};
const authorsByEmail: AuthorMap = {};
knownAuthors.forEach(author => {
author.displayNames.forEach(n => authorsByName[n] = author);
author.emails.forEach(e => authorsByEmail[e.toLocaleLowerCase()] = author);
});
return {
knownAuthors,
authorsByName,
authorsByEmail
};
}
function deduplicate<T>(array: T[]): T[] {
let result: T[] = []
if (array) {
for (const item of array) {
if (result.indexOf(item) < 0) {
result.push(item);
}
}
}
return result;
}
function log(s: string) {
console.log(` ${s}`);
}
function sortAuthors(a: string, b: string) {
if (a.charAt(0) === "@") a = a.substr(1);
if (b.charAt(0) === "@") b = b.substr(1);
if (a.toLocaleLowerCase() < b.toLocaleLowerCase()) {
return -1;
}
else {
return 1;
}
}
namespace Commands {
export const writeAuthors: Command = function () {
const output = deduplicate(getKnownAuthors().map(getAuthorName).filter(a => !!a)).sort(sortAuthors).join("\r\n* ");
fs.writeFileSync(authorsPath, "TypeScript is authored by:\r\n* " + output);
};
writeAuthors.description = "Write known authors to AUTHORS.md file.";
export const listKnownAuthors: Command = function () {
deduplicate(getKnownAuthors().map(getAuthorName)).filter(a => !!a).sort(sortAuthors).forEach(log);
};
listKnownAuthors.description = "List known authors as listed in .mailmap file.";
export const listAuthors: Command = function (...specs:string[]) {
const cmd = "git shortlog -se " + specs.join(" ");
console.log(cmd);
const outputRegExp = /\d+\s+([^<]+)<([^>]+)>/;
const tty = process.platform === 'win32' ? 'CON' : '/dev/tty';
const authors: { name: string, email: string, knownAuthor?: Author }[] = [];
child_process.exec(`${cmd} < ${tty}`, { cwd: path.resolve("../") }, function (error, stdout, stderr) {
if (error) {
console.log(stderr.toString());
}
else {
const output = stdout.toString();
const lines = output.split("\n");
lines.forEach(line => {
if (line) {
let match: RegExpExecArray | null;
if (match = outputRegExp.exec(line)) {
authors.push({ name: match[1], email: match[2] });
}
else {
throw new Error("Could not parse output: " + line);
}
}
});
const maps = getKnownAuthorMaps();
const lookupAuthor = function ({name, email}: { name: string, email: string }) {
return maps.authorsByEmail[email.toLocaleLowerCase()] || maps.authorsByName[name];
};
const knownAuthors = authors
.map(lookupAuthor)
.filter(a => !!a)
.map(getAuthorName);
const unknownAuthors = authors
.filter(a => !lookupAuthor(a))
.map(a => `${a.name} <${a.email}>`);
if (knownAuthors.length) {
console.log("\r\n");
console.log("Found known authors: ");
console.log("=====================");
deduplicate(knownAuthors).sort(sortAuthors).forEach(log);
}
if (unknownAuthors.length) {
console.log("\r\n");
console.log("Found unknown authors: ");
console.log("=====================");
deduplicate(unknownAuthors).sort(sortAuthors).forEach(log);
}
}
});
};
listAuthors.description = "List known and unknown authors for a given spec";
}
var args = process.argv.slice(2);
if (args.length < 1) {
console.log('Usage: node authors.js [command]');
console.log('List of commands: ');
Object.keys(Commands).forEach(k => console.log(` ${k}: ${(Commands as any)[k]['description']}`));
} else {
var cmd: Function = (Commands as any)[args[0]];
if (cmd === undefined) {
console.log('Unknown command ' + args[1]);
} else {
cmd.apply(undefined, args.slice(1));
}
}

45
scripts/parallel-lint.js Normal file
View File

@ -0,0 +1,45 @@
var Linter = 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 lintFileAsync(options, path, cb) {
fs.readFile(path, "utf8", function (err, contents) {
if (err) {
return cb(err);
}
var result = lintFileContents(options, path, contents);
cb(undefined, result);
});
}
process.on("message", function (data) {
switch (data.kind) {
case "file":
var target = data.name;
var lintOptions = getLinterOptions();
lintFileAsync(lintOptions, target, function (err, result) {
if (err) {
process.send({ kind: "error", error: err.toString() });
return;
}
process.send({ kind: "result", failures: result.failureCount, output: result.output });
});
break;
case "close":
process.exit(0);
break;
}
});

View File

@ -69,7 +69,7 @@ function checkForUniqueCodes(messages: string[], diagnosticTable: InputDiagnosti
}
function buildUniqueNameMap(names: string[]): ts.Map<string> {
var nameMap: ts.Map<string> = {};
var nameMap = ts.createMap<string>();
var uniqueNames = NameGenerator.ensureUniqueness(names, /* isCaseSensitive */ false, /* isFixed */ undefined);

View File

@ -1,12 +0,0 @@
{
"version": "v4",
"repo": "borisyankov/DefinitelyTyped",
"ref": "master",
"path": "typings",
"bundle": "typings/tsd.d.ts",
"installed": {
"node/node.d.ts": {
"commit": "5f480287834a2615274eea31574b713e64decf17"
}
}
}

View File

@ -0,0 +1,25 @@
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static TRAILING_FAILURE_STRING = "Excess trailing whitespace found around type assertion.";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new TypeAssertionWhitespaceWalker(sourceFile, this.getOptions()));
}
}
class TypeAssertionWhitespaceWalker extends Lint.RuleWalker {
public visitNode(node: ts.Node) {
if (node.kind === ts.SyntaxKind.TypeAssertionExpression) {
const refined = node as ts.TypeAssertion;
const leftSideWhitespaceStart = refined.type.getEnd() + 1;
const rightSideWhitespaceEnd = refined.expression.getStart();
if (leftSideWhitespaceStart !== rightSideWhitespaceEnd) {
this.addFailure(this.createFailure(leftSideWhitespaceStart, rightSideWhitespaceEnd, Rule.TRAILING_FAILURE_STRING));
}
}
super.visitNode(node);
}
}

View File

@ -1,7 +1,6 @@
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING_FACTORY = (identifier: string) => `Identifier '${identifier}' never appears on the LHS of an assignment - use const instead of let for its declaration.`;
@ -64,7 +63,7 @@ interface DeclarationUsages {
}
class PreferConstWalker extends Lint.RuleWalker {
private inScopeLetDeclarations: ts.Map<DeclarationUsages>[] = [];
private inScopeLetDeclarations: ts.MapLike<DeclarationUsages>[] = [];
private errors: Lint.RuleFailure[] = [];
private markAssignment(identifier: ts.Identifier) {
const name = identifier.text;
@ -172,7 +171,7 @@ class PreferConstWalker extends Lint.RuleWalker {
}
private visitAnyForStatement(node: ts.ForOfStatement | ts.ForInStatement) {
const names: ts.Map<DeclarationUsages> = {};
const names: ts.MapLike<DeclarationUsages> = {};
if (isLet(node.initializer)) {
if (node.initializer.kind === ts.SyntaxKind.VariableDeclarationList) {
this.collectLetIdentifiers(node.initializer as ts.VariableDeclarationList, names);
@ -194,7 +193,7 @@ class PreferConstWalker extends Lint.RuleWalker {
}
visitBlock(node: ts.Block) {
const names: ts.Map<DeclarationUsages> = {};
const names: ts.MapLike<DeclarationUsages> = {};
for (const statement of node.statements) {
if (statement.kind === ts.SyntaxKind.VariableStatement) {
this.collectLetIdentifiers((statement as ts.VariableStatement).declarationList, names);
@ -205,7 +204,7 @@ class PreferConstWalker extends Lint.RuleWalker {
this.popDeclarations();
}
private collectLetIdentifiers(list: ts.VariableDeclarationList, ret: ts.Map<DeclarationUsages>) {
private collectLetIdentifiers(list: ts.VariableDeclarationList, ret: ts.MapLike<DeclarationUsages>) {
for (const node of list.declarations) {
if (isLet(node) && !isExported(node)) {
this.collectNameIdentifiers(node, node.name, ret);
@ -213,7 +212,7 @@ class PreferConstWalker extends Lint.RuleWalker {
}
}
private collectNameIdentifiers(declaration: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.Map<DeclarationUsages>) {
private collectNameIdentifiers(declaration: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.MapLike<DeclarationUsages>) {
if (node.kind === ts.SyntaxKind.Identifier) {
table[(node as ts.Identifier).text] = { declaration, usages: 0 };
}
@ -222,7 +221,7 @@ class PreferConstWalker extends Lint.RuleWalker {
}
}
private collectBindingPatternIdentifiers(value: ts.VariableDeclaration, pattern: ts.BindingPattern, table: ts.Map<DeclarationUsages>) {
private collectBindingPatternIdentifiers(value: ts.VariableDeclaration, pattern: ts.BindingPattern, table: ts.MapLike<DeclarationUsages>) {
for (const element of pattern.elements) {
this.collectNameIdentifiers(value, element.name, table);
}

View File

@ -10,7 +10,7 @@ declare module "gulp-insert" {
export function append(text: string | Buffer): NodeJS.ReadWriteStream;
export function prepend(text: string | Buffer): NodeJS.ReadWriteStream;
export function wrap(text: string | Buffer, tail: string | Buffer): NodeJS.ReadWriteStream;
export function transform(cb: (contents: string, file: {path: string}) => string): NodeJS.ReadWriteStream; // file is a vinyl file
export function transform(cb: (contents: string, file: {path: string, relative: string}) => string): NodeJS.ReadWriteStream; // file is a vinyl file
}
declare module "into-stream" {
@ -19,4 +19,7 @@ declare module "into-stream" {
export function obj(content: any): NodeJS.ReadableStream
}
export = IntoStream;
}
}
declare module "sorcery";
declare module "travis-fold";

View File

@ -3,8 +3,6 @@
/* @internal */
namespace ts {
export let bindTime = 0;
export const enum ModuleInstanceState {
NonInstantiated = 0,
Instantiated = 1,
@ -91,9 +89,10 @@ namespace ts {
const binder = createBinder();
export function bindSourceFile(file: SourceFile, options: CompilerOptions) {
const start = new Date().getTime();
performance.mark("beforeBind");
binder(file, options);
bindTime += new Date().getTime() - start;
performance.mark("afterBind");
performance.measure("Bind", "beforeBind", "afterBind");
}
function createBinder(): (file: SourceFile, options: CompilerOptions) => void {
@ -137,7 +136,7 @@ namespace ts {
options = opts;
languageVersion = getEmitScriptTarget(options);
inStrictMode = !!file.externalModuleIndicator;
classifiableNames = {};
classifiableNames = createMap<string>();
symbolCount = 0;
Symbol = objectAllocator.getSymbolConstructor();
@ -185,11 +184,11 @@ namespace ts {
symbol.declarations.push(node);
if (symbolFlags & SymbolFlags.HasExports && !symbol.exports) {
symbol.exports = {};
symbol.exports = createMap<Symbol>();
}
if (symbolFlags & SymbolFlags.HasMembers && !symbol.members) {
symbol.members = {};
symbol.members = createMap<Symbol>();
}
if (symbolFlags & SymbolFlags.Value) {
@ -300,8 +299,10 @@ namespace ts {
const name = isDefaultExport && parent ? "default" : getDeclarationName(node);
let symbol: Symbol;
if (name !== undefined) {
if (name === undefined) {
symbol = createSymbol(SymbolFlags.None, "__missing");
}
else {
// Check and see if the symbol table already has a symbol with this name. If not,
// create a new symbol with this name and add it to the table. Note that we don't
// give the new symbol any flags *yet*. This ensures that it will not conflict
@ -313,6 +314,11 @@ namespace ts {
// declaration we have for this symbol, and then create a new symbol for this
// declaration.
//
// Note that when properties declared in Javascript constructors
// (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
// Always. This allows the common Javascript pattern of overwriting a prototype method
// with an bound instance method of the same type: `this.method = this.method.bind(this)`
//
// If we created a new symbol, either because we didn't have a symbol with this name
// in the symbol table, or we conflicted with an existing symbol, then just add this
// node as the sole declaration of the new symbol.
@ -320,42 +326,44 @@ namespace ts {
// Otherwise, we'll be merging into a compatible existing symbol (for example when
// you have multiple 'vars' with the same name in the same container). In this case
// just add this node into the declarations list of the symbol.
symbol = hasProperty(symbolTable, name)
? symbolTable[name]
: (symbolTable[name] = createSymbol(SymbolFlags.None, name));
symbol = symbolTable[name] || (symbolTable[name] = createSymbol(SymbolFlags.None, name));
if (name && (includes & SymbolFlags.Classifiable)) {
classifiableNames[name] = name;
}
if (symbol.flags & excludes) {
if (node.name) {
node.name.parent = node;
if (symbol.isReplaceableByMethod) {
// Javascript constructor-declared symbols can be discarded in favor of
// prototype symbols like methods.
symbol = symbolTable[name] = createSymbol(SymbolFlags.None, name);
}
// Report errors every position with duplicate declaration
// Report errors on previous encountered declarations
let message = symbol.flags & SymbolFlags.BlockScopedVariable
? Diagnostics.Cannot_redeclare_block_scoped_variable_0
: Diagnostics.Duplicate_identifier_0;
forEach(symbol.declarations, declaration => {
if (declaration.flags & NodeFlags.Default) {
message = Diagnostics.A_module_cannot_have_multiple_default_exports;
else {
if (node.name) {
node.name.parent = node;
}
});
forEach(symbol.declarations, declaration => {
file.bindDiagnostics.push(createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration)));
});
file.bindDiagnostics.push(createDiagnosticForNode(node.name || node, message, getDisplayName(node)));
// Report errors every position with duplicate declaration
// Report errors on previous encountered declarations
let message = symbol.flags & SymbolFlags.BlockScopedVariable
? Diagnostics.Cannot_redeclare_block_scoped_variable_0
: Diagnostics.Duplicate_identifier_0;
symbol = createSymbol(SymbolFlags.None, name);
forEach(symbol.declarations, declaration => {
if (declaration.flags & NodeFlags.Default) {
message = Diagnostics.A_module_cannot_have_multiple_default_exports;
}
});
forEach(symbol.declarations, declaration => {
file.bindDiagnostics.push(createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration)));
});
file.bindDiagnostics.push(createDiagnosticForNode(node.name || node, message, getDisplayName(node)));
symbol = createSymbol(SymbolFlags.None, name);
}
}
}
else {
symbol = createSymbol(SymbolFlags.None, "__missing");
}
addDeclarationToSymbol(symbol, node, includes);
symbol.parent = parent;
@ -436,7 +444,7 @@ namespace ts {
if (containerFlags & ContainerFlags.IsContainer) {
container = blockScopeContainer = node;
if (containerFlags & ContainerFlags.HasLocals) {
container.locals = {};
container.locals = createMap<Symbol>();
}
addToContainerChain(container);
}
@ -620,18 +628,10 @@ namespace ts {
return false;
}
function isNarrowingNullCheckOperands(expr1: Expression, expr2: Expression) {
return (expr1.kind === SyntaxKind.NullKeyword || expr1.kind === SyntaxKind.Identifier && (<Identifier>expr1).text === "undefined") && isNarrowableOperand(expr2);
}
function isNarrowingTypeofOperands(expr1: Expression, expr2: Expression) {
return expr1.kind === SyntaxKind.TypeOfExpression && isNarrowableOperand((<TypeOfExpression>expr1).expression) && expr2.kind === SyntaxKind.StringLiteral;
}
function isNarrowingDiscriminant(expr: Expression) {
return expr.kind === SyntaxKind.PropertyAccessExpression && isNarrowableReference((<PropertyAccessExpression>expr).expression);
}
function isNarrowingBinaryExpression(expr: BinaryExpression) {
switch (expr.operatorToken.kind) {
case SyntaxKind.EqualsToken:
@ -640,9 +640,8 @@ namespace ts {
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.EqualsEqualsEqualsToken:
case SyntaxKind.ExclamationEqualsEqualsToken:
return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) ||
isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) ||
isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right);
return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
case SyntaxKind.InstanceOfKeyword:
return isNarrowableOperand(expr.left);
case SyntaxKind.CommaToken:
@ -666,11 +665,6 @@ namespace ts {
return isNarrowableReference(expr);
}
function isNarrowingSwitchStatement(switchStatement: SwitchStatement) {
const expr = switchStatement.expression;
return expr.kind === SyntaxKind.PropertyAccessExpression && isNarrowableReference((<PropertyAccessExpression>expr).expression);
}
function createBranchLabel(): FlowLabel {
return {
flags: FlowFlags.BranchLabel,
@ -720,7 +714,7 @@ namespace ts {
}
function createFlowSwitchClause(antecedent: FlowNode, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): FlowNode {
if (!isNarrowingSwitchStatement(switchStatement)) {
if (!isNarrowingExpression(switchStatement.expression)) {
return antecedent;
}
setFlowNodeReferenced(antecedent);
@ -1415,7 +1409,8 @@ namespace ts {
const typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type");
addDeclarationToSymbol(typeLiteralSymbol, node, SymbolFlags.TypeLiteral);
typeLiteralSymbol.members = { [symbol.name]: symbol };
typeLiteralSymbol.members = createMap<Symbol>();
typeLiteralSymbol.members[symbol.name] = symbol;
}
function bindObjectLiteralExpression(node: ObjectLiteralExpression) {
@ -1425,7 +1420,7 @@ namespace ts {
}
if (inStrictMode) {
const seen: Map<ElementKind> = {};
const seen = createMap<ElementKind>();
for (const prop of node.properties) {
if (prop.name.kind !== SyntaxKind.Identifier) {
@ -1481,7 +1476,7 @@ namespace ts {
// fall through.
default:
if (!blockScopeContainer.locals) {
blockScopeContainer.locals = {};
blockScopeContainer.locals = createMap<Symbol>();
addToContainerChain(blockScopeContainer);
}
declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes);
@ -1903,18 +1898,17 @@ namespace ts {
}
function bindExportAssignment(node: ExportAssignment | BinaryExpression) {
const boundExpression = node.kind === SyntaxKind.ExportAssignment ? (<ExportAssignment>node).expression : (<BinaryExpression>node).right;
if (!container.symbol || !container.symbol.exports) {
// Export assignment in some sort of block construct
bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node));
}
else if (boundExpression.kind === SyntaxKind.Identifier && node.kind === SyntaxKind.ExportAssignment) {
// An export default clause with an identifier exports all meanings of that identifier
declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.Alias, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes);
}
else {
// An export default clause with an expression exports a value
declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes);
const flags = node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(<ExportAssignment>node)
// An export default clause with an EntityNameExpression exports all meanings of that identifier
? SymbolFlags.Alias
// An export default clause with any other expression exports a value
: SymbolFlags.Property;
declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes);
}
}
@ -1941,7 +1935,7 @@ namespace ts {
}
}
file.symbol.globalExports = file.symbol.globalExports || {};
file.symbol.globalExports = file.symbol.globalExports || createMap<Symbol>();
declareSymbol(file.symbol.globalExports, file.symbol, node, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
}
@ -1983,20 +1977,25 @@ namespace ts {
}
function bindThisPropertyAssignment(node: BinaryExpression) {
// Declare a 'member' in case it turns out the container was an ES5 class or ES6 constructor
let assignee: Node;
if (container.kind === SyntaxKind.FunctionDeclaration || container.kind === SyntaxKind.FunctionDeclaration) {
assignee = container;
Debug.assert(isInJavaScriptFile(node));
// Declare a 'member' if the container is an ES5 class or ES6 constructor
if (container.kind === SyntaxKind.FunctionDeclaration || container.kind === SyntaxKind.FunctionExpression) {
container.symbol.members = container.symbol.members || createMap<Symbol>();
// It's acceptable for multiple 'this' assignments of the same identifier to occur
declareSymbol(container.symbol.members, container.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes & ~SymbolFlags.Property);
}
else if (container.kind === SyntaxKind.Constructor) {
assignee = container.parent;
// this.foo assignment in a JavaScript class
// Bind this property to the containing class
const saveContainer = container;
container = container.parent;
const symbol = bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property, SymbolFlags.None);
if (symbol) {
// constructor-declared symbols can be overwritten by subsequent method declarations
(symbol as Symbol).isReplaceableByMethod = true;
}
container = saveContainer;
}
else {
return;
}
assignee.symbol.members = assignee.symbol.members || {};
// It's acceptable for multiple 'this' assignments of the same identifier to occur
declareSymbol(assignee.symbol.members, assignee.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes & ~SymbolFlags.Property);
}
function bindPrototypePropertyAssignment(node: BinaryExpression) {
@ -2020,7 +2019,7 @@ namespace ts {
// Set up the members collection if it doesn't exist already
if (!funcSymbol.members) {
funcSymbol.members = {};
funcSymbol.members = createMap<Symbol>();
}
// Declare the method/property
@ -2069,7 +2068,7 @@ namespace ts {
// module might have an exported variable called 'prototype'. We can't allow that as
// that would clash with the built-in 'prototype' for the class.
const prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype");
if (hasProperty(symbol.exports, prototypeSymbol.name)) {
if (symbol.exports[prototypeSymbol.name]) {
if (node.name) {
node.name.parent = node;
}

File diff suppressed because it is too large Load Diff

View File

@ -27,6 +27,10 @@ namespace ts {
name: "diagnostics",
type: "boolean",
},
{
name: "extendedDiagnostics",
type: "boolean",
},
{
name: "emitBOM",
type: "boolean"
@ -57,10 +61,10 @@ namespace ts {
},
{
name: "jsx",
type: {
type: createMap({
"preserve": JsxEmit.Preserve,
"react": JsxEmit.React
},
}),
paramType: Diagnostics.KIND,
description: Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react,
},
@ -87,7 +91,7 @@ namespace ts {
{
name: "module",
shortName: "m",
type: {
type: createMap({
"none": ModuleKind.None,
"commonjs": ModuleKind.CommonJS,
"amd": ModuleKind.AMD,
@ -95,16 +99,16 @@ namespace ts {
"umd": ModuleKind.UMD,
"es6": ModuleKind.ES6,
"es2015": ModuleKind.ES2015,
},
}),
description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015,
paramType: Diagnostics.KIND,
},
{
name: "newLine",
type: {
type: createMap({
"crlf": NewLineKind.CarriageReturnLineFeed,
"lf": NewLineKind.LineFeed
},
}),
description: Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
paramType: Diagnostics.NEWLINE,
},
@ -122,6 +126,10 @@ namespace ts {
type: "boolean",
description: Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
},
{
name: "noErrorTruncation",
type: "boolean"
},
{
name: "noImplicitAny",
type: "boolean",
@ -135,12 +143,12 @@ namespace ts {
{
name: "noUnusedLocals",
type: "boolean",
description: Diagnostics.Report_Errors_on_Unused_Locals,
description: Diagnostics.Report_errors_on_unused_locals,
},
{
name: "noUnusedParameters",
type: "boolean",
description: Diagnostics.Report_Errors_on_Unused_Parameters
description: Diagnostics.Report_errors_on_unused_parameters,
},
{
name: "noLib",
@ -246,12 +254,12 @@ namespace ts {
{
name: "target",
shortName: "t",
type: {
type: createMap({
"es3": ScriptTarget.ES3,
"es5": ScriptTarget.ES5,
"es6": ScriptTarget.ES6,
"es2015": ScriptTarget.ES2015,
},
}),
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015,
paramType: Diagnostics.VERSION,
},
@ -280,10 +288,10 @@ namespace ts {
},
{
name: "moduleResolution",
type: {
type: createMap({
"node": ModuleResolutionKind.NodeJs,
"classic": ModuleResolutionKind.Classic,
},
}),
description: Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
},
{
@ -388,7 +396,7 @@ namespace ts {
type: "list",
element: {
name: "lib",
type: {
type: createMap({
// JavaScript only
"es5": "lib.es5.d.ts",
"es6": "lib.es2015.d.ts",
@ -413,7 +421,7 @@ namespace ts {
"es2016.array.include": "lib.es2016.array.include.d.ts",
"es2017.object": "lib.es2017.object.d.ts",
"es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts"
},
}),
},
description: Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon
},
@ -458,6 +466,14 @@ namespace ts {
shortOptionNames: Map<string>;
}
/* @internal */
export const defaultInitCompilerOptions: CompilerOptions = {
module: ModuleKind.CommonJS,
target: ScriptTarget.ES5,
noImplicitAny: false,
sourceMap: false,
};
let optionNameMapCache: OptionNameMap;
/* @internal */
@ -466,8 +482,8 @@ namespace ts {
return optionNameMapCache;
}
const optionNameMap: Map<CommandLineOption> = {};
const shortOptionNames: Map<string> = {};
const optionNameMap = createMap<CommandLineOption>();
const shortOptionNames = createMap<string>();
forEach(optionDeclarations, option => {
optionNameMap[option.name.toLowerCase()] = option;
if (option.shortName) {
@ -482,10 +498,9 @@ namespace ts {
/* @internal */
export function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic {
const namesOfType: string[] = [];
forEachKey(opt.type, key => {
for (const key in opt.type) {
namesOfType.push(` '${key}'`);
});
}
return createCompilerDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, namesOfType);
}
@ -493,7 +508,7 @@ namespace ts {
export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) {
const key = trimString((value || "")).toLowerCase();
const map = opt.type;
if (hasProperty(map, key)) {
if (key in map) {
return map[key];
}
else {
@ -547,11 +562,11 @@ namespace ts {
s = s.slice(s.charCodeAt(1) === CharacterCodes.minus ? 2 : 1).toLowerCase();
// Try to translate short option names to their full equivalents.
if (hasProperty(shortOptionNames, s)) {
if (s in shortOptionNames) {
s = shortOptionNames[s];
}
if (hasProperty(optionNameMap, s)) {
if (s in optionNameMap) {
const opt = optionNameMap[s];
if (opt.isTSConfigOnly) {
@ -664,6 +679,94 @@ namespace ts {
}
}
/**
* Generate tsconfig configuration when running command line "--init"
* @param options commandlineOptions to be generated into tsconfig.json
* @param fileNames array of filenames to be generated into tsconfig.json
*/
/* @internal */
export function generateTSConfig(options: CompilerOptions, fileNames: string[]): { compilerOptions: Map<CompilerOptionsValue> } {
const compilerOptions = extend(options, defaultInitCompilerOptions);
const configurations: any = {
compilerOptions: serializeCompilerOptions(compilerOptions)
};
if (fileNames && fileNames.length) {
// only set the files property if we have at least one file
configurations.files = fileNames;
}
return configurations;
function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): Map<string | number> | undefined {
if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") {
// this is of a type CommandLineOptionOfPrimitiveType
return undefined;
}
else if (optionDefinition.type === "list") {
return getCustomTypeMapOfCommandLineOption((<CommandLineOptionOfListType>optionDefinition).element);
}
else {
return (<CommandLineOptionOfCustomType>optionDefinition).type;
}
}
function getNameOfCompilerOptionValue(value: CompilerOptionsValue, customTypeMap: MapLike<string | number>): string | undefined {
// There is a typeMap associated with this command-line option so use it to map value back to its name
for (const key in customTypeMap) {
if (customTypeMap[key] === value) {
return key;
}
}
return undefined;
}
function serializeCompilerOptions(options: CompilerOptions): Map<CompilerOptionsValue> {
const result = createMap<CompilerOptionsValue>();
const optionsNameMap = getOptionNameMap().optionNameMap;
for (const name in options) {
if (hasProperty(options, name)) {
// tsconfig only options cannot be specified via command line,
// so we can assume that only types that can appear here string | number | boolean
switch (name) {
case "init":
case "watch":
case "version":
case "help":
case "project":
break;
default:
const value = options[name];
let optionDefinition = optionsNameMap[name.toLowerCase()];
if (optionDefinition) {
const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition);
if (!customTypeMap) {
// There is no map associated with this compiler option then use the value as-is
// This is the case if the value is expect to be string, number, boolean or list of string
result[name] = value;
}
else {
if (optionDefinition.type === "list") {
const convertedValue: string[] = [];
for (const element of value as (string | number)[]) {
convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap));
}
result[name] = convertedValue;
}
else {
// There is a typeMap associated with this command-line option so use it to map value back to its name
result[name] = getNameOfCompilerOptionValue(value, customTypeMap);
}
}
}
break;
}
}
}
return result;
}
}
/**
* Remove the comments from a json like text.
* Comments can be single line comments (starting with # or //) or multiline comments using / * * /
@ -807,7 +910,7 @@ namespace ts {
const optionNameMap = arrayToMap(optionDeclarations, opt => opt.name);
for (const id in jsonOptions) {
if (hasProperty(optionNameMap, id)) {
if (id in optionNameMap) {
const opt = optionNameMap[id];
defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
}
@ -844,7 +947,7 @@ namespace ts {
function convertJsonOptionOfCustomType(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) {
const key = value.toLowerCase();
if (hasProperty(opt.type, key)) {
if (key in opt.type) {
return opt.type[key];
}
else {
@ -954,12 +1057,12 @@ namespace ts {
// Literal file names (provided via the "files" array in tsconfig.json) are stored in a
// file map with a possibly case insensitive key. We use this map later when when including
// wildcard paths.
const literalFileMap: Map<string> = {};
const literalFileMap = createMap<string>();
// Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
// file map with a possibly case insensitive key. We use this map to store paths matched
// via wildcard, and to handle extension priority.
const wildcardFileMap: Map<string> = {};
const wildcardFileMap = createMap<string>();
if (include) {
include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false);
@ -1007,7 +1110,7 @@ namespace ts {
removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
const key = keyMapper(file);
if (!hasProperty(literalFileMap, key) && !hasProperty(wildcardFileMap, key)) {
if (!(key in literalFileMap) && !(key in wildcardFileMap)) {
wildcardFileMap[key] = file;
}
}
@ -1059,7 +1162,7 @@ namespace ts {
// /a/b/a?z - Watch /a/b directly to catch any new file matching a?z
const rawExcludeRegex = getRegularExpressionForWildcard(exclude, path, "exclude");
const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
const wildcardDirectories: Map<WatchDirectoryFlags> = {};
const wildcardDirectories = createMap<WatchDirectoryFlags>();
if (include !== undefined) {
const recursiveKeys: string[] = [];
for (const file of include) {
@ -1072,7 +1175,7 @@ namespace ts {
if (match) {
const key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase();
const flags = watchRecursivePattern.test(name) ? WatchDirectoryFlags.Recursive : WatchDirectoryFlags.None;
const existingFlags = getProperty(wildcardDirectories, key);
const existingFlags = wildcardDirectories[key];
if (existingFlags === undefined || existingFlags < flags) {
wildcardDirectories[key] = flags;
if (flags === WatchDirectoryFlags.Recursive) {
@ -1084,11 +1187,9 @@ namespace ts {
// Remove any subpaths under an existing recursively watched directory.
for (const key in wildcardDirectories) {
if (hasProperty(wildcardDirectories, key)) {
for (const recursiveKey of recursiveKeys) {
if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
delete wildcardDirectories[key];
}
for (const recursiveKey of recursiveKeys) {
if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
delete wildcardDirectories[key];
}
}
}
@ -1111,7 +1212,7 @@ namespace ts {
for (let i = ExtensionPriority.Highest; i < adjustedExtensionPriority; i++) {
const higherPriorityExtension = extensions[i];
const higherPriorityPath = keyMapper(changeExtension(file, higherPriorityExtension));
if (hasProperty(literalFiles, higherPriorityPath) || hasProperty(wildcardFiles, higherPriorityPath)) {
if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) {
return true;
}
}

View File

@ -1,4 +1,6 @@
/// <reference path="types.ts"/>
/// <reference path="performance.ts" />
/* @internal */
namespace ts {
@ -17,8 +19,28 @@ namespace ts {
True = -1
}
const createObject = Object.create;
export function createMap<T>(template?: MapLike<T>): Map<T> {
const map: Map<T> = createObject(null); // tslint:disable-line:no-null-keyword
// Using 'delete' on an object causes V8 to put the object in dictionary mode.
// This disables creation of hidden classes, which are expensive when an object is
// constantly changing shape.
map["__"] = undefined;
delete map["__"];
// Copies keys/values from template. Note that for..in will not throw if
// template is undefined, and instead will just exit the loop.
for (const key in template) if (hasOwnProperty.call(template, key)) {
map[key] = template[key];
}
return map;
}
export function createFileMap<T>(keyMapper?: (key: string) => string): FileMap<T> {
let files: Map<T> = {};
let files = createMap<T>();
return {
get,
set,
@ -44,7 +66,7 @@ namespace ts {
}
function contains(path: Path) {
return hasProperty(files, toKey(path));
return toKey(path) in files;
}
function remove(path: Path) {
@ -53,7 +75,7 @@ namespace ts {
}
function clear() {
files = {};
files = createMap<T>();
}
function toKey(path: Path): string {
@ -79,7 +101,7 @@ namespace ts {
* returns a truthy value, then returns that value.
* If no such value is found, the callback is applied to each element of array and undefined is returned.
*/
export function forEach<T, U>(array: T[], callback: (element: T, index: number) => U): U {
export function forEach<T, U>(array: T[] | undefined, callback: (element: T, index: number) => U | undefined): U | undefined {
if (array) {
for (let i = 0, len = array.length; i < len; i++) {
const result = callback(array[i], i);
@ -91,10 +113,21 @@ namespace ts {
return undefined;
}
export function contains<T>(array: T[], value: T, areEqual?: (a: T, b: T) => boolean): boolean {
/** Like `forEach`, but assumes existence of array and fails if no truthy value is found. */
export function find<T, U>(array: T[], callback: (element: T, index: number) => U | undefined): U {
for (let i = 0, len = array.length; i < len; i++) {
const result = callback(array[i], i);
if (result) {
return result;
}
}
Debug.fail();
}
export function contains<T>(array: T[], value: T): boolean {
if (array) {
for (const v of array) {
if (areEqual ? areEqual(v, value) : v === value) {
if (v === value) {
return true;
}
}
@ -134,17 +167,44 @@ namespace ts {
return count;
}
/**
* Filters an array by a predicate function. Returns the same array instance if the predicate is
* true for all elements, otherwise returns a new array instance containing the filtered subset.
*/
export function filter<T>(array: T[], f: (x: T) => boolean): T[] {
let result: T[];
if (array) {
result = [];
for (const item of array) {
if (f(item)) {
result.push(item);
const len = array.length;
let i = 0;
while (i < len && f(array[i])) i++;
if (i < len) {
const result = array.slice(0, i);
i++;
while (i < len) {
const item = array[i];
if (f(item)) {
result.push(item);
}
i++;
}
return result;
}
}
return result;
return array;
}
export function removeWhere<T>(array: T[], f: (x: T) => boolean): boolean {
let outIndex = 0;
for (const item of array) {
if (!f(item)) {
array[outIndex] = item;
outIndex++;
}
}
if (outIndex !== array.length) {
array.length = outIndex;
return true;
}
return false;
}
export function filterMutate<T>(array: T[], f: (x: T) => boolean): void {
@ -180,10 +240,13 @@ namespace ts {
let result: T[];
if (array) {
result = [];
for (const item of array) {
if (!contains(result, item, areEqual)) {
result.push(item);
loop: for (const item of array) {
for (const res of result) {
if (areEqual ? areEqual(res, item) : res === item) {
continue loop;
}
}
result.push(item);
}
}
return result;
@ -306,82 +369,142 @@ namespace ts {
const hasOwnProperty = Object.prototype.hasOwnProperty;
export function hasProperty<T>(map: Map<T>, key: string): boolean {
/**
* Indicates whether a map-like contains an own property with the specified key.
*
* NOTE: This is intended for use only with MapLike<T> objects. For Map<T> objects, use
* the 'in' operator.
*
* @param map A map-like.
* @param key A property key.
*/
export function hasProperty<T>(map: MapLike<T>, key: string): boolean {
return hasOwnProperty.call(map, key);
}
export function getKeys<T>(map: Map<T>): string[] {
/**
* Gets the value of an owned property in a map-like.
*
* NOTE: This is intended for use only with MapLike<T> objects. For Map<T> objects, use
* an indexer.
*
* @param map A map-like.
* @param key A property key.
*/
export function getProperty<T>(map: MapLike<T>, key: string): T | undefined {
return hasOwnProperty.call(map, key) ? map[key] : undefined;
}
/**
* Gets the owned, enumerable property keys of a map-like.
*
* NOTE: This is intended for use with MapLike<T> objects. For Map<T> objects, use
* Object.keys instead as it offers better performance.
*
* @param map A map-like.
*/
export function getOwnKeys<T>(map: MapLike<T>): string[] {
const keys: string[] = [];
for (const key in map) {
for (const key in map) if (hasOwnProperty.call(map, key)) {
keys.push(key);
}
return keys;
}
export function getProperty<T>(map: Map<T>, key: string): T {
return hasProperty(map, key) ? map[key] : undefined;
/**
* Enumerates the properties of a Map<T>, invoking a callback and returning the first truthy result.
*
* @param map A map for which properties should be enumerated.
* @param callback A callback to invoke for each property.
*/
export function forEachProperty<T, U>(map: Map<T>, callback: (value: T, key: string) => U): U {
let result: U;
for (const key in map) {
if (result = callback(map[key], key)) break;
}
return result;
}
export function getOrUpdateProperty<T>(map: Map<T>, key: string, makeValue: () => T): T {
return hasProperty(map, key) ? map[key] : map[key] = makeValue();
/**
* Returns true if a Map<T> has some matching property.
*
* @param map A map whose properties should be tested.
* @param predicate An optional callback used to test each property.
*/
export function someProperties<T>(map: Map<T>, predicate?: (value: T, key: string) => boolean) {
for (const key in map) {
if (!predicate || predicate(map[key], key)) return true;
}
return false;
}
export function isEmpty<T>(map: Map<T>) {
for (const id in map) {
if (hasProperty(map, id)) {
return false;
}
/**
* Performs a shallow copy of the properties from a source Map<T> to a target MapLike<T>
*
* @param source A map from which properties should be copied.
* @param target A map to which properties should be copied.
*/
export function copyProperties<T>(source: Map<T>, target: MapLike<T>): void {
for (const key in source) {
target[key] = source[key];
}
}
/**
* Reduce the properties of a map.
*
* NOTE: This is intended for use with Map<T> objects. For MapLike<T> objects, use
* reduceOwnProperties instead as it offers better runtime safety.
*
* @param map The map to reduce
* @param callback An aggregation function that is called for each entry in the map
* @param initial The initial value for the reduction.
*/
export function reduceProperties<T, U>(map: Map<T>, callback: (aggregate: U, value: T, key: string) => U, initial: U): U {
let result = initial;
for (const key in map) {
result = callback(result, map[key], String(key));
}
return result;
}
/**
* Reduce the properties defined on a map-like (but not from its prototype chain).
*
* NOTE: This is intended for use with MapLike<T> objects. For Map<T> objects, use
* reduceProperties instead as it offers better performance.
*
* @param map The map-like to reduce
* @param callback An aggregation function that is called for each entry in the map
* @param initial The initial value for the reduction.
*/
export function reduceOwnProperties<T, U>(map: MapLike<T>, callback: (aggregate: U, value: T, key: string) => U, initial: U): U {
let result = initial;
for (const key in map) if (hasOwnProperty.call(map, key)) {
result = callback(result, map[key], String(key));
}
return result;
}
/**
* Performs a shallow equality comparison of the contents of two map-likes.
*
* @param left A map-like whose properties should be compared.
* @param right A map-like whose properties should be compared.
*/
export function equalOwnProperties<T>(left: MapLike<T>, right: MapLike<T>, equalityComparer?: (left: T, right: T) => boolean) {
if (left === right) return true;
if (!left || !right) return false;
for (const key in left) if (hasOwnProperty.call(left, key)) {
if (!hasOwnProperty.call(right, key) === undefined) return false;
if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) return false;
}
for (const key in right) if (hasOwnProperty.call(right, key)) {
if (!hasOwnProperty.call(left, key)) return false;
}
return true;
}
export function clone<T>(object: T): T {
const result: any = {};
for (const id in object) {
result[id] = (<any>object)[id];
}
return <T>result;
}
export function extend<T1 extends Map<{}>, T2 extends Map<{}>>(first: T1 , second: T2): T1 & T2 {
const result: T1 & T2 = <any>{};
for (const id in first) {
(result as any)[id] = first[id];
}
for (const id in second) {
if (!hasProperty(result, id)) {
(result as any)[id] = second[id];
}
}
return result;
}
export function forEachValue<T, U>(map: Map<T>, callback: (value: T) => U): U {
let result: U;
for (const id in map) {
if (result = callback(map[id])) break;
}
return result;
}
export function forEachKey<T, U>(map: Map<T>, callback: (key: string) => U): U {
let result: U;
for (const id in map) {
if (result = callback(id)) break;
}
return result;
}
export function lookUp<T>(map: Map<T>, key: string): T {
return hasProperty(map, key) ? map[key] : undefined;
}
export function copyMap<T>(source: Map<T>, target: Map<T>): void {
for (const p in source) {
target[p] = source[p];
}
}
/**
* Creates a map from the elements of an array.
*
@ -392,33 +515,40 @@ namespace ts {
* the same key with the given 'makeKey' function, then the element with the higher
* index in the array will be the one associated with the produced key.
*/
export function arrayToMap<T>(array: T[], makeKey: (value: T) => string): Map<T> {
const result: Map<T> = {};
forEach(array, value => {
result[makeKey(value)] = value;
});
export function arrayToMap<T>(array: T[], makeKey: (value: T) => string): Map<T>;
export function arrayToMap<T, U>(array: T[], makeKey: (value: T) => string, makeValue: (value: T) => U): Map<U>;
export function arrayToMap<T, U>(array: T[], makeKey: (value: T) => string, makeValue?: (value: T) => U): Map<T | U> {
const result = createMap<T | U>();
for (const value of array) {
result[makeKey(value)] = makeValue ? makeValue(value) : value;
}
return result;
}
/**
* Reduce the properties of a map.
*
* @param map The map to reduce
* @param callback An aggregation function that is called for each entry in the map
* @param initial The initial value for the reduction.
*/
export function reduceProperties<T, U>(map: Map<T>, callback: (aggregate: U, value: T, key: string) => U, initial: U): U {
let result = initial;
if (map) {
for (const key in map) {
if (hasProperty(map, key)) {
result = callback(result, map[key], String(key));
}
export function cloneMap<T>(map: Map<T>) {
const clone = createMap<T>();
copyProperties(map, clone);
return clone;
}
export function clone<T>(object: T): T {
const result: any = {};
for (const id in object) {
if (hasOwnProperty.call(object, id)) {
result[id] = (<any>object)[id];
}
}
return result;
}
export function extend<T1, T2>(first: T1 , second: T2): T1 & T2 {
const result: T1 & T2 = <any>{};
for (const id in second) if (hasOwnProperty.call(second, id)) {
(result as any)[id] = (second as any)[id];
}
for (const id in first) if (hasOwnProperty.call(first, id)) {
(result as any)[id] = (first as any)[id];
}
return result;
}
@ -449,9 +579,7 @@ namespace ts {
export let localizedDiagnosticMessages: Map<string> = undefined;
export function getLocaleSpecificMessage(message: DiagnosticMessage) {
return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key]
? localizedDiagnosticMessages[message.key]
: message.message;
return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message;
}
export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic;
@ -903,10 +1031,19 @@ namespace ts {
return true;
}
/* @internal */
export function startsWith(str: string, prefix: string): boolean {
return str.lastIndexOf(prefix, 0) === 0;
}
/* @internal */
export function endsWith(str: string, suffix: string): boolean {
const expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
export function fileExtensionIs(path: string, extension: string): boolean {
const pathLen = path.length;
const extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
return path.length > extension.length && endsWith(path, extension);
}
export function fileExtensionIsAny(path: string, extensions: string[]): boolean {
@ -919,7 +1056,6 @@ namespace ts {
return false;
}
// Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
// It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
// proof.
@ -1275,26 +1411,28 @@ namespace ts {
export interface ObjectAllocator {
getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node;
getTokenConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token;
getIdentifierConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token;
getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile;
getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol;
getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type;
getSignatureConstructor(): new (checker: TypeChecker) => Signature;
}
function Symbol(flags: SymbolFlags, name: string) {
function Symbol(this: Symbol, flags: SymbolFlags, name: string) {
this.flags = flags;
this.name = name;
this.declarations = undefined;
}
function Type(checker: TypeChecker, flags: TypeFlags) {
function Type(this: Type, checker: TypeChecker, flags: TypeFlags) {
this.flags = flags;
}
function Signature(checker: TypeChecker) {
}
function Node(kind: SyntaxKind, pos: number, end: number) {
function Node(this: Node, kind: SyntaxKind, pos: number, end: number) {
this.kind = kind;
this.pos = pos;
this.end = end;
@ -1304,6 +1442,8 @@ namespace ts {
export let objectAllocator: ObjectAllocator = {
getNodeConstructor: () => <any>Node,
getTokenConstructor: () => <any>Node,
getIdentifierConstructor: () => <any>Node,
getSourceFileConstructor: () => <any>Node,
getSymbolConstructor: () => <any>Symbol,
getTypeConstructor: () => <any>Type,

View File

@ -157,9 +157,7 @@ namespace ts {
if (usedTypeDirectiveReferences) {
for (const directive in usedTypeDirectiveReferences) {
if (hasProperty(usedTypeDirectiveReferences, directive)) {
referencesOutput += `/// <reference types="${directive}" />${newLine}`;
}
referencesOutput += `/// <reference types="${directive}" />${newLine}`;
}
}
@ -269,10 +267,10 @@ namespace ts {
}
if (!usedTypeDirectiveReferences) {
usedTypeDirectiveReferences = {};
usedTypeDirectiveReferences = createMap<string>();
}
for (const directive of typeReferenceDirectives) {
if (!hasProperty(usedTypeDirectiveReferences, directive)) {
if (!(directive in usedTypeDirectiveReferences)) {
usedTypeDirectiveReferences[directive] = directive;
}
}
@ -397,7 +395,7 @@ namespace ts {
case SyntaxKind.NullKeyword:
case SyntaxKind.NeverKeyword:
case SyntaxKind.ThisType:
case SyntaxKind.StringLiteralType:
case SyntaxKind.LiteralType:
return writeTextOfNode(currentText, type);
case SyntaxKind.ExpressionWithTypeArguments:
return emitExpressionWithTypeArguments(<ExpressionWithTypeArguments>type);
@ -441,7 +439,7 @@ namespace ts {
}
}
function emitEntityName(entityName: EntityName | PropertyAccessExpression) {
function emitEntityName(entityName: EntityNameOrEntityNameExpression) {
const visibilityResult = resolver.isEntityNameVisible(entityName,
// Aliases can be written asynchronously so use correct enclosing declaration
entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration ? entityName.parent : enclosingDeclaration);
@ -452,9 +450,9 @@ namespace ts {
}
function emitExpressionWithTypeArguments(node: ExpressionWithTypeArguments) {
if (isSupportedExpressionWithTypeArguments(node)) {
if (isEntityNameExpression(node.expression)) {
Debug.assert(node.expression.kind === SyntaxKind.Identifier || node.expression.kind === SyntaxKind.PropertyAccessExpression);
emitEntityName(<Identifier | PropertyAccessExpression>node.expression);
emitEntityName(node.expression);
if (node.typeArguments) {
write("<");
emitCommaList(node.typeArguments, emitType);
@ -537,14 +535,14 @@ namespace ts {
// do not need to keep track of created temp names.
function getExportDefaultTempVariableName(): string {
const baseName = "_default";
if (!hasProperty(currentIdentifiers, baseName)) {
if (!(baseName in currentIdentifiers)) {
return baseName;
}
let count = 0;
while (true) {
count++;
const name = baseName + "_" + count;
if (!hasProperty(currentIdentifiers, name)) {
if (!(name in currentIdentifiers)) {
return name;
}
}
@ -1019,7 +1017,7 @@ namespace ts {
}
function emitTypeOfTypeReference(node: ExpressionWithTypeArguments) {
if (isSupportedExpressionWithTypeArguments(node)) {
if (isEntityNameExpression(node.expression)) {
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError);
}
else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) {

View File

@ -1755,6 +1755,10 @@
"category": "Error",
"code": 2534
},
"Enum type '{0}' has members with initializers that are not literals.": {
"category": "Error",
"code": 2535
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
@ -1943,6 +1947,10 @@
"category": "Error",
"code": 2689
},
"A class must be declared after its base class.": {
"category": "Error",
"code": 2690
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@ -2223,7 +2231,7 @@
"category": "Error",
"code": 4082
},
"Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict.": {
"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
},
@ -2336,6 +2344,10 @@
"category": "Error",
"code": 5065
},
"Substitutions for pattern '{0}' shouldn't be an empty array.": {
"category": "Error",
"code": 5066
},
"Concatenate and emit output to single file.": {
"category": "Message",
"code": 6001
@ -2800,11 +2812,11 @@
"category": "Error",
"code": 6133
},
"Report Errors on Unused Locals.": {
"Report errors on unused locals.": {
"category": "Message",
"code": 6134
},
"Report Errors on Unused Parameters.": {
"Report errors on unused parameters.": {
"category": "Message",
"code": 6135
},
@ -2816,6 +2828,10 @@
"category": "Message",
"code": 6137
},
"Property '{0}' is declared but never used.": {
"category": "Error",
"code": 6138
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005

View File

@ -24,7 +24,7 @@ namespace ts {
Return = 1 << 3
}
const entities: Map<number> = {
const entities = createMap({
"quot": 0x0022,
"amp": 0x0026,
"apos": 0x0027,
@ -278,7 +278,7 @@ namespace ts {
"clubs": 0x2663,
"hearts": 0x2665,
"diams": 0x2666
};
});
// Flags enum to track count of temp variables and a few dedicated names
const enum TempFlags {
@ -407,7 +407,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
function isUniqueLocalName(name: string, container: Node): boolean {
for (let node = container; isNodeDescendentOf(node, container); node = node.nextContainer) {
if (node.locals && hasProperty(node.locals, name)) {
if (node.locals && name in node.locals) {
// We conservatively include alias symbols to cover cases where they're emitted as locals
if (node.locals[name].flags & (SymbolFlags.Value | SymbolFlags.ExportValue | SymbolFlags.Alias)) {
return false;
@ -489,13 +489,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
function setLabeledJump(state: ConvertedLoopState, isBreak: boolean, labelText: string, labelMarker: string): void {
if (isBreak) {
if (!state.labeledNonLocalBreaks) {
state.labeledNonLocalBreaks = {};
state.labeledNonLocalBreaks = createMap<string>();
}
state.labeledNonLocalBreaks[labelText] = labelMarker;
}
else {
if (!state.labeledNonLocalContinues) {
state.labeledNonLocalContinues = {};
state.labeledNonLocalContinues = createMap<string>();
}
state.labeledNonLocalContinues[labelText] = labelMarker;
}
@ -577,27 +577,27 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
const setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer: SourceMapWriter) { };
const moduleEmitDelegates: Map<(node: SourceFile, emitRelativePathAsModuleName?: boolean) => void> = {
const moduleEmitDelegates = createMap<(node: SourceFile, emitRelativePathAsModuleName?: boolean) => void>({
[ModuleKind.ES6]: emitES6Module,
[ModuleKind.AMD]: emitAMDModule,
[ModuleKind.System]: emitSystemModule,
[ModuleKind.UMD]: emitUMDModule,
[ModuleKind.CommonJS]: emitCommonJSModule,
};
});
const bundleEmitDelegates: Map<(node: SourceFile, emitRelativePathAsModuleName?: boolean) => void> = {
const bundleEmitDelegates = createMap<(node: SourceFile, emitRelativePathAsModuleName?: boolean) => void>({
[ModuleKind.ES6]() {},
[ModuleKind.AMD]: emitAMDModule,
[ModuleKind.System]: emitSystemModule,
[ModuleKind.UMD]() {},
[ModuleKind.CommonJS]() {},
};
});
return doEmit;
function doEmit(jsFilePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) {
sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit);
generatedNameSet = {};
generatedNameSet = createMap<string>();
nodeToGeneratedName = [];
decoratedClassAliases = [];
isOwnFileEmit = !isBundledEmit;
@ -614,7 +614,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
const sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write(`//# sourceMappingURL=${sourceMappingURL}`);
write(`//# ${"sourceMappingURL"}=${sourceMappingURL}`); // Sometimes tools can sometimes see this line as a source mapping url comment
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles);
@ -669,8 +669,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
function isUniqueName(name: string): boolean {
return !resolver.hasGlobalName(name) &&
!hasProperty(currentFileIdentifiers, name) &&
!hasProperty(generatedNameSet, name);
!(name in currentFileIdentifiers) &&
!(name in generatedNameSet);
}
// Return the next available name in the pattern _a ... _z, _0, _1, ...
@ -2578,7 +2578,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
operand = (<TypeAssertion | NonNullExpression>operand).expression;
}
// We have an expression of the form: (<Type>SubExpr)
// We have an expression of the form: (<Type>SubExpr) or (SubExpr as Type)
// Emitting this as (SubExpr) is really not desirable. We would like to emit the subexpr as is.
// Omitting the parentheses, however, could cause change in the semantics of the generated
// code if the casted expression has a lower precedence than the rest of the expression, e.g.:
@ -2592,6 +2592,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
operand.kind !== SyntaxKind.DeleteExpression &&
operand.kind !== SyntaxKind.PostfixUnaryExpression &&
operand.kind !== SyntaxKind.NewExpression &&
!(operand.kind === SyntaxKind.BinaryExpression && node.expression.kind === SyntaxKind.AsExpression) &&
!(operand.kind === SyntaxKind.CallExpression && node.parent.kind === SyntaxKind.NewExpression) &&
!(operand.kind === SyntaxKind.FunctionExpression && node.parent.kind === SyntaxKind.CallExpression) &&
!(operand.kind === SyntaxKind.NumericLiteral && node.parent.kind === SyntaxKind.PropertyAccessExpression)) {
@ -2645,7 +2646,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
return false;
}
return !exportEquals && exportSpecifiers && hasProperty(exportSpecifiers, (<Identifier>node).text);
return !exportEquals && exportSpecifiers && (<Identifier>node).text in exportSpecifiers;
}
function emitPrefixUnaryExpression(node: PrefixUnaryExpression) {
@ -2667,7 +2668,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
isNameOfExportedDeclarationInNonES6Module(node.operand);
if (internalExportChanged) {
emitAliasEqual(<Identifier> node.operand);
emitAliasEqual(<Identifier>node.operand);
}
write(tokenToString(node.operator));
@ -2722,7 +2723,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
}
else if (internalExportChanged) {
emitAliasEqual(<Identifier> node.operand);
emitAliasEqual(<Identifier>node.operand);
emit(node.operand);
if (node.operator === SyntaxKind.PlusPlusToken) {
write(" += 1");
@ -3256,13 +3257,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
// Don't initialize seen unless we have at least one element.
// Emit a comma to separate for all but the first element.
if (!seen) {
seen = {};
seen = createMap<string>();
}
else {
write(", ");
}
if (!hasProperty(seen, id.text)) {
if (!(id.text in seen)) {
emit(id);
seen[id.text] = id.text;
}
@ -3855,7 +3856,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
if (convertedLoopState) {
if (!convertedLoopState.labels) {
convertedLoopState.labels = {};
convertedLoopState.labels = createMap<string>();
}
convertedLoopState.labels[node.label.text] = node.label.text;
}
@ -3969,7 +3970,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
return;
}
if (!exportEquals && exportSpecifiers && hasProperty(exportSpecifiers, name.text)) {
if (!exportEquals && exportSpecifiers && name.text in exportSpecifiers) {
for (const specifier of exportSpecifiers[name.text]) {
writeLine();
emitStart(specifier.name);
@ -5310,18 +5311,7 @@ const _super = (function (geti, seti) {
emitSignatureParameters(ctor);
}
else {
// Based on EcmaScript6 section 14.5.14: Runtime Semantics: ClassDefinitionEvaluation.
// If constructor is empty, then,
// If ClassHeritageopt is present, then
// Let constructor be the result of parsing the String "constructor(... args){ super (...args);}" using the syntactic grammar with the goal symbol MethodDefinition.
// Else,
// Let constructor be the result of parsing the String "constructor( ){ }" using the syntactic grammar with the goal symbol MethodDefinition
if (baseTypeElement) {
write("(...args)");
}
else {
write("()");
}
write("()");
}
}
@ -5359,7 +5349,7 @@ const _super = (function (geti, seti) {
write("_super.apply(this, arguments);");
}
else {
write("super(...args);");
write("super(...arguments);");
}
emitEnd(baseTypeElement);
}
@ -6045,7 +6035,7 @@ const _super = (function (geti, seti) {
return;
case SyntaxKind.StringKeyword:
case SyntaxKind.StringLiteralType:
case SyntaxKind.LiteralType:
write("String");
return;
@ -6460,7 +6450,7 @@ const _super = (function (geti, seti) {
* Here we check if alternative name was provided for a given moduleName and return it if possible.
*/
function tryRenameExternalModule(moduleName: LiteralExpression): string {
if (renamedDependencies && hasProperty(renamedDependencies, moduleName.text)) {
if (renamedDependencies && moduleName.text in renamedDependencies) {
return `"${renamedDependencies[moduleName.text]}"`;
}
return undefined;
@ -6802,7 +6792,7 @@ const _super = (function (geti, seti) {
function collectExternalModuleInfo(sourceFile: SourceFile) {
externalImports = [];
exportSpecifiers = {};
exportSpecifiers = createMap<ExportSpecifier[]>();
exportEquals = undefined;
hasExportStarsToExportValues = false;
for (const node of sourceFile.statements) {
@ -6841,7 +6831,7 @@ const _super = (function (geti, seti) {
// export { x, y }
for (const specifier of (<ExportDeclaration>node).exportClause.elements) {
const name = (specifier.propertyName || specifier.name).text;
getOrUpdateProperty(exportSpecifiers, name, () => []).push(specifier);
(exportSpecifiers[name] || (exportSpecifiers[name] = [])).push(specifier);
}
}
break;
@ -6940,7 +6930,7 @@ const _super = (function (geti, seti) {
}
// local names set should only be added if we have anything exported
if (!exportedDeclarations && isEmpty(exportSpecifiers)) {
if (!exportedDeclarations && !someProperties(exportSpecifiers)) {
// no exported declarations (export var ...) or export specifiers (export {x})
// check if we have any non star export declarations.
let hasExportDeclarationWithExportClause = false;
@ -7080,7 +7070,7 @@ const _super = (function (geti, seti) {
if (hoistedVars) {
writeLine();
write("var ");
const seen: Map<string> = {};
const seen = createMap<string>();
for (let i = 0; i < hoistedVars.length; i++) {
const local = hoistedVars[i];
const name = local.kind === SyntaxKind.Identifier
@ -7090,7 +7080,7 @@ const _super = (function (geti, seti) {
if (name) {
// do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables
const text = unescapeIdentifier(name.text);
if (hasProperty(seen, text)) {
if (text in seen) {
continue;
}
else {
@ -7446,7 +7436,7 @@ const _super = (function (geti, seti) {
writeModuleName(node, emitRelativePathAsModuleName);
write("[");
const groupIndices: Map<number> = {};
const groupIndices = createMap<number>();
const dependencyGroups: DependencyGroup[] = [];
for (let i = 0; i < externalImports.length; i++) {
@ -7459,7 +7449,7 @@ const _super = (function (geti, seti) {
// for deduplication purposes in key remove leading and trailing quotes so 'a' and "a" will be considered the same
const key = text.substr(1, text.length - 2);
if (hasProperty(groupIndices, key)) {
if (key in groupIndices) {
// deduplicate/group entries in dependency list by the dependency name
const groupIndex = groupIndices[key];
dependencyGroups[groupIndex].push(externalImports[i]);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,95 @@
/*@internal*/
namespace ts {
declare const performance: { now?(): number } | undefined;
/** Gets a timestamp with (at least) ms resolution */
export const timestamp = typeof performance !== "undefined" && performance.now ? () => performance.now() : Date.now ? Date.now : () => +(new Date());
}
/*@internal*/
/** Performance measurements for the compiler. */
namespace ts.performance {
declare const onProfilerEvent: { (markName: string): void; profiler: boolean; };
const profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true
? onProfilerEvent
: (markName: string) => { };
let enabled = false;
let profilerStart = 0;
let counts: Map<number>;
let marks: Map<number>;
let measures: Map<number>;
/**
* Marks a performance event.
*
* @param markName The name of the mark.
*/
export function mark(markName: string) {
if (enabled) {
marks[markName] = timestamp();
counts[markName] = (counts[markName] || 0) + 1;
profilerEvent(markName);
}
}
/**
* Adds a performance measurement with the specified name.
*
* @param measureName The name of the performance measurement.
* @param startMarkName The name of the starting mark. If not supplied, the point at which the
* profiler was enabled is used.
* @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
* used.
*/
export function measure(measureName: string, startMarkName?: string, endMarkName?: string) {
if (enabled) {
const end = endMarkName && marks[endMarkName] || timestamp();
const start = startMarkName && marks[startMarkName] || profilerStart;
measures[measureName] = (measures[measureName] || 0) + (end - start);
}
}
/**
* Gets the number of times a marker was encountered.
*
* @param markName The name of the mark.
*/
export function getCount(markName: string) {
return counts && counts[markName] || 0;
}
/**
* Gets the total duration of all measurements with the supplied name.
*
* @param measureName The name of the measure whose durations should be accumulated.
*/
export function getDuration(measureName: string) {
return measures && measures[measureName] || 0;
}
/**
* Iterate over each measure, performing some action
*
* @param cb The action to perform for each measure
*/
export function forEachMeasure(cb: (measureName: string, duration: number) => void) {
for (const key in measures) {
cb(key, measures[key]);
}
}
/** Enables (and resets) performance measurements for the compiler. */
export function enable() {
counts = createMap<number>();
marks = createMap<number>();
measures = createMap<number>();
enabled = true;
profilerStart = timestamp();
}
/** Disables performance measurements for the compiler. */
export function disable() {
enabled = false;
}
}

View File

@ -3,13 +3,8 @@
/// <reference path="core.ts" />
namespace ts {
/* @internal */ export let programTime = 0;
/* @internal */ export let emitTime = 0;
/* @internal */ export let ioReadTime = 0;
/* @internal */ export let ioWriteTime = 0;
/** The version of the TypeScript compiler release */
export const version = "2.0.0";
export const version = "2.1.0";
const emptyArray: any[] = [];
@ -112,13 +107,7 @@ namespace ts {
}
function moduleHasNonRelativeName(moduleName: string): boolean {
if (isRootedDiskPath(moduleName)) {
return false;
}
const i = moduleName.lastIndexOf("./", 1);
const startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === CharacterCodes.dot);
return !startsWithDotSlashOrDotDotSlash;
return !(isRootedDiskPath(moduleName) || isExternalModuleNameRelative(moduleName));
}
interface ModuleResolutionState {
@ -130,49 +119,31 @@ namespace ts {
}
function tryReadTypesSection(packageJsonPath: string, baseDirectory: string, state: ModuleResolutionState): string {
let jsonContent: { typings?: string, types?: string, main?: string };
try {
const jsonText = state.host.readFile(packageJsonPath);
jsonContent = jsonText ? <{ typings?: string, types?: string, main?: string }>JSON.parse(jsonText) : {};
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
jsonContent = {};
const jsonContent = readJson(packageJsonPath, state.host);
function tryReadFromField(fieldName: string) {
if (hasProperty(jsonContent, fieldName)) {
const typesFile = (<any>jsonContent)[fieldName];
if (typeof typesFile === "string") {
const typesFilePath = normalizePath(combinePaths(baseDirectory, typesFile));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath);
}
return typesFilePath;
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
}
}
}
}
let typesFile: string;
let fieldName: string;
// first try to read content of 'typings' section (backward compatibility)
if (jsonContent.typings) {
if (typeof jsonContent.typings === "string") {
fieldName = "typings";
typesFile = jsonContent.typings;
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings);
}
}
}
// then read 'types'
if (!typesFile && jsonContent.types) {
if (typeof jsonContent.types === "string") {
fieldName = "types";
typesFile = jsonContent.types;
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types);
}
}
}
if (typesFile) {
const typesFilePath = normalizePath(combinePaths(baseDirectory, typesFile));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath);
}
const typesFilePath = tryReadFromField("typings") || tryReadFromField("types");
if (typesFilePath) {
return typesFilePath;
}
// Use the main module for inferring types if no types package specified and the allowJs is set
if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") {
if (state.traceEnabled) {
@ -184,6 +155,17 @@ namespace ts {
return undefined;
}
function readJson(path: string, host: ModuleResolutionHost): { typings?: string, types?: string, main?: string } {
try {
const jsonText = host.readFile(path);
return jsonText ? JSON.parse(jsonText) : {};
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
return {};
}
}
const typeReferenceExtensions = [".d.ts"];
function getEffectiveTypeRoots(options: CompilerOptions, host: ModuleResolutionHost) {
@ -519,7 +501,7 @@ namespace ts {
if (state.traceEnabled) {
trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
}
matchedPattern = matchPatternOrExact(getKeys(state.compilerOptions.paths), moduleName);
matchedPattern = matchPatternOrExact(getOwnKeys(state.compilerOptions.paths), moduleName);
}
if (matchedPattern) {
@ -728,7 +710,7 @@ namespace ts {
}
function loadNodeModuleFromDirectory(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
const packageJsonPath = combinePaths(candidate, "package.json");
const packageJsonPath = pathToPackageJson(candidate);
const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
if (directoryExists && state.host.fileExists(packageJsonPath)) {
if (state.traceEnabled) {
@ -758,6 +740,10 @@ namespace ts {
return loadModuleFromFile(combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
}
function pathToPackageJson(directory: string): string {
return combinePaths(directory, "package.json");
}
function loadModuleFromNodeModulesFolder(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string {
const nodeModulesFolder = combinePaths(directory, "node_modules");
const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
@ -842,14 +828,6 @@ namespace ts {
: { resolvedModule: undefined, failedLookupLocations };
}
/* @internal */
export const defaultInitCompilerOptions: CompilerOptions = {
module: ModuleKind.CommonJS,
target: ScriptTarget.ES5,
noImplicitAny: false,
sourceMap: false,
};
interface OutputFingerprint {
hash: string;
byteOrderMark: boolean;
@ -857,7 +835,7 @@ namespace ts {
}
export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost {
const existingDirectories: Map<boolean> = {};
const existingDirectories = createMap<boolean>();
function getCanonicalFileName(fileName: string): string {
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
@ -871,9 +849,10 @@ namespace ts {
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile {
let text: string;
try {
const start = new Date().getTime();
performance.mark("beforeIORead");
text = sys.readFile(fileName, options.charset);
ioReadTime += new Date().getTime() - start;
performance.mark("afterIORead");
performance.measure("I/O Read", "beforeIORead", "afterIORead");
}
catch (e) {
if (onError) {
@ -888,7 +867,7 @@ namespace ts {
}
function directoryExists(directoryPath: string): boolean {
if (hasProperty(existingDirectories, directoryPath)) {
if (directoryPath in existingDirectories) {
return true;
}
if (sys.directoryExists(directoryPath)) {
@ -910,13 +889,13 @@ namespace ts {
function writeFileIfUpdated(fileName: string, data: string, writeByteOrderMark: boolean): void {
if (!outputFingerprints) {
outputFingerprints = {};
outputFingerprints = createMap<OutputFingerprint>();
}
const hash = sys.createHash(data);
const mtimeBefore = sys.getModifiedTime(fileName);
if (mtimeBefore && hasProperty(outputFingerprints, fileName)) {
if (mtimeBefore && fileName in outputFingerprints) {
const fingerprint = outputFingerprints[fileName];
// If output has not been changed, and the file has no external modification
@ -940,7 +919,7 @@ namespace ts {
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) {
try {
const start = new Date().getTime();
performance.mark("beforeIOWrite");
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
if (isWatchSet(options) && sys.createHash && sys.getModifiedTime) {
@ -950,7 +929,8 @@ namespace ts {
sys.writeFile(fileName, data, writeByteOrderMark);
}
ioWriteTime += new Date().getTime() - start;
performance.mark("afterIOWrite");
performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
}
catch (e) {
if (onError) {
@ -1051,16 +1031,11 @@ namespace ts {
return [];
}
const resolutions: T[] = [];
const cache: Map<T> = {};
const cache = createMap<T>();
for (const name of names) {
let result: T;
if (hasProperty(cache, name)) {
result = cache[name];
}
else {
result = loader(name, containingFile);
cache[name] = result;
}
const result = name in cache
? cache[name]
: cache[name] = loader(name, containingFile);
resolutions.push(result);
}
return resolutions;
@ -1081,15 +1056,21 @@ namespace ts {
}
// Walk the primary type lookup locations
let result: string[] = [];
const result: string[] = [];
if (host.directoryExists && host.getDirectories) {
const typeRoots = getEffectiveTypeRoots(options, host);
if (typeRoots) {
for (const root of typeRoots) {
if (host.directoryExists(root)) {
for (const typeDirectivePath of host.getDirectories(root)) {
// Return just the type directive names
result = result.concat(getBaseFileName(normalizePath(typeDirectivePath)));
const normalized = normalizePath(typeDirectivePath);
const packageJsonPath = pathToPackageJson(combinePaths(root, normalized));
// tslint:disable-next-line:no-null-keyword
const isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
if (!isNotNeededPackage) {
// Return just the type directive names
result.push(getBaseFileName(normalized));
}
}
}
}
@ -1106,7 +1087,7 @@ namespace ts {
let noDiagnosticsTypeChecker: TypeChecker;
let classifiableNames: Map<string>;
let resolvedTypeReferenceDirectives: Map<ResolvedTypeReferenceDirective> = {};
let resolvedTypeReferenceDirectives = createMap<ResolvedTypeReferenceDirective>();
let fileProcessingDiagnostics = createDiagnosticCollection();
// The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
@ -1121,12 +1102,12 @@ namespace ts {
// If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
// this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
const modulesWithElidedImports: Map<boolean> = {};
const modulesWithElidedImports = createMap<boolean>();
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
const sourceFilesFoundSearchingNodeModules: Map<boolean> = {};
const sourceFilesFoundSearchingNodeModules = createMap<boolean>();
const start = new Date().getTime();
performance.mark("beforeProgram");
host = host || createCompilerHost(options);
@ -1224,8 +1205,8 @@ namespace ts {
};
verifyCompilerOptions();
programTime += new Date().getTime() - start;
performance.mark("afterProgram");
performance.measure("Program", "beforeProgram", "afterProgram");
return program;
@ -1252,10 +1233,10 @@ namespace ts {
if (!classifiableNames) {
// Initialize a checker so that all our files are bound.
getTypeChecker();
classifiableNames = {};
classifiableNames = createMap<string>();
for (const sourceFile of files) {
copyMap(sourceFile.classifiableNames, classifiableNames);
copyProperties(sourceFile.classifiableNames, classifiableNames);
}
}
@ -1283,7 +1264,7 @@ namespace ts {
(oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) ||
!arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) ||
!arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) ||
!mapIsEqualTo(oldOptions.paths, options.paths)) {
!equalOwnProperties(oldOptions.paths, options.paths)) {
return false;
}
@ -1405,7 +1386,7 @@ namespace ts {
getSourceFile: program.getSourceFile,
getSourceFileByPath: program.getSourceFileByPath,
getSourceFiles: program.getSourceFiles,
isSourceFileFromExternalLibrary: (file: SourceFile) => !!lookUp(sourceFilesFoundSearchingNodeModules, file.path),
isSourceFileFromExternalLibrary: (file: SourceFile) => !!sourceFilesFoundSearchingNodeModules[file.path],
writeFile: writeFileCallback || (
(fileName, data, writeByteOrderMark, onError, sourceFiles) => host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles)),
isEmitBlocked,
@ -1421,7 +1402,7 @@ namespace ts {
}
function emit(sourceFile?: SourceFile, writeFileCallback?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult {
return runWithCancellationToken(() => emitWorker(this, sourceFile, writeFileCallback, cancellationToken));
return runWithCancellationToken(() => emitWorker(program, sourceFile, writeFileCallback, cancellationToken));
}
function isEmitBlocked(emitFileName: string): boolean {
@ -1468,14 +1449,15 @@ namespace ts {
// checked is to not pass the file to getEmitResolver.
const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
const start = new Date().getTime();
performance.mark("beforeEmit");
const emitResult = emitFiles(
emitResolver,
getEmitHost(writeFileCallback),
sourceFile);
emitTime += new Date().getTime() - start;
performance.mark("afterEmit");
performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
}
@ -1942,7 +1924,7 @@ namespace ts {
// If the file was previously found via a node_modules search, but is now being processed as a root file,
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
if (file && lookUp(sourceFilesFoundSearchingNodeModules, file.path) && currentNodeModulesDepth == 0) {
if (file && sourceFilesFoundSearchingNodeModules[file.path] && currentNodeModulesDepth == 0) {
sourceFilesFoundSearchingNodeModules[file.path] = false;
if (!options.noResolve) {
processReferencedFiles(file, getDirectoryPath(fileName), isDefaultLib);
@ -1953,7 +1935,7 @@ namespace ts {
processImportedModules(file, getDirectoryPath(fileName));
}
// See if we need to reprocess the imports due to prior skipped imports
else if (file && lookUp(modulesWithElidedImports, file.path)) {
else if (file && modulesWithElidedImports[file.path]) {
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
modulesWithElidedImports[file.path] = false;
processImportedModules(file, getDirectoryPath(fileName));
@ -2020,15 +2002,17 @@ namespace ts {
}
function processTypeReferenceDirectives(file: SourceFile) {
const typeDirectives = map(file.typeReferenceDirectives, l => l.fileName);
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
const typeDirectives = map(file.typeReferenceDirectives, ref => ref.fileName.toLocaleLowerCase());
const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName);
for (let i = 0; i < typeDirectives.length; i++) {
const ref = file.typeReferenceDirectives[i];
const resolvedTypeReferenceDirective = resolutions[i];
// store resolved type directive on the file
setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective);
processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end);
const fileName = ref.fileName.toLocaleLowerCase();
setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end);
}
}
@ -2053,7 +2037,7 @@ namespace ts {
const otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) {
fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd,
Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict,
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
@ -2093,7 +2077,7 @@ namespace ts {
function processImportedModules(file: SourceFile, basePath: string) {
collectExternalModuleReferences(file);
if (file.imports.length || file.moduleAugmentations.length) {
file.resolvedModules = {};
file.resolvedModules = createMap<ResolvedModule>();
const moduleNames = map(concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral);
const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory));
for (let i = 0; i < moduleNames.length; i++) {
@ -2210,6 +2194,9 @@ namespace ts {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key));
}
if (isArray(options.paths[key])) {
if (options.paths[key].length === 0) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key));
}
for (const subst of options.paths[key]) {
const typeOfSubst = typeof subst;
if (typeOfSubst === "string") {

View File

@ -55,7 +55,7 @@ namespace ts {
tryScan<T>(callback: () => T): T;
}
const textToToken: Map<SyntaxKind> = {
const textToToken = createMap({
"abstract": SyntaxKind.AbstractKeyword,
"any": SyntaxKind.AnyKeyword,
"as": SyntaxKind.AsKeyword,
@ -179,7 +179,7 @@ namespace ts {
"|=": SyntaxKind.BarEqualsToken,
"^=": SyntaxKind.CaretEqualsToken,
"@": SyntaxKind.AtToken,
};
});
/*
As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
@ -274,9 +274,7 @@ namespace ts {
function makeReverseMap(source: Map<number>): string[] {
const result: string[] = [];
for (const name in source) {
if (source.hasOwnProperty(name)) {
result[source[name]] = name;
}
result[source[name]] = name;
}
return result;
}

View File

@ -46,6 +46,7 @@ namespace ts {
export function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter {
const compilerOptions = host.getCompilerOptions();
const extendedDiagnostics = compilerOptions.extendedDiagnostics;
let currentSourceFile: SourceFile;
let sourceMapDir: string; // The directory in which sourcemap will be
let stopOverridingSpan = false;
@ -240,6 +241,10 @@ namespace ts {
return;
}
if (extendedDiagnostics) {
performance.mark("beforeSourcemap");
}
const sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos);
// Convert the location to be one-based.
@ -279,6 +284,11 @@ namespace ts {
}
updateLastEncodedAndRecordedSpans();
if (extendedDiagnostics) {
performance.mark("afterSourcemap");
performance.measure("Source Map", "beforeSourcemap", "afterSourcemap");
}
}
function getStartPos(range: TextRange) {

View File

@ -182,7 +182,7 @@ namespace ts {
return matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
return {
const wscriptSystem: System = {
args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@ -201,7 +201,7 @@ namespace ts {
return fso.FolderExists(path);
},
createDirectory(directoryName: string) {
if (!this.directoryExists(directoryName)) {
if (!wscriptSystem.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@ -221,6 +221,7 @@ namespace ts {
}
}
};
return wscriptSystem;
}
function getNodeSystem(): System {
@ -232,15 +233,15 @@ namespace ts {
const useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"];
function createWatchedFileSet() {
const dirWatchers: Map<DirectoryWatcher> = {};
const dirWatchers = createMap<DirectoryWatcher>();
// One file can have multiple watchers
const fileWatcherCallbacks: Map<FileWatcherCallback[]> = {};
const fileWatcherCallbacks = createMap<FileWatcherCallback[]>();
return { addFile, removeFile };
function reduceDirWatcherRefCountForFile(fileName: string) {
const dirName = getDirectoryPath(fileName);
if (hasProperty(dirWatchers, dirName)) {
const watcher = dirWatchers[dirName];
const watcher = dirWatchers[dirName];
if (watcher) {
watcher.referenceCount -= 1;
if (watcher.referenceCount <= 0) {
watcher.close();
@ -250,13 +251,12 @@ namespace ts {
}
function addDirWatcher(dirPath: string): void {
if (hasProperty(dirWatchers, dirPath)) {
const watcher = dirWatchers[dirPath];
let watcher = dirWatchers[dirPath];
if (watcher) {
watcher.referenceCount += 1;
return;
}
const watcher: DirectoryWatcher = _fs.watch(
watcher = _fs.watch(
dirPath,
{ persistent: true },
(eventName: string, relativeFileName: string) => fileEventHandler(eventName, relativeFileName, dirPath)
@ -267,12 +267,7 @@ namespace ts {
}
function addFileWatcherCallback(filePath: string, callback: FileWatcherCallback): void {
if (hasProperty(fileWatcherCallbacks, filePath)) {
fileWatcherCallbacks[filePath].push(callback);
}
else {
fileWatcherCallbacks[filePath] = [callback];
}
(fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback);
}
function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile {
@ -288,8 +283,9 @@ namespace ts {
}
function removeFileWatcherCallback(filePath: string, callback: FileWatcherCallback) {
if (hasProperty(fileWatcherCallbacks, filePath)) {
const newCallbacks = copyListRemovingItem(callback, fileWatcherCallbacks[filePath]);
const callbacks = fileWatcherCallbacks[filePath];
if (callbacks) {
const newCallbacks = copyListRemovingItem(callback, callbacks);
if (newCallbacks.length === 0) {
delete fileWatcherCallbacks[filePath];
}
@ -305,7 +301,7 @@ namespace ts {
? undefined
: ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath);
// Some applications save a working file via rename operations
if ((eventName === "change" || eventName === "rename") && hasProperty(fileWatcherCallbacks, fileName)) {
if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) {
for (const fileCallback of fileWatcherCallbacks[fileName]) {
fileCallback(fileName);
}
@ -439,7 +435,7 @@ namespace ts {
return filter<string>(_fs.readdirSync(path), p => fileSystemEntryExists(combinePaths(path, p), FileSystemEntryKind.Directory));
}
return {
const nodeSystem: System = {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@ -501,7 +497,7 @@ namespace ts {
fileExists,
directoryExists,
createDirectory(directoryName: string) {
if (!this.directoryExists(directoryName)) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@ -549,6 +545,7 @@ namespace ts {
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem(): System {

View File

@ -122,11 +122,11 @@ namespace ts {
const gutterSeparator = " ";
const resetEscapeSequence = "\u001b[0m";
const ellipsis = "...";
const categoryFormatMap: Map<string> = {
const categoryFormatMap = createMap<string>({
[DiagnosticCategory.Warning]: yellowForegroundEscapeSequence,
[DiagnosticCategory.Error]: redForegroundEscapeSequence,
[DiagnosticCategory.Message]: blueForegroundEscapeSequence,
};
});
function formatAndReset(text: string, formatStyle: string) {
return formatStyle + text + resetEscapeSequence;
@ -432,7 +432,7 @@ namespace ts {
}
// reset the cache of existing files
cachedExistingFiles = {};
cachedExistingFiles = createMap<boolean>();
const compileResult = compile(rootFileNames, compilerOptions, compilerHost);
@ -445,10 +445,9 @@ namespace ts {
}
function cachedFileExists(fileName: string): boolean {
if (hasProperty(cachedExistingFiles, fileName)) {
return cachedExistingFiles[fileName];
}
return cachedExistingFiles[fileName] = hostFileExists(fileName);
return fileName in cachedExistingFiles
? cachedExistingFiles[fileName]
: cachedExistingFiles[fileName] = hostFileExists(fileName);
}
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void) {
@ -550,12 +549,8 @@ namespace ts {
}
function compile(fileNames: string[], compilerOptions: CompilerOptions, compilerHost: CompilerHost) {
ioReadTime = 0;
ioWriteTime = 0;
programTime = 0;
bindTime = 0;
checkTime = 0;
emitTime = 0;
const hasDiagnostics = compilerOptions.diagnostics || compilerOptions.extendedDiagnostics;
if (hasDiagnostics) performance.enable();
const program = createProgram(fileNames, compilerOptions, compilerHost);
const exitStatus = compileProgram();
@ -566,7 +561,7 @@ namespace ts {
});
}
if (compilerOptions.diagnostics) {
if (hasDiagnostics) {
const memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1;
reportCountStatistic("Files", program.getSourceFiles().length);
reportCountStatistic("Lines", countLines(program));
@ -579,17 +574,28 @@ namespace ts {
reportStatisticalValue("Memory used", Math.round(memoryUsed / 1000) + "K");
}
// Individual component times.
// Note: To match the behavior of previous versions of the compiler, the reported parse time includes
// I/O read time and processing time for triple-slash references and module imports, and the reported
// emit time includes I/O write time. We preserve this behavior so we can accurately compare times.
reportTimeStatistic("I/O read", ioReadTime);
reportTimeStatistic("I/O write", ioWriteTime);
reportTimeStatistic("Parse time", programTime);
reportTimeStatistic("Bind time", bindTime);
reportTimeStatistic("Check time", checkTime);
reportTimeStatistic("Emit time", emitTime);
const programTime = performance.getDuration("Program");
const bindTime = performance.getDuration("Bind");
const checkTime = performance.getDuration("Check");
const emitTime = performance.getDuration("Emit");
if (compilerOptions.extendedDiagnostics) {
performance.forEachMeasure((name, duration) => reportTimeStatistic(`${name} time`, duration));
}
else {
// Individual component times.
// Note: To match the behavior of previous versions of the compiler, the reported parse time includes
// I/O read time and processing time for triple-slash references and module imports, and the reported
// emit time includes I/O write time. We preserve this behavior so we can accurately compare times.
reportTimeStatistic("I/O read", performance.getDuration("I/O Read"));
reportTimeStatistic("I/O write", performance.getDuration("I/O Write"));
reportTimeStatistic("Parse time", programTime);
reportTimeStatistic("Bind time", bindTime);
reportTimeStatistic("Check time", checkTime);
reportTimeStatistic("Emit time", emitTime);
}
reportTimeStatistic("Total time", programTime + bindTime + checkTime + emitTime);
performance.disable();
}
return { program, exitStatus };
@ -653,7 +659,7 @@ namespace ts {
// Build up the list of examples.
const padding = makePadding(marginLength);
output += getDiagnosticText(Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine;
output += padding + "tsc --out file.js file.ts" + sys.newLine;
output += padding + "tsc --outFile file.js file.ts" + sys.newLine;
output += padding + "tsc @args.txt" + sys.newLine;
output += sys.newLine;
@ -669,7 +675,7 @@ namespace ts {
const usageColumn: string[] = []; // Things like "-d, --declaration" go in here.
const descriptionColumn: string[] = [];
const optionsDescriptionMap: Map<string[]> = {}; // Map between option.description and list of option.type if it is a kind
const optionsDescriptionMap = createMap<string[]>(); // Map between option.description and list of option.type if it is a kind
for (let i = 0; i < optsList.length; i++) {
const option = optsList[i];
@ -697,9 +703,10 @@ namespace ts {
description = getDiagnosticText(option.description);
const options: string[] = [];
const element = (<CommandLineOptionOfListType>option).element;
forEachKey(<Map<number | string>>element.type, key => {
const typeMap = <Map<number | string>>element.type;
for (const key in typeMap) {
options.push(`'${key}'`);
});
}
optionsDescriptionMap[description] = options;
}
else {
@ -756,68 +763,11 @@ namespace ts {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file), /* host */ undefined);
}
else {
const compilerOptions = extend(options, defaultInitCompilerOptions);
const configurations: any = {
compilerOptions: serializeCompilerOptions(compilerOptions)
};
if (fileNames && fileNames.length) {
// only set the files property if we have at least one file
configurations.files = fileNames;
}
else {
configurations.exclude = ["node_modules"];
if (compilerOptions.outDir) {
configurations.exclude.push(compilerOptions.outDir);
}
}
sys.writeFile(file, JSON.stringify(configurations, undefined, 4));
sys.writeFile(file, JSON.stringify(generateTSConfig(options, fileNames), undefined, 4));
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Successfully_created_a_tsconfig_json_file), /* host */ undefined);
}
return;
function serializeCompilerOptions(options: CompilerOptions): Map<string | number | boolean> {
const result: Map<string | number | boolean> = {};
const optionsNameMap = getOptionNameMap().optionNameMap;
for (const name in options) {
if (hasProperty(options, name)) {
// tsconfig only options cannot be specified via command line,
// so we can assume that only types that can appear here string | number | boolean
const value = <string | number | boolean>options[name];
switch (name) {
case "init":
case "watch":
case "version":
case "help":
case "project":
break;
default:
let optionDefinition = optionsNameMap[name.toLowerCase()];
if (optionDefinition) {
if (typeof optionDefinition.type === "string") {
// string, number or boolean
result[name] = value;
}
else {
// Enum
const typeMap = <Map<number>>optionDefinition.type;
for (const key in typeMap) {
if (hasProperty(typeMap, key)) {
if (typeMap[key] === value)
result[name] = key;
}
}
}
}
break;
}
}
}
return result;
}
}
}

View File

@ -1,8 +1,10 @@
{
"compilerOptions": {
"noImplicitAny": true,
"noImplicitThis": true,
"removeComments": true,
"preserveConstEnums": true,
"pretty": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true,
"declaration": true,
@ -10,6 +12,7 @@
},
"files": [
"core.ts",
"performance.ts",
"sys.ts",
"types.ts",
"scanner.ts",

View File

@ -1,9 +1,13 @@
namespace ts {
export interface Map<T> {
export interface MapLike<T> {
[index: string]: T;
}
export interface Map<T> extends MapLike<T> {
__mapBrand: any;
}
// branded string type used to store absolute, normalized and canonicalized paths
// arbitrary file name can be converted to Path via toPath function
export type Path = string & { __pathBrand: any };
@ -210,7 +214,7 @@ namespace ts {
IntersectionType,
ParenthesizedType,
ThisType,
StringLiteralType,
LiteralType,
// Binding patterns
ObjectBindingPattern,
ArrayBindingPattern,
@ -346,6 +350,7 @@ namespace ts {
JSDocTypedefTag,
JSDocPropertyTag,
JSDocTypeLiteral,
JSDocLiteralType,
// Synthesized list
SyntaxList,
@ -361,7 +366,7 @@ namespace ts {
FirstFutureReservedWord = ImplementsKeyword,
LastFutureReservedWord = YieldKeyword,
FirstTypeNode = TypePredicate,
LastTypeNode = StringLiteralType,
LastTypeNode = LiteralType,
FirstPunctuation = OpenBraceToken,
LastPunctuation = CaretEqualsToken,
FirstToken = Unknown,
@ -376,9 +381,9 @@ namespace ts {
LastBinaryOperator = CaretEqualsToken,
FirstNode = QualifiedName,
FirstJSDocNode = JSDocTypeExpression,
LastJSDocNode = JSDocTypeLiteral,
LastJSDocNode = JSDocLiteralType,
FirstJSDocTagNode = JSDocComment,
LastJSDocTagNode = JSDocTypeLiteral
LastJSDocTagNode = JSDocLiteralType
}
export const enum NodeFlags {
@ -472,6 +477,10 @@ namespace ts {
flags: NodeFlags;
}
export interface Token extends Node {
__tokenTag: any;
}
// @kind(SyntaxKind.AbstractKeyword)
// @kind(SyntaxKind.AsyncKeyword)
// @kind(SyntaxKind.ConstKeyword)
@ -482,7 +491,7 @@ namespace ts {
// @kind(SyntaxKind.PrivateKeyword)
// @kind(SyntaxKind.ProtectedKeyword)
// @kind(SyntaxKind.StaticKeyword)
export interface Modifier extends Node { }
export interface Modifier extends Token { }
// @kind(SyntaxKind.Identifier)
export interface Identifier extends PrimaryExpression {
@ -790,8 +799,9 @@ namespace ts {
}
// @kind(SyntaxKind.StringLiteralType)
export interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode {
export interface LiteralTypeNode extends TypeNode {
_stringLiteralTypeBrand: any;
literal: Expression;
}
// @kind(SyntaxKind.StringLiteral)
@ -977,13 +987,19 @@ namespace ts {
multiLine?: boolean;
}
export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression;
export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression;
// @kind(SyntaxKind.PropertyAccessExpression)
export interface PropertyAccessExpression extends MemberExpression, Declaration {
expression: LeftHandSideExpression;
name: Identifier;
}
export type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression;
/** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */
export interface PropertyAccessEntityNameExpression extends PropertyAccessExpression {
_propertyAccessExpressionLikeQualifiedNameBrand?: any;
expression: EntityNameExpression;
}
// @kind(SyntaxKind.ElementAccessExpression)
export interface ElementAccessExpression extends MemberExpression {
@ -1487,6 +1503,10 @@ namespace ts {
type: JSDocType;
}
export interface JSDocLiteralType extends JSDocType {
literal: LiteralTypeNode;
}
export type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType;
// @kind(SyntaxKind.JSDocRecordMember)
@ -1601,6 +1621,16 @@ namespace ts {
antecedent: FlowNode;
}
export type FlowType = Type | IncompleteType;
// Incomplete types occur during control flow analysis of loops. An IncompleteType
// is distinguished from a regular type by a flags value of zero. Incomplete type
// objects are internal to the getFlowTypeOfRefecence function and never escape it.
export interface IncompleteType {
flags: TypeFlags; // No flags set
type: Type; // The type marked incomplete
}
export interface AmdDependency {
path: string;
name: string;
@ -1912,6 +1942,7 @@ namespace ts {
InElementType = 0x00000040, // Writing an array or union element type
UseFullyQualifiedType = 0x00000080, // Write out the fully qualified type name (eg. Module.Type, instead of Type)
InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type
InTypeAlias = 0x00000200, // Writing type in type alias declaration
}
export const enum SymbolFormatFlags {
@ -2015,7 +2046,7 @@ namespace ts {
writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessibilityResult;
isEntityNameVisible(entityName: EntityName | Expression, enclosingDeclaration: Node): SymbolVisibilityResult;
isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult;
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getReferencedValueDeclaration(reference: Identifier): Declaration;
@ -2024,7 +2055,7 @@ namespace ts {
moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean;
isArgumentsLocalBinding(node: Identifier): boolean;
getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): SourceFile;
getTypeReferenceDirectivesForEntityName(name: EntityName | PropertyAccessExpression): string[];
getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): string[];
getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[];
}
@ -2065,8 +2096,8 @@ namespace ts {
Enum = RegularEnum | ConstEnum,
Variable = FunctionScopedVariable | BlockScopedVariable,
Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor,
Type = Class | Interface | Enum | TypeLiteral | ObjectLiteral | TypeParameter | TypeAlias,
Namespace = ValueModule | NamespaceModule,
Type = Class | Interface | Enum | EnumMember | TypeLiteral | ObjectLiteral | TypeParameter | TypeAlias,
Namespace = ValueModule | NamespaceModule | Enum,
Module = ValueModule | NamespaceModule,
Accessor = GetAccessor | SetAccessor,
@ -2080,7 +2111,7 @@ namespace ts {
ParameterExcludes = Value,
PropertyExcludes = None,
EnumMemberExcludes = Value,
EnumMemberExcludes = Value | Type,
FunctionExcludes = Value & ~(Function | ValueModule),
ClassExcludes = (Value | Type) & ~(ValueModule | Interface), // class-interface mergability done in checker.ts
InterfaceExcludes = Type & ~(Interface | Class),
@ -2131,6 +2162,8 @@ namespace ts {
/* @internal */ exportSymbol?: Symbol; // Exported symbol associated with this symbol
/* @internal */ constEnumOnlyModule?: boolean; // True if module contains only const enums or other modules with only const enums
/* @internal */ isReferenced?: boolean; // True if the symbol is referenced elsewhere
/* @internal */ isReplaceableByMethod?: boolean; // Can this Javascript class property be replaced by a method symbol?
/* @internal */ isAssigned?: boolean; // True if the symbol is a parameter with assignments
}
/* @internal */
@ -2144,6 +2177,8 @@ namespace ts {
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
hasCommonType?: boolean; // True if constituents of synthetic property all have same type
isDiscriminantProperty?: boolean; // True if discriminant synthetic property
resolvedExports?: SymbolTable; // Resolved exports of module
exportsChecked?: boolean; // True if exports of external module have been checked
isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration
@ -2154,9 +2189,7 @@ namespace ts {
/* @internal */
export interface TransientSymbol extends Symbol, SymbolLinks { }
export interface SymbolTable {
[index: string]: Symbol;
}
export type SymbolTable = Map<Symbol>;
/** Represents a "prefix*suffix" pattern. */
/* @internal */
@ -2183,23 +2216,24 @@ namespace ts {
AsyncMethodWithSuper = 0x00000800, // An async method that reads a value from a member of 'super'.
AsyncMethodWithSuperBinding = 0x00001000, // An async method that assigns a value to a member of 'super'.
CaptureArguments = 0x00002000, // Lexical 'arguments' used in body (for async functions)
EnumValuesComputed = 0x00004000, // Values for enum members have been computed, and any errors have been reported for them.
LexicalModuleMergesWithClass = 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration.
LoopWithCapturedBlockScopedBinding = 0x00010000, // Loop that contains block scoped variable captured in closure
CapturedBlockScopedBinding = 0x00020000, // Block-scoped binding that is captured in some function
BlockScopedBindingInLoop = 0x00040000, // Block-scoped binding with declaration nested inside iteration statement
ClassWithBodyScopedClassBinding = 0x00080000, // Decorated class that contains a binding to itself inside of the class body.
BodyScopedClassBinding = 0x00100000, // Binding to a decorated class inside of the class's body.
NeedsLoopOutParameter = 0x00200000, // Block scoped binding whose value should be explicitly copied outside of the converted loop
EnumValuesComputed = 0x00004000, // Values for enum members have been computed, and any errors have been reported for them.
LexicalModuleMergesWithClass = 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration.
LoopWithCapturedBlockScopedBinding = 0x00010000, // Loop that contains block scoped variable captured in closure
CapturedBlockScopedBinding = 0x00020000, // Block-scoped binding that is captured in some function
BlockScopedBindingInLoop = 0x00040000, // Block-scoped binding with declaration nested inside iteration statement
ClassWithBodyScopedClassBinding = 0x00080000, // Decorated class that contains a binding to itself inside of the class body.
BodyScopedClassBinding = 0x00100000, // Binding to a decorated class inside of the class's body.
NeedsLoopOutParameter = 0x00200000, // Block scoped binding whose value should be explicitly copied outside of the converted loop
AssignmentsMarked = 0x00400000, // Parameter assignments have been marked
}
/* @internal */
export interface NodeLinks {
flags?: NodeCheckFlags; // Set of flags specific to Node
resolvedType?: Type; // Cached type of type node
resolvedSignature?: Signature; // Cached signature of signature node or call expression
resolvedSymbol?: Symbol; // Cached name resolution result
resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result
flags?: NodeCheckFlags; // Set of flags specific to Node
enumMemberValue?: number; // Constant value of enum member
isVisible?: boolean; // Is this node visible
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
@ -2211,57 +2245,65 @@ namespace ts {
}
export const enum TypeFlags {
Any = 0x00000001,
String = 0x00000002,
Number = 0x00000004,
Boolean = 0x00000008,
Void = 0x00000010,
Undefined = 0x00000020,
Null = 0x00000040,
Enum = 0x00000080, // Enum type
StringLiteral = 0x00000100, // String literal type
TypeParameter = 0x00000200, // Type parameter
Class = 0x00000400, // Class
Interface = 0x00000800, // Interface
Reference = 0x00001000, // Generic type reference
Tuple = 0x00002000, // Tuple
Union = 0x00004000, // Union (T | U)
Intersection = 0x00008000, // Intersection (T & U)
Anonymous = 0x00010000, // Anonymous
Instantiated = 0x00020000, // Instantiated anonymous type
Any = 1 << 0,
String = 1 << 1,
Number = 1 << 2,
Boolean = 1 << 3,
Enum = 1 << 4,
StringLiteral = 1 << 5,
NumberLiteral = 1 << 6,
BooleanLiteral = 1 << 7,
EnumLiteral = 1 << 8,
ESSymbol = 1 << 9, // Type of symbol primitive introduced in ES6
Void = 1 << 10,
Undefined = 1 << 11,
Null = 1 << 12,
Never = 1 << 13, // Never type
TypeParameter = 1 << 14, // Type parameter
Class = 1 << 15, // Class
Interface = 1 << 16, // Interface
Reference = 1 << 17, // Generic type reference
Tuple = 1 << 18, // Tuple
Union = 1 << 19, // Union (T | U)
Intersection = 1 << 20, // Intersection (T & U)
Anonymous = 1 << 21, // Anonymous
Instantiated = 1 << 22, // Instantiated anonymous type
/* @internal */
FromSignature = 0x00040000, // Created for signature assignment check
ObjectLiteral = 0x00080000, // Originates in an object literal
ObjectLiteral = 1 << 23, // Originates in an object literal
/* @internal */
FreshObjectLiteral = 0x00100000, // Fresh object literal type
FreshObjectLiteral = 1 << 24, // Fresh object literal type
/* @internal */
ContainsWideningType = 0x00200000, // Type is or contains undefined or null widening type
ContainsWideningType = 1 << 25, // Type is or contains undefined or null widening type
/* @internal */
ContainsObjectLiteral = 0x00400000, // Type is or contains object literal type
ContainsObjectLiteral = 1 << 26, // Type is or contains object literal type
/* @internal */
ContainsAnyFunctionType = 0x00800000, // Type is or contains object literal type
ESSymbol = 0x01000000, // Type of symbol primitive introduced in ES6
ThisType = 0x02000000, // This type
ObjectLiteralPatternWithComputedProperties = 0x04000000, // Object literal type implied by binding pattern has computed properties
Never = 0x08000000, // Never type
ContainsAnyFunctionType = 1 << 27, // Type is or contains object literal type
ThisType = 1 << 28, // This type
ObjectLiteralPatternWithComputedProperties = 1 << 29, // Object literal type implied by binding pattern has computed properties
/* @internal */
Nullable = Undefined | Null,
Literal = StringLiteral | NumberLiteral | BooleanLiteral | EnumLiteral,
/* @internal */
Falsy = Void | Undefined | Null, // TODO: Add false, 0, and ""
DefinitelyFalsy = StringLiteral | NumberLiteral | BooleanLiteral | Void | Undefined | Null,
PossiblyFalsy = DefinitelyFalsy | String | Number | Boolean,
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null | Never,
Intrinsic = Any | String | Number | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never,
/* @internal */
Primitive = String | Number | Boolean | ESSymbol | Void | Undefined | Null | StringLiteral | Enum,
Primitive = String | Number | Boolean | Enum | ESSymbol | Void | Undefined | Null | Literal,
StringLike = String | StringLiteral,
NumberLike = Number | Enum,
NumberLike = Number | NumberLiteral | Enum | EnumLiteral,
BooleanLike = Boolean | BooleanLiteral,
EnumLike = Enum | EnumLiteral,
ObjectType = Class | Interface | Reference | Tuple | Anonymous,
UnionOrIntersection = Union | Intersection,
StructuredType = ObjectType | Union | Intersection,
StructuredOrTypeParameter = StructuredType | TypeParameter,
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
Narrowable = Any | StructuredType | TypeParameter | StringLike | NumberLike | Boolean | ESSymbol,
Narrowable = Any | StructuredType | TypeParameter | StringLike | NumberLike | BooleanLike | ESSymbol,
NotUnionOrUnit = Any | String | Number | ESSymbol | ObjectType,
/* @internal */
RequiresWidening = ContainsWideningType | ContainsObjectLiteral,
/* @internal */
@ -2276,6 +2318,8 @@ namespace ts {
/* @internal */ id: number; // Unique ID
symbol?: Symbol; // Symbol associated with type (if any)
pattern?: DestructuringPattern; // Destructuring pattern represented by type (if any)
aliasSymbol?: Symbol; // Alias associated with type
aliasTypeArguments?: Type[]; // Alias type arguments (if any)
}
/* @internal */
@ -2285,10 +2329,20 @@ namespace ts {
}
// String literal types (TypeFlags.StringLiteral)
export interface StringLiteralType extends Type {
export interface LiteralType extends Type {
text: string; // Text of string literal
}
// Enum types (TypeFlags.Enum)
export interface EnumType extends Type {
memberTypes: Map<EnumLiteralType>;
}
// Enum types (TypeFlags.EnumLiteral)
export interface EnumLiteralType extends LiteralType {
baseType: EnumType & UnionType;
}
// Object types (TypeFlags.ObjectType)
export interface ObjectType extends Type { }
@ -2333,14 +2387,15 @@ namespace ts {
export interface TupleType extends ObjectType {
elementTypes: Type[]; // Element types
thisType?: Type; // This-type of tuple (only needed for tuples that are constraints of type parameters)
}
export interface UnionOrIntersectionType extends Type {
types: Type[]; // Constituent types
/* @internal */
reducedType: Type; // Reduced union type (all subtypes removed)
/* @internal */
resolvedProperties: SymbolTable; // Cache of resolved properties
/* @internal */
couldContainTypeParameters: boolean;
}
export interface UnionType extends UnionOrIntersectionType { }
@ -2409,7 +2464,7 @@ namespace ts {
/* @internal */
hasRestParameter: boolean; // True if last parameter is rest parameter
/* @internal */
hasStringLiterals: boolean; // True if specialized
hasLiteralTypes: boolean; // True if specialized
/* @internal */
target?: Signature; // Instantiation target
/* @internal */
@ -2439,6 +2494,7 @@ 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).
@ -2518,7 +2574,7 @@ namespace ts {
}
export type RootPaths = string[];
export type PathSubstitutions = Map<string[]>;
export type PathSubstitutions = MapLike<string[]>;
export type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
export type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions;
@ -2535,6 +2591,7 @@ namespace ts {
declaration?: boolean;
declarationDir?: string;
/* @internal */ diagnostics?: boolean;
/* @internal */ extendedDiagnostics?: boolean;
disableSizeLimit?: boolean;
emitBOM?: boolean;
emitDecoratorMetadata?: boolean;
@ -2677,7 +2734,7 @@ namespace ts {
fileNames: string[];
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: Map<WatchDirectoryFlags>;
wildcardDirectories?: MapLike<WatchDirectoryFlags>;
}
export const enum WatchDirectoryFlags {
@ -2687,7 +2744,7 @@ namespace ts {
export interface ExpandResult {
fileNames: string[];
wildcardDirectories: Map<WatchDirectoryFlags>;
wildcardDirectories: MapLike<WatchDirectoryFlags>;
}
/* @internal */
@ -2709,7 +2766,7 @@ namespace ts {
/* @internal */
export interface CommandLineOptionOfCustomType extends CommandLineOptionBase {
type: Map<number | string>; // an object literal mapping named values to actual values
type: Map<number | string>; // an object literal mapping named values to actual values
}
/* @internal */

View File

@ -87,25 +87,6 @@ namespace ts {
return node.end - node.pos;
}
export function mapIsEqualTo<T>(map1: Map<T>, map2: Map<T>): boolean {
if (!map1 || !map2) {
return map1 === map2;
}
return containsAll(map1, map2) && containsAll(map2, map1);
}
function containsAll<T>(map: Map<T>, other: Map<T>): boolean {
for (const key in map) {
if (!hasProperty(map, key)) {
continue;
}
if (!hasProperty(other, key) || map[key] !== other[key]) {
return false;
}
}
return true;
}
export function arrayIsEqualTo<T>(array1: T[], array2: T[], equaler?: (a: T, b: T) => boolean): boolean {
if (!array1 || !array2) {
return array1 === array2;
@ -126,7 +107,7 @@ namespace ts {
}
export function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean {
return sourceFile.resolvedModules && hasProperty(sourceFile.resolvedModules, moduleNameText);
return !!(sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]);
}
export function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModule {
@ -135,7 +116,7 @@ namespace ts {
export function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModule): void {
if (!sourceFile.resolvedModules) {
sourceFile.resolvedModules = {};
sourceFile.resolvedModules = createMap<ResolvedModule>();
}
sourceFile.resolvedModules[moduleNameText] = resolvedModule;
@ -143,7 +124,7 @@ namespace ts {
export function setResolvedTypeReferenceDirective(sourceFile: SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective): void {
if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
sourceFile.resolvedTypeReferenceDirectiveNames = {};
sourceFile.resolvedTypeReferenceDirectiveNames = createMap<ResolvedTypeReferenceDirective>();
}
sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective;
@ -166,7 +147,7 @@ namespace ts {
}
for (let i = 0; i < names.length; i++) {
const newResolution = newResolutions[i];
const oldResolution = oldResolutions && hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined;
const oldResolution = oldResolutions && oldResolutions[names[i]];
const changed =
oldResolution
? !newResolution || !comparer(oldResolution, newResolution)
@ -1033,14 +1014,14 @@ namespace ts {
&& (<PropertyAccessExpression | ElementAccessExpression>node).expression.kind === SyntaxKind.SuperKeyword;
}
export function getEntityNameFromTypeNode(node: TypeNode): EntityName | Expression {
export function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression {
if (node) {
switch (node.kind) {
case SyntaxKind.TypeReference:
return (<TypeReferenceNode>node).typeName;
case SyntaxKind.ExpressionWithTypeArguments:
return (<ExpressionWithTypeArguments>node).expression;
Debug.assert(isEntityNameExpression((<ExpressionWithTypeArguments>node).expression));
return <EntityNameExpression>(<ExpressionWithTypeArguments>node).expression;
case SyntaxKind.Identifier:
case SyntaxKind.QualifiedName:
return (<EntityName><Node>node);
@ -1218,7 +1199,7 @@ namespace ts {
export function isExternalModuleNameRelative(moduleName: string): boolean {
// TypeScript 1.0 spec (April 2014): 11.2.1
// An external module name is "relative" if the first term is "." or "..".
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
return /^\.\.?($|[\\/])/.test(moduleName);
}
export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) {
@ -1523,7 +1504,7 @@ namespace ts {
continue;
}
return parent.kind === SyntaxKind.BinaryExpression &&
(<BinaryExpression>parent).operatorToken.kind === SyntaxKind.EqualsToken &&
isAssignmentOperator((<BinaryExpression>parent).operatorToken.kind) &&
(<BinaryExpression>parent).left === node ||
(parent.kind === SyntaxKind.ForInStatement || parent.kind === SyntaxKind.ForOfStatement) &&
(<ForInStatement | ForOfStatement>parent).initializer === node;
@ -1694,8 +1675,8 @@ namespace ts {
// import * as <symbol> from ...
// import { x as <symbol> } from ...
// export { x as <symbol> } from ...
// export = ...
// export default ...
// export = <EntityNameExpression>
// export default <EntityNameExpression>
export function isAliasSymbolDeclaration(node: Node): boolean {
return node.kind === SyntaxKind.ImportEqualsDeclaration ||
node.kind === SyntaxKind.NamespaceExportDeclaration ||
@ -1703,7 +1684,11 @@ namespace ts {
node.kind === SyntaxKind.NamespaceImport ||
node.kind === SyntaxKind.ImportSpecifier ||
node.kind === SyntaxKind.ExportSpecifier ||
node.kind === SyntaxKind.ExportAssignment && (<ExportAssignment>node).expression.kind === SyntaxKind.Identifier;
node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(<ExportAssignment>node);
}
export function exportAssignmentIsAlias(node: ExportAssignment): boolean {
return isEntityNameExpression(node.expression);
}
export function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration | InterfaceDeclaration) {
@ -1966,7 +1951,7 @@ namespace ts {
export function createDiagnosticCollection(): DiagnosticCollection {
let nonFileDiagnostics: Diagnostic[] = [];
const fileDiagnostics: Map<Diagnostic[]> = {};
const fileDiagnostics = createMap<Diagnostic[]>();
let diagnosticsModified = false;
let modificationCount = 0;
@ -1984,12 +1969,11 @@ namespace ts {
}
function reattachFileDiagnostics(newFile: SourceFile): void {
if (!hasProperty(fileDiagnostics, newFile.fileName)) {
return;
}
for (const diagnostic of fileDiagnostics[newFile.fileName]) {
diagnostic.file = newFile;
const diagnostics = fileDiagnostics[newFile.fileName];
if (diagnostics) {
for (const diagnostic of diagnostics) {
diagnostic.file = newFile;
}
}
}
@ -2030,9 +2014,7 @@ namespace ts {
forEach(nonFileDiagnostics, pushDiagnostic);
for (const key in fileDiagnostics) {
if (hasProperty(fileDiagnostics, key)) {
forEach(fileDiagnostics[key], pushDiagnostic);
}
forEach(fileDiagnostics[key], pushDiagnostic);
}
return sortAndDeduplicateDiagnostics(allDiagnostics);
@ -2047,9 +2029,7 @@ namespace ts {
nonFileDiagnostics = sortAndDeduplicateDiagnostics(nonFileDiagnostics);
for (const key in fileDiagnostics) {
if (hasProperty(fileDiagnostics, key)) {
fileDiagnostics[key] = sortAndDeduplicateDiagnostics(fileDiagnostics[key]);
}
fileDiagnostics[key] = sortAndDeduplicateDiagnostics(fileDiagnostics[key]);
}
}
}
@ -2060,7 +2040,7 @@ namespace ts {
// the map below must be updated. Note that this regexp *does not* include the 'delete' character.
// There is no reason for this other than that JSON.stringify does not handle it either.
const escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
const escapedCharsMap: Map<string> = {
const escapedCharsMap = createMap({
"\0": "\\0",
"\t": "\\t",
"\v": "\\v",
@ -2073,7 +2053,7 @@ namespace ts {
"\u2028": "\\u2028", // lineSeparator
"\u2029": "\\u2029", // paragraphSeparator
"\u0085": "\\u0085" // nextLine
};
});
/**
@ -2681,22 +2661,9 @@ namespace ts {
isClassLike(node.parent.parent);
}
// Returns false if this heritage clause element's expression contains something unsupported
// (i.e. not a name or dotted name).
export function isSupportedExpressionWithTypeArguments(node: ExpressionWithTypeArguments): boolean {
return isSupportedExpressionWithTypeArgumentsRest(node.expression);
}
function isSupportedExpressionWithTypeArgumentsRest(node: Expression): boolean {
if (node.kind === SyntaxKind.Identifier) {
return true;
}
else if (isPropertyAccessExpression(node)) {
return isSupportedExpressionWithTypeArgumentsRest(node.expression);
}
else {
return false;
}
export function isEntityNameExpression(node: Expression): node is EntityNameExpression {
return node.kind === SyntaxKind.Identifier ||
node.kind === SyntaxKind.PropertyAccessExpression && isEntityNameExpression((<PropertyAccessExpression>node).expression);
}
export function isRightSideOfQualifiedNameOrPropertyAccess(node: Node) {
@ -2806,7 +2773,7 @@ namespace ts {
}
function stringifyObject(value: any) {
return `{${reduceProperties(value, stringifyProperty, "")}}`;
return `{${reduceOwnProperties(value, stringifyProperty, "")}}`;
}
function stringifyProperty(memo: string, value: any, key: string) {
@ -3114,13 +3081,4 @@ namespace ts {
export function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean {
return node.flags & NodeFlags.ParameterPropertyModifier && node.parent.kind === SyntaxKind.Constructor && isClassLike(node.parent.parent);
}
export function startsWith(str: string, prefix: string): boolean {
return str.lastIndexOf(prefix, 0) === 0;
}
export function endsWith(str: string, suffix: string): boolean {
const expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
}

View File

@ -50,7 +50,9 @@ class CompilerBaselineRunner extends RunnerBase {
}
private makeUnitName(name: string, root: string) {
return ts.isRootedDiskPath(name) ? name : ts.combinePaths(root, name);
const path = ts.toPath(name, root, (fileName) => Harness.Compiler.getCanonicalFileName(fileName));
const pathStart = ts.toPath(Harness.IO.getCurrentDirectory(), "", (fileName) => Harness.Compiler.getCanonicalFileName(fileName));
return pathStart ? path.replace(pathStart, "/") : path;
};
public checkTestCodeOutput(fileName: string) {
@ -289,8 +291,8 @@ class CompilerBaselineRunner extends RunnerBase {
const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true);
const fullResults: ts.Map<TypeWriterResult[]> = {};
const pullResults: ts.Map<TypeWriterResult[]> = {};
const fullResults = ts.createMap<TypeWriterResult[]>();
const pullResults = ts.createMap<TypeWriterResult[]>();
for (const sourceFile of allFiles) {
fullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);

View File

@ -1,179 +0,0 @@
// Type definitions for chai 1.7.2
// Project: http://chaijs.com/
// Definitions by: Jed Hunsaker <https://github.com/jedhunsaker/>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
declare module chai {
function expect(target: any, message?: string): Expect;
// Provides a way to extend the internals of Chai
function use(fn: (chai: any, utils: any) => void): any;
interface ExpectStatic {
(target: any): Expect;
}
interface Assertions {
attr(name: string, value?: string): any;
css(name: string, value?: string): any;
data(name: string, value?: string): any;
class(className: string): any;
id(id: string): any;
html(html: string): any;
text(text: string): any;
value(value: string): any;
visible: any;
hidden: any;
selected: any;
checked: any;
disabled: any;
empty: any;
exist: any;
}
interface Expect extends LanguageChains, NumericComparison, TypeComparison, Assertions {
not: Expect;
deep: Deep;
a: TypeComparison;
an: TypeComparison;
include: Include;
contain: Include;
ok: Expect;
true: Expect;
false: Expect;
null: Expect;
undefined: Expect;
exist: Expect;
empty: Expect;
arguments: Expect;
Arguments: Expect;
equal: Equal;
equals: Equal;
eq: Equal;
eql: Equal;
eqls: Equal;
property: Property;
ownProperty: OwnProperty;
haveOwnProperty: OwnProperty;
length: Length;
lengthOf: Length;
match(RegularExpression: RegExp, message?: string): Expect;
string(string: string, message?: string): Expect;
keys: Keys;
key(string: string): Expect;
throw: Throw;
throws: Throw;
Throw: Throw;
respondTo(method: string, message?: string): Expect;
itself: Expect;
satisfy(matcher: Function, message?: string): Expect;
closeTo(expected: number, delta: number, message?: string): Expect;
members: Members;
}
interface LanguageChains {
to: Expect;
be: Expect;
been: Expect;
is: Expect;
that: Expect;
and: Expect;
have: Expect;
with: Expect;
at: Expect;
of: Expect;
same: Expect;
}
interface NumericComparison {
above: NumberComparer;
gt: NumberComparer;
greaterThan: NumberComparer;
least: NumberComparer;
gte: NumberComparer;
below: NumberComparer;
lt: NumberComparer;
lessThan: NumberComparer;
most: NumberComparer;
lte: NumberComparer;
within(start: number, finish: number, message?: string): Expect;
}
interface NumberComparer {
(value: number, message?: string): Expect;
}
interface TypeComparison {
(type: string, message?: string): Expect;
instanceof: InstanceOf;
instanceOf: InstanceOf;
}
interface InstanceOf {
(constructor: Object, message?: string): Expect;
}
interface Deep {
equal: Equal;
property: Property;
}
interface Equal {
(value: any, message?: string): Expect;
}
interface Property {
(name: string, value?: any, message?: string): Expect;
}
interface OwnProperty {
(name: string, message?: string): Expect;
}
interface Length extends LanguageChains, NumericComparison {
(length: number, message?: string): Expect;
}
interface Include {
(value: Object, message?: string): Expect;
(value: string, message?: string): Expect;
(value: number, message?: string): Expect;
keys: Keys;
members: Members;
}
interface Keys {
(...keys: string[]): Expect;
(keys: any[]): Expect;
}
interface Members {
(set: any[], message?: string): Expect;
}
interface Throw {
(): Expect;
(expected: string, message?: string): Expect;
(expected: RegExp, message?: string): Expect;
(constructor: Error, expected?: string, message?: string): Expect;
(constructor: Error, expected?: RegExp, message?: string): Expect;
(constructor: Function, expected?: string, message?: string): Expect;
(constructor: Function, expected?: RegExp, message?: string): Expect;
}
function assert(expression: any, message?: string): void;
module assert {
function equal(actual: any, expected: any, message?: string): void;
function notEqual(actual: any, expected: any, message?: string): void;
function deepEqual<T>(actual: T, expected: T, message?: string): void;
function notDeepEqual<T>(actual: T, expected: T, message?: string): void;
function lengthOf(object: any[], length: number, message?: string): void;
function isTrue(value: any, message?: string): void;
function isFalse(value: any, message?: string): void;
function isOk(actual: any, message?: string): void;
function isUndefined(value: any, message?: string): void;
function isDefined(value: any, message?: string): void;
}
}

View File

@ -1,45 +0,0 @@
// Type definitions for mocha 1.9.0
// Project: http://visionmedia.github.io/mocha/
// Definitions by: Kazi Manzur Rashid <https://github.com/kazimanzurrashid/>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
declare var describe : {
(description: string, spec: () => void): void;
only(description: string, spec: () => void): void;
skip(description: string, spec: () => void): void;
timeout(ms: number): void;
}
declare var it: {
(expectation: string, assertion?: () => void): void;
(expectation: string, assertion?: (done: () => void) => void): void;
only(expectation: string, assertion?: () => void): void;
only(expectation: string, assertion?: (done: () => void) => void): void;
skip(expectation: string, assertion?: () => void): void;
skip(expectation: string, assertion?: (done: () => void) => void): void;
timeout(ms: number): void;
};
/** Runs once before any 'it' blocks in the current 'describe' are run */
declare function before(action: () => void): void;
/** Runs once before any 'it' blocks in the current 'describe' are run */
declare function before(action: (done: () => void) => void): void;
/** Runs once after all 'it' blocks in the current 'describe' are run */
declare function after(action: () => void): void;
/** Runs once after all 'it' blocks in the current 'describe' are run */
declare function after(action: (done: () => void) => void): void;
/** Runs before each individual 'it' block in the current 'describe' is run */
declare function beforeEach(action: () => void): void;
/** Runs before each individual 'it' block in the current 'describe' is run */
declare function beforeEach(action: (done: () => void) => void): void;
/** Runs after each individual 'it' block in the current 'describe' is run */
declare function afterEach(action: () => void): void;
/** Runs after each individual 'it' block in the current 'describe' is run */
declare function afterEach(action: (done: () => void) => void): void;

File diff suppressed because it is too large Load Diff

View File

@ -95,14 +95,14 @@ namespace FourSlash {
export import IndentStyle = ts.IndentStyle;
const entityMap: ts.Map<string> = {
const entityMap = ts.createMap({
"&": "&amp;",
"\"": "&quot;",
"'": "&#39;",
"/": "&#47;",
"<": "&lt;",
">": "&gt;"
};
});
export function escapeXmlAttributeValue(s: string) {
return s.replace(/[&<>"'\/]/g, ch => entityMap[ch]);
@ -204,7 +204,7 @@ namespace FourSlash {
public formatCodeOptions: ts.FormatCodeOptions;
private inputFiles: ts.Map<string> = {}; // Map between inputFile's fileName and its content for easily looking up when resolving references
private inputFiles = ts.createMap<string>(); // Map between inputFile's fileName and its content for easily looking up when resolving references
// Add input file which has matched file name with the given reference-file path.
// This is necessary when resolveReference flag is specified
@ -249,6 +249,7 @@ namespace FourSlash {
if (compilationOptions.typeRoots) {
compilationOptions.typeRoots = compilationOptions.typeRoots.map(p => ts.getNormalizedAbsolutePath(p, this.basePath));
}
compilationOptions.skipDefaultLibCheck = true;
const languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions);
this.languageServiceAdapterHost = languageServiceAdapter.getHost();
@ -300,11 +301,11 @@ namespace FourSlash {
}
else {
// resolveReference file-option is not specified then do not resolve any files and include all inputFiles
ts.forEachKey(this.inputFiles, fileName => {
for (const fileName in this.inputFiles) {
if (!Harness.isDefaultLibraryFile(fileName)) {
this.languageServiceAdapterHost.addScript(fileName, this.inputFiles[fileName], /*isRootFile*/ true);
}
});
}
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName,
Harness.Compiler.getDefaultLibrarySourceFile().text, /*isRootFile*/ false);
}
@ -376,7 +377,7 @@ namespace FourSlash {
public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) {
const startMarker = this.getMarkerByName(startMarkerName);
const endMarker = this.getMarkerByName(endMarkerName);
const predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
const predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false;
};
@ -428,12 +429,12 @@ namespace FourSlash {
let predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean;
if (after) {
predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar >= startPos) && (errorLimChar >= startPos)) ? true : false;
};
}
else {
predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar <= startPos) && (errorLimChar <= startPos)) ? true : false;
};
}
@ -458,7 +459,7 @@ namespace FourSlash {
endPos = endMarker.position;
}
errors.forEach(function (error: ts.Diagnostic) {
errors.forEach(function(error: ts.Diagnostic) {
if (predicate(error.start, error.start + error.length, startPos, endPos)) {
exists = true;
}
@ -475,7 +476,7 @@ namespace FourSlash {
Harness.IO.log("Unexpected error(s) found. Error list is:");
}
errors.forEach(function (error: ts.Diagnostic) {
errors.forEach(function(error: ts.Diagnostic) {
Harness.IO.log(" minChar: " + error.start +
", limChar: " + (error.start + error.length) +
", message: " + ts.flattenDiagnosticMessageText(error.messageText, Harness.IO.newLine()) + "\n");
@ -593,9 +594,9 @@ namespace FourSlash {
public noItemsWithSameNameButDifferentKind(): void {
const completions = this.getCompletionListAtCaret();
const uniqueItems: ts.Map<string> = {};
const uniqueItems = ts.createMap<string>();
for (const item of completions.entries) {
if (!ts.hasProperty(uniqueItems, item.name)) {
if (!(item.name in uniqueItems)) {
uniqueItems[item.name] = item.kind;
}
else {
@ -773,7 +774,7 @@ namespace FourSlash {
}
public verifyRangesWithSameTextReferenceEachOther() {
ts.forEachValue(this.rangesByText(), ranges => this.verifyRangesReferenceEachOther(ranges));
ts.forEachProperty(this.rangesByText(), ranges => this.verifyRangesReferenceEachOther(ranges));
}
private verifyReferencesWorker(references: ts.ReferenceEntry[], fileName: string, start: number, end: number, isWriteAccess?: boolean, isDefinition?: boolean) {
@ -1348,14 +1349,7 @@ namespace FourSlash {
}
// Enters lines of text at the current caret position
public type(text: string) {
return this.typeHighFidelity(text);
}
// Enters lines of text at the current caret position, invoking
// language service APIs to mimic Visual Studio's behavior
// as much as possible
private typeHighFidelity(text: string) {
public type(text: string, highFidelity = false) {
let offset = this.currentCaretPosition;
const prevChar = " ";
const checkCadence = (text.length >> 2) + 1;
@ -1364,24 +1358,26 @@ namespace FourSlash {
// Make the edit
const ch = text.charAt(i);
this.languageServiceAdapterHost.editScript(this.activeFile.fileName, offset, offset, ch);
this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, offset);
if (highFidelity) {
this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, offset);
}
this.updateMarkersForEdit(this.activeFile.fileName, offset, offset, ch);
offset++;
if (ch === "(" || ch === ",") {
/* Signature help*/
this.languageService.getSignatureHelpItems(this.activeFile.fileName, offset);
}
else if (prevChar === " " && /A-Za-z_/.test(ch)) {
/* Completions */
this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset);
}
if (highFidelity) {
if (ch === "(" || ch === ",") {
/* Signature help*/
this.languageService.getSignatureHelpItems(this.activeFile.fileName, offset);
}
else if (prevChar === " " && /A-Za-z_/.test(ch)) {
/* Completions */
this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset);
}
if (i % checkCadence === 0) {
this.checkPostEditInvariants();
// this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
// this.languageService.getSemanticDiagnostics(this.activeFile.fileName);
if (i % checkCadence === 0) {
this.checkPostEditInvariants();
}
}
// Handle post-keystroke formatting
@ -1389,14 +1385,12 @@ namespace FourSlash {
const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions);
if (edits.length) {
offset += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
// this.checkPostEditInvariants();
}
}
}
// Move the caret to wherever we ended up
this.currentCaretPosition = offset;
this.fixCaretPosition();
this.checkPostEditInvariants();
}
@ -1415,7 +1409,6 @@ namespace FourSlash {
const edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions);
if (edits.length) {
offset += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
this.checkPostEditInvariants();
}
}
@ -1639,10 +1632,11 @@ namespace FourSlash {
}
public rangesByText(): ts.Map<Range[]> {
const result: ts.Map<Range[]> = {};
const result = ts.createMap<Range[]>();
for (const range of this.getRanges()) {
const text = this.rangeText(range);
(ts.getProperty(result, text) || (result[text] = [])).push(range);
const ranges = result[text] || (result[text] = []);
ranges.push(range);
}
return result;
}
@ -1897,7 +1891,7 @@ namespace FourSlash {
public verifyBraceCompletionAtPosition(negative: boolean, openingBrace: string) {
const openBraceMap: ts.Map<ts.CharacterCodes> = {
const openBraceMap = ts.createMap<ts.CharacterCodes>({
"(": ts.CharacterCodes.openParen,
"{": ts.CharacterCodes.openBrace,
"[": ts.CharacterCodes.openBracket,
@ -1905,7 +1899,7 @@ namespace FourSlash {
'"': ts.CharacterCodes.doubleQuote,
"`": ts.CharacterCodes.backtick,
"<": ts.CharacterCodes.lessThan
};
});
const charCode = openBraceMap[openingBrace];
@ -2269,40 +2263,12 @@ namespace FourSlash {
export function runFourSlashTestContent(basePath: string, testType: FourSlashTestType, content: string, fileName: string): void {
// Parse out the files and their metadata
const testData = parseTestData(basePath, content, fileName);
const state = new TestState(basePath, testType, testData);
let result = "";
const fourslashFile: Harness.Compiler.TestFile = {
unitName: Harness.Compiler.fourslashFileName,
content: undefined,
};
const testFile: Harness.Compiler.TestFile = {
unitName: fileName,
content: content
};
const host = Harness.Compiler.createCompilerHost(
[fourslashFile, testFile],
(fn, contents) => result = contents,
ts.ScriptTarget.Latest,
Harness.IO.useCaseSensitiveFileNames(),
Harness.IO.getCurrentDirectory());
const program = ts.createProgram([Harness.Compiler.fourslashFileName, fileName], { outFile: "fourslashTestOutput.js", noResolve: true, target: ts.ScriptTarget.ES3 }, host);
const sourceFile = host.getSourceFile(fileName, ts.ScriptTarget.ES3);
const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);
if (diagnostics.length > 0) {
throw new Error(`Error compiling ${fileName}: ` +
diagnostics.map(e => ts.flattenDiagnosticMessageText(e.messageText, Harness.IO.newLine())).join("\r\n"));
const output = ts.transpileModule(content, { reportDiagnostics: true });
if (output.diagnostics.length > 0) {
throw new Error(`Syntax error in ${basePath}: ${output.diagnostics[0].messageText}`);
}
program.emit(sourceFile);
ts.Debug.assert(!!result);
runCode(result, state);
runCode(output.outputText, state);
}
function runCode(code: string, state: TestState): void {
@ -2395,13 +2361,14 @@ ${code}
// Comment line, check for global/file @options and record them
const match = optionRegex.exec(line.substr(2));
if (match) {
const fileMetadataNamesIndex = fileMetadataNames.indexOf(match[1]);
const [key, value] = match.slice(1);
const fileMetadataNamesIndex = fileMetadataNames.indexOf(key);
if (fileMetadataNamesIndex === -1) {
// Check if the match is already existed in the global options
if (globalOptions[match[1]] !== undefined) {
throw new Error("Global Option : '" + match[1] + "' is already existed");
if (globalOptions[key] !== undefined) {
throw new Error(`Global option '${key}' already exists`);
}
globalOptions[match[1]] = match[2];
globalOptions[key] = value;
}
else {
if (fileMetadataNamesIndex === fileMetadataNames.indexOf(metadataOptionNames.fileName)) {
@ -2416,12 +2383,12 @@ ${code}
resetLocalData();
}
currentFileName = basePath + "/" + match[2];
currentFileOptions[match[1]] = match[2];
currentFileName = basePath + "/" + value;
currentFileOptions[key] = value;
}
else {
// Add other fileMetadata flag
currentFileOptions[match[1]] = match[2];
currentFileOptions[key] = value;
}
}
}
@ -2509,7 +2476,7 @@ ${code}
}
const marker: Marker = {
fileName: fileName,
fileName,
position: location.position,
data: markerValue
};
@ -2526,7 +2493,7 @@ ${code}
function recordMarker(fileName: string, location: LocationInformation, name: string, markerMap: MarkerMap, markers: Marker[]): Marker {
const marker: Marker = {
fileName: fileName,
fileName,
position: location.position
};

View File

@ -18,12 +18,13 @@
/// <reference path="..\services\shims.ts" />
/// <reference path="..\server\session.ts" />
/// <reference path="..\server\client.ts" />
/// <reference path="..\server\node.d.ts" />
/// <reference path="external\mocha.d.ts"/>
/// <reference path="external\chai.d.ts"/>
/// <reference path="sourceMapRecorder.ts"/>
/// <reference path="runnerbase.ts"/>
/// <reference path="virtualFileSystem.ts" />
/// <reference types="node" />
/// <reference types="mocha" />
/// <reference types="chai" />
// Block scoped definitions work poorly for global variables, temporarily enable var
/* tslint:disable:no-var-keyword */
@ -32,7 +33,13 @@
var _chai: typeof chai = require("chai");
var assert: typeof _chai.assert = _chai.assert;
declare var __dirname: string; // Node-specific
var global = <any>Function("return this").call(undefined);
var global: NodeJS.Global = <any>Function("return this").call(undefined);
declare namespace NodeJS {
export interface Global {
WScript: typeof WScript;
ActiveXObject: typeof ActiveXObject;
}
}
/* tslint:enable:no-var-keyword */
namespace Utils {
@ -57,7 +64,7 @@ namespace Utils {
export let currentExecutionEnvironment = getExecutionEnvironment();
const Buffer: BufferConstructor = currentExecutionEnvironment !== ExecutionEnvironment.Browser
const Buffer: typeof global.Buffer = currentExecutionEnvironment !== ExecutionEnvironment.Browser
? require("buffer").Buffer
: undefined;
@ -127,7 +134,7 @@ namespace Utils {
export function memoize<T extends Function>(f: T): T {
const cache: { [idx: string]: any } = {};
return <any>(function() {
return <any>(function(this: any) {
const key = Array.prototype.join.call(arguments);
const cachedResult = cache[key];
if (cachedResult) {
@ -743,7 +750,7 @@ namespace Harness {
export function readDirectory(path: string, extension?: string[], exclude?: string[], include?: string[]) {
const fs = new Utils.VirtualFileSystem(path, useCaseSensitiveFileNames());
for (const file in listFiles(path)) {
for (const file of listFiles(path)) {
fs.addFile(file);
}
return ts.matchFiles(path, extension, exclude, include, useCaseSensitiveFileNames(), getCurrentDirectory(), path => {
@ -841,9 +848,9 @@ namespace Harness {
export const defaultLibFileName = "lib.d.ts";
export const es2015DefaultLibFileName = "lib.es2015.d.ts";
const libFileNameSourceFileMap: ts.Map<ts.SourceFile> = {
const libFileNameSourceFileMap= ts.createMap<ts.SourceFile>({
[defaultLibFileName]: createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.es5.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest)
};
});
export function getDefaultLibrarySourceFile(fileName = defaultLibFileName): ts.SourceFile {
if (!isDefaultLibraryFile(fileName)) {
@ -998,13 +1005,13 @@ namespace Harness {
let optionsIndex: ts.Map<ts.CommandLineOption>;
function getCommandLineOption(name: string): ts.CommandLineOption {
if (!optionsIndex) {
optionsIndex = {};
optionsIndex = ts.createMap<ts.CommandLineOption>();
const optionDeclarations = harnessOptionDeclarations.concat(ts.optionDeclarations);
for (const option of optionDeclarations) {
optionsIndex[option.name.toLowerCase()] = option;
}
}
return ts.lookUp(optionsIndex, name.toLowerCase());
return optionsIndex[name.toLowerCase()];
}
export function setCompilerOptionsFromHarnessSetting(settings: Harness.TestCaseParser.CompilerSettings, options: ts.CompilerOptions & HarnessOptions): void {
@ -1203,18 +1210,7 @@ namespace Harness {
}
export function minimalDiagnosticsToString(diagnostics: ts.Diagnostic[]) {
// This is basically copied from tsc.ts's reportError to replicate what tsc does
let errorOutput = "";
ts.forEach(diagnostics, diagnostic => {
if (diagnostic.file) {
const lineAndCharacter = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
errorOutput += diagnostic.file.fileName + "(" + (lineAndCharacter.line + 1) + "," + (lineAndCharacter.character + 1) + "): ";
}
errorOutput += ts.DiagnosticCategory[diagnostic.category].toLowerCase() + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, Harness.IO.newLine()) + Harness.IO.newLine();
});
return errorOutput;
return ts.formatDiagnostics(diagnostics, { getCanonicalFileName, getCurrentDirectory: () => "", getNewLine: () => Harness.IO.newLine() });
}
export function getErrorBaseline(inputFiles: TestFile[], diagnostics: ts.Diagnostic[]) {
@ -1370,31 +1366,27 @@ namespace Harness {
writeByteOrderMark: boolean;
}
function stringEndsWith(str: string, end: string) {
return str.substr(str.length - end.length) === end;
}
export function isTS(fileName: string) {
return stringEndsWith(fileName, ".ts");
return ts.endsWith(fileName, ".ts");
}
export function isTSX(fileName: string) {
return stringEndsWith(fileName, ".tsx");
return ts.endsWith(fileName, ".tsx");
}
export function isDTS(fileName: string) {
return stringEndsWith(fileName, ".d.ts");
return ts.endsWith(fileName, ".d.ts");
}
export function isJS(fileName: string) {
return stringEndsWith(fileName, ".js");
return ts.endsWith(fileName, ".js");
}
export function isJSX(fileName: string) {
return stringEndsWith(fileName, ".jsx");
return ts.endsWith(fileName, ".jsx");
}
export function isJSMap(fileName: string) {
return stringEndsWith(fileName, ".js.map") || stringEndsWith(fileName, ".jsx.map");
return ts.endsWith(fileName, ".js.map") || ts.endsWith(fileName, ".jsx.map");
}
/** Contains the code and errors of a compilation and some helper methods to check its status. */
@ -1577,6 +1569,7 @@ namespace Harness {
/** Support class for baseline files */
export namespace Baseline {
const NoContent = "<no content>";
export interface BaselineOptions {
Subfolder?: string;
@ -1643,14 +1636,6 @@ namespace Harness {
throw new Error("The generated content was \"undefined\". Return \"null\" if no baselining is required.\"");
}
// Store the content in the 'local' folder so we
// can accept it later (manually)
/* tslint:disable:no-null-keyword */
if (actual !== null) {
/* tslint:enable:no-null-keyword */
IO.writeFile(actualFileName, actual);
}
return actual;
}
@ -1667,7 +1652,7 @@ namespace Harness {
/* tslint:disable:no-null-keyword */
if (actual === null) {
/* tslint:enable:no-null-keyword */
actual = "<no content>";
actual = NoContent;
}
let expected = "<no content>";
@ -1680,13 +1665,20 @@ namespace Harness {
function writeComparison(expected: string, actual: string, relativeFileName: string, actualFileName: string, descriptionForDescribe: string) {
const encoded_actual = Utils.encodeString(actual);
if (expected != encoded_actual) {
if (expected !== encoded_actual) {
if (actual === NoContent) {
IO.writeFile(localPath(relativeFileName + ".delete"), "");
}
else {
IO.writeFile(localPath(relativeFileName), actual);
}
// Overwrite & issue error
const errMsg = "The baseline file " + relativeFileName + " has changed.";
throw new Error(errMsg);
}
}
export function runBaseline(
descriptionForDescribe: string,
relativeFileName: string,

View File

@ -123,7 +123,7 @@ namespace Harness.LanguageService {
}
export class LanguageServiceAdapterHost {
protected fileNameToScript: ts.Map<ScriptInfo> = {};
protected fileNameToScript = ts.createMap<ScriptInfo>();
constructor(protected cancellationToken = DefaultHostCancellationToken.Instance,
protected settings = ts.getDefaultCompilerOptions()) {
@ -135,7 +135,7 @@ namespace Harness.LanguageService {
public getFilenames(): string[] {
const fileNames: string[] = [];
ts.forEachValue(this.fileNameToScript, (scriptInfo) => {
ts.forEachProperty(this.fileNameToScript, (scriptInfo) => {
if (scriptInfo.isRootFile) {
// only include root files here
// usually it means that we won't include lib.d.ts in the list of root files so it won't mess the computation of compilation root dir.
@ -146,7 +146,7 @@ namespace Harness.LanguageService {
}
public getScriptInfo(fileName: string): ScriptInfo {
return ts.lookUp(this.fileNameToScript, fileName);
return this.fileNameToScript[fileName];
}
public addScript(fileName: string, content: string, isRootFile: boolean): void {
@ -235,7 +235,7 @@ namespace Harness.LanguageService {
this.getModuleResolutionsForFile = (fileName) => {
const scriptInfo = this.getScriptInfo(fileName);
const preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ true);
const imports: ts.Map<string> = {};
const imports = ts.createMap<string>();
for (const module of preprocessInfo.importedFiles) {
const resolutionInfo = ts.resolveModuleName(module.fileName, fileName, compilerOptions, moduleResolutionHost);
if (resolutionInfo.resolvedModule) {
@ -248,7 +248,7 @@ namespace Harness.LanguageService {
const scriptInfo = this.getScriptInfo(fileName);
if (scriptInfo) {
const preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ false);
const resolutions: ts.Map<ts.ResolvedTypeReferenceDirective> = {};
const resolutions = ts.createMap<ts.ResolvedTypeReferenceDirective>();
const settings = this.nativeHost.getCompilationSettings();
for (const typeReferenceDirective of preprocessInfo.typeReferenceDirectives) {
const resolutionInfo = ts.resolveTypeReferenceDirective(typeReferenceDirective.fileName, fileName, settings, moduleResolutionHost);

View File

@ -209,7 +209,7 @@ namespace Playback {
memoize(path => findResultByFields(replayLog.pathsResolved, { path }, !ts.isRootedDiskPath(ts.normalizeSlashes(path)) && replayLog.currentDirectory ? replayLog.currentDirectory + "/" + path : ts.normalizeSlashes(path))));
wrapper.readFile = recordReplay(wrapper.readFile, underlying)(
path => {
(path: string) => {
const result = underlying.readFile(path);
const logEntry = { path, codepage: 0, result: { contents: result, codepage: 0 } };
recordLog.filesRead.push(logEntry);

View File

@ -253,18 +253,15 @@ class ProjectRunner extends RunnerBase {
moduleResolution: ts.ModuleResolutionKind.Classic, // currently all tests use classic module resolution kind, this will change in the future
};
// Set the values specified using json
const optionNameMap: ts.Map<ts.CommandLineOption> = {};
ts.forEach(ts.optionDeclarations, option => {
optionNameMap[option.name] = option;
});
const optionNameMap = ts.arrayToMap(ts.optionDeclarations, option => option.name);
for (const name in testCase) {
if (name !== "mapRoot" && name !== "sourceRoot" && ts.hasProperty(optionNameMap, name)) {
if (name !== "mapRoot" && name !== "sourceRoot" && name in optionNameMap) {
const option = optionNameMap[name];
const optType = option.type;
let value = <any>testCase[name];
if (typeof optType !== "string") {
const key = value.toLowerCase();
if (ts.hasProperty(optType, key)) {
if (key in optType) {
value = optType[key];
}
}
@ -328,7 +325,7 @@ class ProjectRunner extends RunnerBase {
if (Harness.Compiler.isJS(fileName)) {
// Make sure if there is URl we have it cleaned up
const indexOfSourceMapUrl = data.lastIndexOf("//# sourceMappingURL=");
const indexOfSourceMapUrl = data.lastIndexOf(`//# ${"sourceMappingURL"}=`); // This line can be seen as a sourceMappingURL comment
if (indexOfSourceMapUrl !== -1) {
data = data.substring(0, indexOfSourceMapUrl + 21) + cleanProjectUrl(data.substring(indexOfSourceMapUrl + 21));
}

View File

@ -193,7 +193,7 @@ if (taskConfigsFolder) {
for (let i = 0; i < workerCount; i++) {
const startPos = i * chunkSize;
const len = Math.min(chunkSize, files.length - startPos);
if (len !== 0) {
if (len > 0) {
workerConfigs[i].tasks.push({
runner: runner.kind(),
files: files.slice(startPos, startPos + len)
@ -214,5 +214,5 @@ else {
}
if (!runUnitTests) {
// patch `describe` to skip unit tests
describe = <any>describe.skip;
}
describe = <any>(function () { });
}

95
src/harness/tsconfig.json Normal file
View File

@ -0,0 +1,95 @@
{
"compilerOptions": {
"noImplicitAny": true,
"pretty": true,
"removeComments": false,
"preserveConstEnums": true,
"outFile": "../../built/local/run.js",
"sourceMap": true,
"declaration": false,
"stripInternal": true,
"types": [
"node", "mocha", "chai"
]
},
"files": [
"../compiler/core.ts",
"../compiler/performance.ts",
"../compiler/sys.ts",
"../compiler/types.ts",
"../compiler/scanner.ts",
"../compiler/parser.ts",
"../compiler/utilities.ts",
"../compiler/binder.ts",
"../compiler/checker.ts",
"../compiler/sourcemap.ts",
"../compiler/declarationEmitter.ts",
"../compiler/emitter.ts",
"../compiler/program.ts",
"../compiler/commandLineParser.ts",
"../compiler/diagnosticInformationMap.generated.ts",
"../services/breakpoints.ts",
"../services/navigateTo.ts",
"../services/navigationBar.ts",
"../services/outliningElementsCollector.ts",
"../services/patternMatcher.ts",
"../services/services.ts",
"../services/shims.ts",
"../services/signatureHelp.ts",
"../services/utilities.ts",
"../services/jsTyping.ts",
"../services/formatting/formatting.ts",
"../services/formatting/formattingContext.ts",
"../services/formatting/formattingRequestKind.ts",
"../services/formatting/formattingScanner.ts",
"../services/formatting/references.ts",
"../services/formatting/rule.ts",
"../services/formatting/ruleAction.ts",
"../services/formatting/ruleDescriptor.ts",
"../services/formatting/ruleFlag.ts",
"../services/formatting/ruleOperation.ts",
"../services/formatting/ruleOperationContext.ts",
"../services/formatting/rules.ts",
"../services/formatting/rulesMap.ts",
"../services/formatting/rulesProvider.ts",
"../services/formatting/smartIndenter.ts",
"../services/formatting/tokenRange.ts",
"harness.ts",
"sourceMapRecorder.ts",
"harnessLanguageService.ts",
"fourslash.ts",
"runnerbase.ts",
"compilerRunner.ts",
"typeWriter.ts",
"fourslashRunner.ts",
"projectsRunner.ts",
"loggedIO.ts",
"rwcRunner.ts",
"test262Runner.ts",
"runner.ts",
"../server/protocol.d.ts",
"../server/session.ts",
"../server/client.ts",
"../server/editorServices.ts",
"./unittests/incrementalParser.ts",
"./unittests/jsDocParsing.ts",
"./unittests/services/colorization.ts",
"./unittests/services/documentRegistry.ts",
"./unittests/services/preProcessFile.ts",
"./unittests/services/patternMatcher.ts",
"./unittests/session.ts",
"./unittests/versionCache.ts",
"./unittests/convertToBase64.ts",
"./unittests/transpile.ts",
"./unittests/reuseProgramStructure.ts",
"./unittests/cachingInServerLSHost.ts",
"./unittests/moduleResolution.ts",
"./unittests/tsconfigParsing.ts",
"./unittests/commandLineParsing.ts",
"./unittests/convertCompilerOptionsFromJson.ts",
"./unittests/convertTypingOptionsFromJson.ts",
"./unittests/tsserverProjectSystem.ts",
"./unittests/matchFiles.ts",
"./unittests/initializeTSConfig.ts"
]
}

View File

@ -1,4 +1,4 @@
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\harness.ts" />
namespace ts {
interface File {
@ -7,16 +7,16 @@ namespace ts {
}
function createDefaultServerHost(fileMap: Map<File>): server.ServerHost {
const existingDirectories: Map<boolean> = {};
forEachValue(fileMap, v => {
let dir = getDirectoryPath(v.name);
const existingDirectories = createMap<boolean>();
for (const name in fileMap) {
let dir = getDirectoryPath(name);
let previous: string;
do {
existingDirectories[dir] = true;
previous = dir;
dir = getDirectoryPath(dir);
} while (dir !== previous);
});
}
return {
args: <string[]>[],
newLine: "\r\n",
@ -24,7 +24,7 @@ namespace ts {
write: (s: string) => {
},
readFile: (path: string, encoding?: string): string => {
return hasProperty(fileMap, path) && fileMap[path].content;
return path in fileMap ? fileMap[path].content : undefined;
},
writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => {
throw new Error("NYI");
@ -33,10 +33,10 @@ namespace ts {
throw new Error("NYI");
},
fileExists: (path: string): boolean => {
return hasProperty(fileMap, path);
return path in fileMap;
},
directoryExists: (path: string): boolean => {
return hasProperty(existingDirectories, path);
return existingDirectories[path] || false;
},
createDirectory: (path: string) => {
},
@ -101,7 +101,7 @@ namespace ts {
content: `foo()`
};
const serverHost = createDefaultServerHost({ [root.name]: root, [imported.name]: imported });
const serverHost = createDefaultServerHost(createMap({ [root.name]: root, [imported.name]: imported }));
const { project, rootScriptInfo } = createProject(root.name, serverHost);
// ensure that imported file was found
@ -193,7 +193,7 @@ namespace ts {
content: `export var y = 1`
};
const fileMap: Map<File> = { [root.name]: root };
const fileMap = createMap({ [root.name]: root });
const serverHost = createDefaultServerHost(fileMap);
const originalFileExists = serverHost.fileExists;

View File

@ -1,5 +1,5 @@
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\..\..\src\compiler\commandLineParser.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\..\compiler\commandLineParser.ts" />
namespace ts {
describe("parseCommandLine", () => {

View File

@ -1,5 +1,5 @@
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\..\..\src\compiler\commandLineParser.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\..\compiler\commandLineParser.ts" />
namespace ts {
describe("convertCompilerOptionsFromJson", () => {

View File

@ -1,4 +1,4 @@
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\harness.ts" />
namespace ts {
describe("convertToBase64", () => {

View File

@ -1,5 +1,5 @@
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\..\..\src\compiler\commandLineParser.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\..\compiler\commandLineParser.ts" />
namespace ts {
describe("convertTypingOptionsFromJson", () => {

View File

@ -1,5 +1,5 @@
/// <reference path="..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path="..\..\..\src\compiler\parser.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\..\compiler\parser.ts" />
namespace ts {
ts.disableIncrementalParsing = false;

View File

@ -0,0 +1,44 @@
/// <reference path="..\harness.ts" />
/// <reference path="..\..\compiler\commandLineParser.ts" />
namespace ts {
describe("initTSConfig", () => {
function initTSConfigCorrectly(name: string, commandLinesArgs: string[]) {
describe(name, () => {
const commandLine = parseCommandLine(commandLinesArgs);
const initResult = generateTSConfig(commandLine.options, commandLine.fileNames);
const outputFileName = `tsConfig/${name.replace(/[^a-z0-9\-. ]/ig, "")}/tsconfig.json`;
it(`Correct output for ${outputFileName}`, () => {
Harness.Baseline.runBaseline("Correct output", outputFileName, () => {
if (initResult) {
return JSON.stringify(initResult, undefined, 4);
}
else {
// This can happen if compiler recieve invalid compiler-options
/* tslint:disable:no-null-keyword */
return null;
/* tslint:enable:no-null-keyword */
}
});
});
});
}
initTSConfigCorrectly("Default initialized TSConfig", ["--init"]);
initTSConfigCorrectly("Initialized TSConfig with files options", ["--init", "file0.st", "file1.ts", "file2.ts"]);
initTSConfigCorrectly("Initialized TSConfig with boolean value compiler options", ["--init", "--noUnusedLocals"]);
initTSConfigCorrectly("Initialized TSConfig with enum value compiler options", ["--init", "--target", "es5", "--jsx", "react"]);
initTSConfigCorrectly("Initialized TSConfig with list compiler options", ["--init", "--types", "jquery,mocha"]);
initTSConfigCorrectly("Initialized TSConfig with list compiler options with enum value", ["--init", "--lib", "es5,es2015.core"]);
initTSConfigCorrectly("Initialized TSConfig with incorrect compiler option", ["--init", "--someNonExistOption"]);
initTSConfigCorrectly("Initialized TSConfig with incorrect compiler option value", ["--init", "--lib", "nonExistLib,es5,es2015.promise"]);
});
}

View File

@ -1,7 +1,5 @@
/// <reference path="..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path="..\..\..\src\harness\external\chai.d.ts" />
/// <reference path="..\..\..\src\compiler\parser.ts" />
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\..\compiler\parser.ts" />
/// <reference path="..\harness.ts" />
namespace ts {
describe("JSDocParsing", () => {
@ -986,7 +984,7 @@ namespace ts {
});
describe("DocComments", () => {
function parsesCorrectly(content: string, expected: string) {
function parsesCorrectly(content: string, expected: string | {}) {
const comment = parseIsolatedJSDocComment(content);
if (!comment) {
Debug.fail("Comment failed to parse entirely");
@ -995,30 +993,46 @@ namespace ts {
Debug.fail("Comment has at least one diagnostic: " + comment.diagnostics[0].messageText);
}
const result = JSON.stringify(comment.jsDocComment, (k, v) => {
return v && v.pos !== undefined
? JSON.parse(Utils.sourceFileToJSON(v))
: v;
}, 4);
const result = toJsonString(comment.jsDocComment);
if (result !== expected) {
const expectedString = typeof expected === "string"
? expected
: toJsonString(expected);
if (result !== expectedString) {
// Turn on a human-readable diff
if (typeof require !== "undefined") {
const chai = require("chai");
chai.config.showDiff = true;
chai.expect(JSON.parse(result)).equal(JSON.parse(expected));
// Use deep equal to compare key value data instead of the two objects
chai.expect(JSON.parse(result)).deep.equal(JSON.parse(expectedString));
}
else {
assert.equal(result, expected);
assert.equal(result, expectedString);
}
}
}
function toJsonString(obj: {}) {
return JSON.stringify(obj, (k, v) => {
return v && v.pos !== undefined
? JSON.parse(Utils.sourceFileToJSON(v))
: v;
}, 4);
}
function parsesIncorrectly(content: string) {
const type = parseIsolatedJSDocComment(content);
assert.isTrue(!type || type.diagnostics.length > 0);
}
function reIndentJSDocComment(jsdocComment: string) {
const result = jsdocComment
.replace(/[\t ]*\/\*\*/, "/**")
.replace(/[\t ]*\*\s?@/g, " * @")
.replace(/[\t ]*\*\s?\//, " */");
return result;
}
describe("parsesIncorrectly", () => {
it("emptyComment", () => {
parsesIncorrectly("/***/");
@ -2216,6 +2230,152 @@ namespace ts {
}
}`);
});
it("typedefTagWithChildrenTags", () => {
const content =
`/**
* @typedef People
* @type {Object}
* @property {number} age
* @property {string} name
*/`;
const expected = {
"end": 102,
"kind": "JSDocComment",
"pos": 0,
"tags": {
"0": {
"atToken": {
"end": 9,
"kind": "AtToken",
"pos": 8
},
"end": 97,
"jsDocTypeLiteral": {
"end": 97,
"jsDocPropertyTags": [
{
"atToken": {
"end": 48,
"kind": "AtToken",
"pos": 46
},
"end": 69,
"kind": "JSDocPropertyTag",
"name": {
"end": 69,
"kind": "Identifier",
"pos": 66,
"text": "age"
},
"pos": 46,
"tagName": {
"end": 56,
"kind": "Identifier",
"pos": 48,
"text": "property"
},
"typeExpression": {
"end": 65,
"kind": "JSDocTypeExpression",
"pos": 57,
"type": {
"end": 64,
"kind": "NumberKeyword",
"pos": 58
}
}
},
{
"atToken": {
"end": 75,
"kind": "AtToken",
"pos": 73
},
"end": 97,
"kind": "JSDocPropertyTag",
"name": {
"end": 97,
"kind": "Identifier",
"pos": 93,
"text": "name"
},
"pos": 73,
"tagName": {
"end": 83,
"kind": "Identifier",
"pos": 75,
"text": "property"
},
"typeExpression": {
"end": 92,
"kind": "JSDocTypeExpression",
"pos": 84,
"type": {
"end": 91,
"kind": "StringKeyword",
"pos": 85
}
}
}
],
"jsDocTypeTag": {
"atToken": {
"end": 29,
"kind": "AtToken",
"pos": 27
},
"end": 42,
"kind": "JSDocTypeTag",
"pos": 27,
"tagName": {
"end": 33,
"kind": "Identifier",
"pos": 29,
"text": "type"
},
"typeExpression": {
"end": 42,
"kind": "JSDocTypeExpression",
"pos": 34,
"type": {
"end": 41,
"kind": "JSDocTypeReference",
"name": {
"end": 41,
"kind": "Identifier",
"pos": 35,
"text": "Object"
},
"pos": 35
}
}
},
"kind": "JSDocTypeLiteral",
"pos": 23
},
"kind": "JSDocTypedefTag",
"name": {
"end": 23,
"kind": "Identifier",
"pos": 17,
"text": "People"
},
"pos": 8,
"tagName": {
"end": 16,
"kind": "Identifier",
"pos": 9,
"text": "typedef"
}
},
"end": 97,
"length": 1,
"pos": 8
}
};
parsesCorrectly(reIndentJSDocComment(content), expected);
});
});
});
});

View File

@ -1,6 +1,5 @@
/// <reference path="..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\..\..\src\harness\virtualFileSystem.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\virtualFileSystem.ts" />
namespace ts {
const caseInsensitiveBasePath = "c:/dev/";

View File

@ -1,28 +1,6 @@
/// <reference path="..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path='..\..\..\src\harness\harness.ts' />
declare namespace chai.assert {
/* tslint:disable no-unused-variable */
function deepEqual(actual: any, expected: any): void;
/* tslint:enable no-unused-variable */
}
/// <reference path="..\harness.ts" />
namespace ts {
function diagnosticToString(diagnostic: Diagnostic) {
let output = "";
if (diagnostic.file) {
const loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
output += `${diagnostic.file.fileName}(${loc.line + 1},${loc.character + 1}): `;
}
const category = DiagnosticCategory[diagnostic.category].toLowerCase();
output += `${category} TS${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine)}${sys.newLine}`;
return output;
}
interface File {
name: string;
content?: string;
@ -32,7 +10,7 @@ namespace ts {
const map = arrayToMap(files, f => f.name);
if (hasDirectoryExists) {
const directories: Map<string> = {};
const directories = createMap<string>();
for (const f of files) {
let name = getDirectoryPath(f.name);
while (true) {
@ -47,19 +25,19 @@ namespace ts {
return {
readFile,
directoryExists: path => {
return hasProperty(directories, path);
return path in directories;
},
fileExists: path => {
assert.isTrue(hasProperty(directories, getDirectoryPath(path)), `'fileExists' '${path}' request in non-existing directory`);
return hasProperty(map, path);
assert.isTrue(getDirectoryPath(path) in directories, `'fileExists' '${path}' request in non-existing directory`);
return path in map;
}
};
}
else {
return { readFile, fileExists: path => hasProperty(map, path), };
return { readFile, fileExists: path => path in map, };
}
function readFile(path: string): string {
return hasProperty(map, path) ? map[path].content : undefined;
return path in map ? map[path].content : undefined;
}
}
@ -309,7 +287,7 @@ namespace ts {
const host: CompilerHost = {
getSourceFile: (fileName: string, languageVersion: ScriptTarget) => {
const path = normalizePath(combinePaths(currentDirectory, fileName));
return hasProperty(files, path) ? createSourceFile(fileName, files[path], languageVersion) : undefined;
return path in files ? createSourceFile(fileName, files[path], languageVersion) : undefined;
},
getDefaultLibFileName: () => "lib.d.ts",
writeFile: (fileName, content): void => { throw new Error("NotImplemented"); },
@ -320,7 +298,7 @@ namespace ts {
useCaseSensitiveFileNames: () => false,
fileExists: fileName => {
const path = normalizePath(combinePaths(currentDirectory, fileName));
return hasProperty(files, path);
return path in files;
},
readFile: (fileName): string => { throw new Error("NotImplemented"); }
};
@ -329,9 +307,9 @@ namespace ts {
assert.equal(program.getSourceFiles().length, expectedFilesCount);
const syntacticDiagnostics = program.getSyntacticDiagnostics();
assert.equal(syntacticDiagnostics.length, 0, `expect no syntactic diagnostics, got: ${JSON.stringify(syntacticDiagnostics.map(diagnosticToString))}`);
assert.equal(syntacticDiagnostics.length, 0, `expect no syntactic diagnostics, got: ${JSON.stringify(Harness.Compiler.minimalDiagnosticsToString(syntacticDiagnostics))}`);
const semanticDiagnostics = program.getSemanticDiagnostics();
assert.equal(semanticDiagnostics.length, 0, `expect no semantic diagnostics, got: ${JSON.stringify(semanticDiagnostics.map(diagnosticToString))}`);
assert.equal(semanticDiagnostics.length, 0, `expect no semantic diagnostics, got: ${JSON.stringify(Harness.Compiler.minimalDiagnosticsToString(semanticDiagnostics))}`);
// try to get file using a relative name
for (const relativeFileName of relativeNamesToCheck) {
@ -340,7 +318,7 @@ namespace ts {
}
it("should find all modules", () => {
const files: Map<string> = {
const files = createMap({
"/a/b/c/first/shared.ts": `
class A {}
export = A`,
@ -354,23 +332,23 @@ import Shared = require('../first/shared');
class C {}
export = C;
`
};
});
test(files, "/a/b/c/first/second", ["class_a.ts"], 3, ["../../../c/third/class_c.ts"]);
});
it("should find modules in node_modules", () => {
const files: Map<string> = {
const files = createMap({
"/parent/node_modules/mod/index.d.ts": "export var x",
"/parent/app/myapp.ts": `import {x} from "mod"`
};
});
test(files, "/parent/app", ["myapp.ts"], 2, []);
});
it("should find file referenced via absolute and relative names", () => {
const files: Map<string> = {
const files = createMap({
"/a/b/c.ts": `/// <reference path="b.ts"/>`,
"/a/b/b.ts": "var x"
};
});
test(files, "/a/b", ["c.ts", "/a/b/b.ts"], 2, []);
});
});
@ -380,11 +358,7 @@ export = C;
function test(files: Map<string>, options: CompilerOptions, currentDirectory: string, useCaseSensitiveFileNames: boolean, rootFiles: string[], diagnosticCodes: number[]): void {
const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
if (!useCaseSensitiveFileNames) {
const f: Map<string> = {};
for (const fileName in files) {
f[getCanonicalFileName(fileName)] = files[fileName];
}
files = f;
files = reduceProperties(files, (files, file, fileName) => (files[getCanonicalFileName(fileName)] = file, files), createMap<string>());
}
const host: CompilerHost = {
@ -393,7 +367,7 @@ export = C;
return library;
}
const path = getCanonicalFileName(normalizePath(combinePaths(currentDirectory, fileName)));
return hasProperty(files, path) ? createSourceFile(fileName, files[path], languageVersion) : undefined;
return path in files ? createSourceFile(fileName, files[path], languageVersion) : undefined;
},
getDefaultLibFileName: () => "lib.d.ts",
writeFile: (fileName, content): void => { throw new Error("NotImplemented"); },
@ -404,70 +378,70 @@ export = C;
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
fileExists: fileName => {
const path = getCanonicalFileName(normalizePath(combinePaths(currentDirectory, fileName)));
return hasProperty(files, path);
return path in files;
},
readFile: (fileName): string => { throw new Error("NotImplemented"); }
};
const program = createProgram(rootFiles, options, host);
const diagnostics = sortAndDeduplicateDiagnostics(program.getSemanticDiagnostics().concat(program.getOptionsDiagnostics()));
assert.equal(diagnostics.length, diagnosticCodes.length, `Incorrect number of expected diagnostics, expected ${diagnosticCodes.length}, got '${map(diagnostics, diagnosticToString).join("\r\n")}'`);
assert.equal(diagnostics.length, diagnosticCodes.length, `Incorrect number of expected diagnostics, expected ${diagnosticCodes.length}, got '${Harness.Compiler.minimalDiagnosticsToString(diagnostics)}'`);
for (let i = 0; i < diagnosticCodes.length; i++) {
assert.equal(diagnostics[i].code, diagnosticCodes[i], `Expected diagnostic code ${diagnosticCodes[i]}, got '${diagnostics[i].code}': '${diagnostics[i].messageText}'`);
}
}
it("should succeed when the same file is referenced using absolute and relative names", () => {
const files: Map<string> = {
const files = createMap({
"/a/b/c.ts": `/// <reference path="d.ts"/>`,
"/a/b/d.ts": "var x"
};
});
test(files, { module: ts.ModuleKind.AMD }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "/a/b/d.ts"], []);
});
it("should fail when two files used in program differ only in casing (tripleslash references)", () => {
const files: Map<string> = {
const files = createMap({
"/a/b/c.ts": `/// <reference path="D.ts"/>`,
"/a/b/d.ts": "var x"
};
});
test(files, { module: ts.ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "d.ts"], [1149]);
});
it("should fail when two files used in program differ only in casing (imports)", () => {
const files: Map<string> = {
const files = createMap({
"/a/b/c.ts": `import {x} from "D"`,
"/a/b/d.ts": "export var x"
};
});
test(files, { module: ts.ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "d.ts"], [1149]);
});
it("should fail when two files used in program differ only in casing (imports, relative module names)", () => {
const files: Map<string> = {
const files = createMap({
"moduleA.ts": `import {x} from "./ModuleB"`,
"moduleB.ts": "export var x"
};
});
test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", /*useCaseSensitiveFileNames*/ false, ["moduleA.ts", "moduleB.ts"], [1149]);
});
it("should fail when two files exist on disk that differs only in casing", () => {
const files: Map<string> = {
const files = createMap({
"/a/b/c.ts": `import {x} from "D"`,
"/a/b/D.ts": "export var x",
"/a/b/d.ts": "export var y"
};
});
test(files, { module: ts.ModuleKind.AMD }, "/a/b", /*useCaseSensitiveFileNames*/ true, ["c.ts", "d.ts"], [1149]);
});
it("should fail when module name in 'require' calls has inconsistent casing", () => {
const files: Map<string> = {
const files = createMap({
"moduleA.ts": `import a = require("./ModuleC")`,
"moduleB.ts": `import a = require("./moduleC")`,
"moduleC.ts": "export var x"
};
});
test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", /*useCaseSensitiveFileNames*/ false, ["moduleA.ts", "moduleB.ts", "moduleC.ts"], [1149, 1149]);
});
it("should fail when module names in 'require' calls has inconsistent casing and current directory has uppercase chars", () => {
const files: Map<string> = {
const files = createMap({
"/a/B/c/moduleA.ts": `import a = require("./ModuleC")`,
"/a/B/c/moduleB.ts": `import a = require("./moduleC")`,
"/a/B/c/moduleC.ts": "export var x",
@ -475,11 +449,11 @@ export = C;
import a = require("./moduleA.ts");
import b = require("./moduleB.ts");
`
};
});
test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], [1149]);
});
it("should not fail when module names in 'require' calls has consistent casing and current directory has uppercase chars", () => {
const files: Map<string> = {
const files = createMap({
"/a/B/c/moduleA.ts": `import a = require("./moduleC")`,
"/a/B/c/moduleB.ts": `import a = require("./moduleC")`,
"/a/B/c/moduleC.ts": "export var x",
@ -487,7 +461,7 @@ import b = require("./moduleB.ts");
import a = require("./moduleA.ts");
import b = require("./moduleB.ts");
`
};
});
test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], []);
});
});
@ -1045,7 +1019,7 @@ import b = require("./moduleB.ts");
const names = map(files, f => f.name);
const sourceFiles = arrayToMap(map(files, f => createSourceFile(f.name, f.content, ScriptTarget.ES6)), f => f.fileName);
const compilerHost: CompilerHost = {
fileExists : fileName => hasProperty(sourceFiles, fileName),
fileExists : fileName => fileName in sourceFiles,
getSourceFile: fileName => sourceFiles[fileName],
getDefaultLibFileName: () => "lib.d.ts",
writeFile(file, text) {
@ -1056,7 +1030,7 @@ import b = require("./moduleB.ts");
getCanonicalFileName: f => f.toLowerCase(),
getNewLine: () => "\r\n",
useCaseSensitiveFileNames: () => false,
readFile: fileName => hasProperty(sourceFiles, fileName) ? sourceFiles[fileName].text : undefined
readFile: fileName => fileName in sourceFiles ? sourceFiles[fileName].text : undefined
};
const program1 = createProgram(names, {}, compilerHost);
const diagnostics1 = program1.getFileProcessingDiagnostics().getDiagnostics();

View File

@ -1,6 +1,5 @@
/// <reference path="..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path='..\..\..\src\harness\harness.ts' />
/// <reference path="..\..\..\src\harness\harnessLanguageService.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\..\harness\harnessLanguageService.ts" />
namespace ts {
@ -96,13 +95,14 @@ namespace ts {
}
}
function createSourceFileWithText(fileName: string, sourceText: SourceText, target: ScriptTarget) {
const file = <SourceFileWithText>createSourceFile(fileName, sourceText.getFullText(), target);
file.sourceText = sourceText;
return file;
}
function createTestCompilerHost(texts: NamedSourceText[], target: ScriptTarget): CompilerHost {
const files: Map<SourceFileWithText> = {};
for (const t of texts) {
const file = <SourceFileWithText>createSourceFile(t.name, t.text.getFullText(), target);
file.sourceText = t.text;
files[t.name] = file;
}
const files = arrayToMap(texts, t => t.name, t => createSourceFileWithText(t.name, t.text, target));
return {
getSourceFile(fileName): SourceFile {
@ -129,10 +129,9 @@ namespace ts {
getNewLine(): string {
return sys ? sys.newLine : newLine;
},
fileExists: fileName => hasProperty(files, fileName),
fileExists: fileName => fileName in files,
readFile: fileName => {
const file = lookUp(files, fileName);
return file && file.text;
return fileName in files ? files[fileName].text : undefined;
}
};
}
@ -153,29 +152,29 @@ namespace ts {
return program;
}
function getSizeOfMap(map: Map<any>): number {
let size = 0;
for (const id in map) {
if (hasProperty(map, id)) {
size++;
function checkResolvedModule(expected: ResolvedModule, actual: ResolvedModule): boolean {
if (!expected === !actual) {
if (expected) {
assert.isTrue(expected.resolvedFileName === actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`);
assert.isTrue(expected.isExternalLibraryImport === actual.isExternalLibraryImport, `'isExternalLibraryImport': expected '${expected.isExternalLibraryImport}' to be equal to '${actual.isExternalLibraryImport}'`);
}
return true;
}
return size;
return false;
}
function checkResolvedModule(expected: ResolvedModule, actual: ResolvedModule): void {
assert.isTrue(actual !== undefined);
assert.isTrue(expected.resolvedFileName === actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`);
assert.isTrue(expected.isExternalLibraryImport === actual.isExternalLibraryImport, `'isExternalLibraryImport': expected '${expected.isExternalLibraryImport}' to be equal to '${actual.isExternalLibraryImport}'`);
function checkResolvedTypeDirective(expected: ResolvedTypeReferenceDirective, actual: ResolvedTypeReferenceDirective): boolean {
if (!expected === !actual) {
if (expected) {
assert.isTrue(expected.resolvedFileName === actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`);
assert.isTrue(expected.primary === actual.primary, `'primary': expected '${expected.primary}' to be equal to '${actual.primary}'`);
}
return true;
}
return false;
}
function checkResolvedTypeDirective(expected: ResolvedTypeReferenceDirective, actual: ResolvedTypeReferenceDirective): void {
assert.isTrue(actual !== undefined);
assert.isTrue(expected.resolvedFileName === actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`);
assert.isTrue(expected.primary === actual.primary, `'primary': expected '${expected.primary}' to be equal to '${actual.primary}'`);
}
function checkCache<T>(caption: string, program: Program, fileName: string, expectedContent: Map<T>, getCache: (f: SourceFile) => Map<T>, entryChecker: (expected: T, original: T) => void): void {
function checkCache<T>(caption: string, program: Program, fileName: string, expectedContent: Map<T>, getCache: (f: SourceFile) => Map<T>, entryChecker: (expected: T, original: T) => boolean): void {
const file = program.getSourceFile(fileName);
assert.isTrue(file !== undefined, `cannot find file ${fileName}`);
const cache = getCache(file);
@ -184,23 +183,7 @@ namespace ts {
}
else {
assert.isTrue(cache !== undefined, `expected ${caption} to be set`);
const actualCacheSize = getSizeOfMap(cache);
const expectedSize = getSizeOfMap(expectedContent);
assert.isTrue(actualCacheSize === expectedSize, `expected actual size: ${actualCacheSize} to be equal to ${expectedSize}`);
for (const id in expectedContent) {
if (hasProperty(expectedContent, id)) {
if (expectedContent[id]) {
const expected = expectedContent[id];
const actual = cache[id];
entryChecker(expected, actual);
}
}
else {
assert.isTrue(cache[id] === undefined);
}
}
assert.isTrue(equalOwnProperties(expectedContent, cache, entryChecker), `contents of ${caption} did not match the expected contents.`);
}
}
@ -314,6 +297,8 @@ namespace ts {
});
it("resolution cache follows imports", () => {
(<any>Error).stackTraceLimit = Infinity;
const files = [
{ name: "a.ts", text: SourceText.New("", "import {_} from 'b'", "var x = 1") },
{ name: "b.ts", text: SourceText.New("", "", "var y = 2") },
@ -321,7 +306,7 @@ namespace ts {
const options: CompilerOptions = { target };
const program_1 = newProgram(files, ["a.ts"], options);
checkResolvedModulesCache(program_1, "a.ts", { "b": { resolvedFileName: "b.ts" } });
checkResolvedModulesCache(program_1, "a.ts", createMap({ "b": { resolvedFileName: "b.ts" } }));
checkResolvedModulesCache(program_1, "b.ts", undefined);
const program_2 = updateProgram(program_1, ["a.ts"], options, files => {
@ -330,7 +315,7 @@ namespace ts {
assert.isTrue(program_1.structureIsReused);
// content of resolution cache should not change
checkResolvedModulesCache(program_1, "a.ts", { "b": { resolvedFileName: "b.ts" } });
checkResolvedModulesCache(program_1, "a.ts", createMap({ "b": { resolvedFileName: "b.ts" } }));
checkResolvedModulesCache(program_1, "b.ts", undefined);
// imports has changed - program is not reused
@ -347,7 +332,7 @@ namespace ts {
files[0].text = files[0].text.updateImportsAndExports(newImports);
});
assert.isTrue(!program_3.structureIsReused);
checkResolvedModulesCache(program_4, "a.ts", { "b": { resolvedFileName: "b.ts" }, "c": undefined });
checkResolvedModulesCache(program_4, "a.ts", createMap({ "b": { resolvedFileName: "b.ts" }, "c": undefined }));
});
it("resolved type directives cache follows type directives", () => {
@ -358,7 +343,7 @@ namespace ts {
const options: CompilerOptions = { target, typeRoots: ["/types"] };
const program_1 = newProgram(files, ["/a.ts"], options);
checkResolvedTypeDirectivesCache(program_1, "/a.ts", { "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } });
checkResolvedTypeDirectivesCache(program_1, "/a.ts", createMap({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
checkResolvedTypeDirectivesCache(program_1, "/types/typedefs/index.d.ts", undefined);
const program_2 = updateProgram(program_1, ["/a.ts"], options, files => {
@ -367,7 +352,7 @@ namespace ts {
assert.isTrue(program_1.structureIsReused);
// content of resolution cache should not change
checkResolvedTypeDirectivesCache(program_1, "/a.ts", { "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } });
checkResolvedTypeDirectivesCache(program_1, "/a.ts", createMap({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
checkResolvedTypeDirectivesCache(program_1, "/types/typedefs/index.d.ts", undefined);
// type reference directives has changed - program is not reused
@ -385,7 +370,7 @@ namespace ts {
files[0].text = files[0].text.updateReferences(newReferences);
});
assert.isTrue(!program_3.structureIsReused);
checkResolvedTypeDirectivesCache(program_1, "/a.ts", { "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } });
checkResolvedTypeDirectivesCache(program_1, "/a.ts", createMap({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
});
});

View File

@ -1,5 +1,4 @@
/// <reference path="..\..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path="..\..\..\..\src\harness\harnessLanguageService.ts" />
/// <reference path="..\..\harnessLanguageService.ts" />
interface ClassificationEntry {
value: any;

View File

@ -1,4 +1,4 @@
///<reference path='..\..\..\..\src\harness\harness.ts' />
/// <reference path="..\..\harness.ts" />
describe("DocumentRegistry", () => {
it("documents are shared between projects", () => {

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