Commit Graph

1503 Commits

Author SHA1 Message Date
Greg Magolan 9bb349e1c8 refactor: handle breaking changes in rules_nodejs 1.0.0 (#34589)
The major one that affects the angular repo is the removal of the bootstrap attribute in nodejs_binary, nodejs_test and jasmine_node_test in favor of using templated_args --node_options=--require=/path/to/script. The side-effect of this is that the bootstrap script does not get the require.resolve patches with explicitly loading the targets _loader.js file.

PR Close #34589
2020-01-10 08:31:59 -08:00
Greg Magolan cb6ffa1211 build: upgrade to rules_nodejs 1.0.0 (first stable release) (#34589)
Brings in the fix for stamping which was preventing many targets from getting cached.

PR Close #34589
2020-01-10 08:31:58 -08:00
George Kalpakas c3271ac22a fix(ngcc): recognize re-exports with imported TS helpers in CommonJS and UMD (#34527)
Previously, the `CommonJsReflectionHost` and `UmdReflectionHost` would
only recognize re-exports of the form `__export(...)`. This is what
re-exports look like, when the TypeScript helpers are emitted inline
(i.e. when compiling with the default [TypeScript compiler options][1]
that include `noEmitHelpers: false` and `importHelpers: false`).

However, when compiling with `importHelpers: true` and [tslib][2] (which
is the recommended way for optimized bundles), the re-exports will look
like: `tslib_1.__exportStar(..., exports)`
These types of re-exports were previously not recognized by the
CommonJS/UMD `ReflectionHost`s and thus ignored.

This commit fixes this by ensuring both re-export formats are
recognized.

[1]: https://www.typescriptlang.org/docs/handbook/compiler-options.html
[2]: https://www.npmjs.com/package/tslib

PR Close #34527
2020-01-10 08:28:50 -08:00
Pete Bacon Darwin 8815ace418 fix(ngcc): insert definitions after statement (#34677)
If a class was defined as a class expression
in a variable declaration, the definitions
were being inserted before the statment's
final semi-colon.

Now the insertion point will be after the
full statement.

Fixes #34648

PR Close #34677
2020-01-08 15:09:24 -08:00
Pete Bacon Darwin 58cdc22791 fix(ngcc): handle UMD factories that do not use all params (#34660)
In some cases, where a module imports a dependency
but does not actually use it, UMD bundlers may remove
the dependency parameter from the UMD factory function
definition.

For example:

```
import * as x from 'x';
import * as z from 'z';
export const y = x;
```

may result in a UMD bundle including:

```
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ?
        factory(exports, require('x'), require('z')) :
    typeof define === 'function' && define.amd ?
        define(['exports', 'x', 'z'], factory) :
    (global = global || self, factory(global.myBundle = {}, global.x));
}(this, (function (exports, x) { 'use strict';
...
})));
```

Note that while the `z` dependency is provide in the call,
the factory itself only accepts `exports` and `x` as parameters.

Previously ngcc appended new dependencies to the end of the factory
function, but this breaks in the above scenario. Now the new
dependencies are prefixed at the front of parameters/arguments
already in place.

Fixes #34653

PR Close #34660
2020-01-08 15:07:36 -08:00
Pete Bacon Darwin 570574df5b fix(ngcc): don't crash if symbol has no declarations (#34658)
In some cases TypeScript is unable to identify a valid
symbol for an export. In this case it returns an "unknown"
symbol, which does not reference any declarations.

This fix ensures that ngcc does not crash if such a symbol
is encountered by checking whether `symbol.declarations`
exists before accessing it.

The commit does not contain a unit test as it was not possible
to recreate a scenario that had such an "unknown" symbol in
the unit test environment. The fix has been manually checked
against that original issue; and also this check is equivalent to
similar checks elsewhere in the code, e.g.

https://github.com/angular/angular/blob/8d0de89e/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts#L309

Fixes #34560

PR Close #34658
2020-01-08 15:07:10 -08:00
George Kalpakas 07ea6cf582 fix(ngcc): avoid error due to circular dependency in `EsmDependencyHost` (#34512)
Previously, there was circular dependency between `ngcc/src/utils.ts`,
`ngcc/src/dependencies/dependency_host.ts` and
`ngcc/src/dependencies/esm_dependency_host.ts`. More specifically,
`utils.ts` would [import from `esm_dependency_host.ts`][1], which would
[import from `dependency_host.ts`][2], which would in turn
[import from `utils.ts`][3].

This might be fine in some environments/module formats, but it can cause
unclear errors in the transpiled CommonJS/UMD format (given how Node.js
handles [cycles in module resolution][4]).
(An example error can be found [here][5].)

This commit fixes the problem by moving the code that depends on
`EsmDependencyHost` out of `utils.ts` and into a dedicated file under
`dependencies/`. It also converts the `createDtsDependencyHost()`
function to a class for consistency with the rest of the
`DependencyHost`s.

[1]: https://github.com/angular/angular/blob/18d89c9c8/packages/compiler-cli/ngcc/src/utils.ts#L10
[2]: https://github.com/angular/angular/blob/18d89c9c8/packages/compiler-cli/ngcc/src/dependencies/esm_dependency_host.ts#L10
[3]: https://github.com/angular/angular/blob/18d89c9c8/packages/compiler-cli/ngcc/src/dependencies/dependency_host.ts#L9
[4]: https://nodejs.org/api/modules.html#modules_cycles
[5]: https://circleci.com/gh/angular/angular/577581

PR Close #34512
2020-01-08 15:00:50 -08:00
George Kalpakas c38195f59e refactor(ngcc): use a special map for memoizing expensive-to-compute values (#34512)
Previously, in cases were values were expensive to compute and would be
used multiple times, a combination of a regular `Map` and a helper
function (`getOrDefault()`) was used to ensure values were only computed
once.

This commit uses a special `Map`-like structure to compute and memoize
such expensive values without the need to a helper function.

PR Close #34512
2020-01-08 15:00:50 -08:00
George Kalpakas 6606ce69f6 refactor(ngcc): avoid returning the same top-level helper calls multiple times (#34512)
This change should not have any impact on the code's behavior (based on
how the function is currently used), but it will avoid unnecessary work.

PR Close #34512
2020-01-08 15:00:50 -08:00
George Kalpakas 17d5e2bc99 refactor(ngcc): share code between `CommonJsReflectionHost` and `UmdReflectionHost` (#34512)
While different, CommonJS and UMD have a lot in common regarding the
their exports are constructed. Therefore, there was some code
duplication between `CommonJsReflectionHost` and `UmdReflectionHost`.

This commit extracts some of the common bits into a separate file as
helpers to allow reusing the code in both `ReflectionHost`s.

PR Close #34512
2020-01-08 15:00:49 -08:00
George Kalpakas d5fd742763 fix(ngcc): recognize re-exports with `require()` calls in UMD (#34512)
Previously, `UmdReflectionHost` would only recognize re-exports of the
form `__export(someIdentifier)` and not `__export(require('...'))`.
However, it is possible in some UMD variations to have the latter format
as well. See discussion in https://github.com/angular/angular/pull/34254/files#r359515373

This commit adds support for re-export of the form
`__export(require('...'))` in UMD.

PR Close #34512
2020-01-08 15:00:49 -08:00
George Kalpakas 6654f82522 fix(ngcc): correctly handle inline exports in UMD (#34512)
This fix was part of a broader `ngtsc`/`ngcc` fix in 02bab8cf9 (see
there for details). In 02bab8cf9, the fix was only applied to
`CommonJsReflectionHost`, but it is equally applicable to
`UmdReflectionHost`. Later in #34254, the fix was partially ported to
`UmdReflectionHost` by fixing the `extractUmdReexports()` method.

This commit fully fixes `ngcc`'s handling of inline exports for code in
UMD format.

PR Close #34512
2020-01-08 15:00:49 -08:00
Andrew Scott 4d7a9db44c fix(ivy): Ensure ngProjectAs marker name appears at even attribute index (#34617)
The `getProjectAsAttrValue` in `node_selector_matcher` finds the
ProjectAs marker and then additionally checks that the marker appears in
an even index of the node attributes because "attribute names are stored
at even indexes". This is true for "regular" attribute bindings but
classes, styles, bindings, templates, and i18n do not necessarily follow
this rule because there can be an uneven number of them, causing the
next "special" attribute "name" to appear at an odd index. To address
this issue, ensure ngProjectAs is placed right after "regular"
attributes.

PR Close #34617
2020-01-07 10:51:46 -08:00
George Kalpakas 10e29355db fix(ngcc): do not add trailing commas in UMD imports (#34545)
Previously, if `UmdRenderingFormatter#addImports()` was called with an
empty list of imports to add (i.e. no new imports were needed), it would
add trailing commas in several locations (arrays, function arguments,
function parameters), thus making the code imcompatible with legacy
browsers such as IE11.

This commit fixes it by ensuring that no trailing commas are added if
`addImports()` is called with an empty list of imports.
This is a follow-up to #34353.

Fixes #34525

PR Close #34545
2020-01-07 10:42:06 -08:00
Pete Bacon Darwin 4f42de9704 fix(ngcc): capture entry-point dependencies from typings as well as source (#34494)
ngcc computes a dependency graph of entry-points to ensure that
entry-points are processed in the correct order. Previously only the imports
in source files were analysed to determine the dependencies for each
entry-point.

This is not sufficient when an entry-point has a "type-only" dependency
 - for example only importing an interface from another entry-point.
In this case the "type-only" import does not appear in the
source code. It only appears in the typings files. This can cause a
dependency to be missed on the entry-point.

This commit fixes this by additionally processing the imports in the
typings program, as well as the source program.

Note that these missing dependencies could cause unexpected flakes when
running ngcc in async mode on multiple processes due to the way that
ngcc caches files when they are first read from disk.

Fixes #34411

// FW-1781

PR Close #34494
2020-01-07 10:35:03 -08:00
Pete Bacon Darwin 69950e3888 refactor(ngcc): resolve modules based on the provided `moduleResolver` (#34494)
The `DependencyHost` implementations were duplicating the "postfix" strings
which are used to find matching paths when resolving module specifiers.
Now the hosts reuse the postfixes given to the `ModuleResolver` that is
passed to the host.

PR Close #34494
2020-01-07 10:35:03 -08:00
Pete Bacon Darwin e2b184515b refactor(ngcc): pass dependency info to `collectDependencies()` (#34494)
Rather than return a new object of dependency info from calls to
`collectDependencies()` we now pass in an object that will be updated
with the dependency info. This is in preparation of a change where
we will collect dependency information from more than one
`DependencyHost`.

Also to better fit with this approach the name is changed from
`findDependencies()` to `collectDependencies()`.

PR Close #34494
2020-01-07 10:35:03 -08:00
Andrew Kushnir b4c5bdb093 fix(ivy): append `advance` instructions before `i18nExp` (#34436)
Prior to this commit, there were no `advance` instructions generated before `i18nExp` instructions and as a result, lifecycle hooks for components used inside i18n blocks were flushed too late. This commit adds the logic to generate `advance` instructions in front of `i18nExp` ones (similar to what we have in other places like interpolations, property bindings, etc), so that the necessary lifecycle hooks are flushed before expression value is captured.

PR Close #34436
2020-01-07 10:31:45 -08:00
JoostK e116816131 refactor(ivy): let `strictTemplates` imply `fullTemplateTypeCheck` (#34195)
Previously, it was required that both `fullTemplateTypeCheck` and
`strictTemplates` had to be enabled for strict mode to be enabled. This
is strange, as `strictTemplates` implies `fullTemplateTypeCheck`. This
commit makes setting the `fullTemplateTypeCheck` flag optional so that
strict mode can be enabled by just setting `strictTemplates`.

PR Close #34195
2020-01-06 11:07:54 -08:00
JoostK 2e82357611 refactor(ivy): verify template type check options are compatible (#34195)
It is now an error if '"fullTemplateTypeCheck"' is disabled while
`"strictTemplates"` is enabled, as enabling the latter implies that the
former is also enabled.

PR Close #34195
2020-01-06 11:07:54 -08:00
JoostK 1de49ba369 refactor(ivy): consistently translate types to `ts.TypeNode` (#34021)
The compiler has a translation mechanism to convert from an Angular
`Type` to a `ts.TypeNode`, as appropriate. Prior to this change, it
would translate certain Angular expressions into their value equivalent
in TypeScript, instead of the correct type equivalent. This was possible
as the `ExpressionVisitor` interface is not strictly typed, with `any`s
being used for return values.

For example, a literal object was translated into a
`ts.ObjectLiteralExpression`, containing `ts.PropertyAssignment` nodes
as its entries. This has worked without issues as their printed
representation is identical, however it was incorrect from a semantic
point of view. Instead, a `ts.TypeLiteralNode` is created with
`ts.PropertySignature` as its members, which corresponds with the type
declaration of an object literal.

PR Close #34021
2020-01-06 11:06:07 -08:00
JoostK f27187c063 perf(ivy): support simple generic type constraints in local type ctors (#34021)
In Ivy's template type checker, type constructors are created for all
directive types to allow for accurate type inference to work. The type
checker has two strategies for dealing with such type constructors:

1. They can be emitted local to the type check block/type check file.
2. They can be emitted as static `ngTypeCtor` field into the directive
itself.

The first strategy is preferred, as it avoids having to update the
directive type which would cause a more expensive rebuild. However, this
strategy is not suitable for directives that have constrained generic
types, as those constraints would need to be present on the local type
constructor declaration. This is not trivial, as it requires that any
type references within a type parameter's constraint are imported into
the local context of the type check block.

For example, lets consider the `NgForOf` directive from '@angular/core'
looks as follows:

```typescript
import {NgIterable} from '@angular/core';

export class NgForOf<T, U extends NgIterable<T>> {}
```

The type constructor will then have the signature:
`(o: Pick<i1.NgForOf<T, U>, 'ngForOf'>) => i1.NgForOf<T, U>`

Notice how this refers to the type parameters `T` and `U`, so the type
constructor needs to be emitted into a scope where those types are
available, _and_ have the correct constraints.

Previously, the template type checker would detect the situation where a
type parameter is constrained, and would emit the type constructor
using strategy 2; within the directive type itself. This approach makes
any type references within the generic type constraints lexically
available:

```typescript
export class NgForOf<T, U extends NgIterable<T>> {
  static ngTypeCtor<T = any, U extends NgIterable<T> = any>
    (o: Pick<NgForOf<T, U>, 'ngForOf'>): NgForOf<T, U> { return null!; }
}
```

This commit introduces the ability to emit a type parameter with
constraints into a different context, under the condition that it can
be imported from an absolute module. This allows a generic type
constructor to be emitted into a type check block or type check file
according to strategy 1, as imports have been generated for all type
references within generic type constraints. For example:

```typescript
import * as i0 from '@angular/core';
import * as i1 from '@angular/common';

const _ctor1: <T = any, U extends i0.NgIterable<T> = any>
  (o: Pick<i1.NgForOf<T, U>, 'ngForOf'>) => i1.NgForOf<T, U> = null!;
```

Notice how the generic type constraint of `U` has resulted in an import
of `@angular/core`, and the `NgIterable` is transformed into a qualified
name during the emitting process.

Resolves FW-1739

PR Close #34021
2020-01-06 11:06:07 -08:00
crisbeto cf37c003ff feat(ivy): error in ivy when inheriting a ctor from an undecorated base (#34460)
Angular View Engine uses global knowledge to compile the following code:

```typescript
export class Base {
  constructor(private vcr: ViewContainerRef) {}
}

@Directive({...})
export class Dir extends Base {
  // constructor inherited from base
}
```

Here, `Dir` extends `Base` and inherits its constructor. To create a `Dir`
the arguments to this inherited constructor must be obtained via dependency
injection. View Engine is able to generate a correct factory for `Dir` to do
this because via metadata it knows the arguments of `Base`'s constructor,
even if `Base` is declared in a different library.

In Ivy, DI is entirely a runtime concept. Currently `Dir` is compiled with
an ngDirectiveDef field that delegates its factory to `getInheritedFactory`.
This looks for some kind of factory function on `Base`, which comes up
empty. This case looks identical to an inheritance chain with no
constructors, which works today in Ivy.

Both of these cases will now become an error in this commit. If a decorated
class inherits from an undecorated base class, a diagnostic is produced
informing the user of the need to either explicitly declare a constructor or
to decorate the base class.

PR Close #34460
2019-12-18 15:04:49 -08:00
crisbeto dcc8ff4ce7 feat(ivy): throw compilation error when providing undecorated classes (#34460)
Adds a compilation error if the consumer tries to pass in an undecorated class into the `providers` of an `NgModule`, or the `providers`/`viewProviders` arrays of a `Directive`/`Component`.

PR Close #34460
2019-12-18 15:04:49 -08:00
Alex Rickabaugh 6057c7a373 refactor(ivy): force NG-space error codes for template errors (#34460)
The function `makeTemplateDiagnostic` was accepting an error code of type
`number`, making it easy to accidentally pass an `ErrorCode` directly and
not convert it to an Angular diagnostic code first.

This commit refactors `makeTemplateDiagnostic` to accept `ErrorCode` up
front, and convert it internally. This is less error-prone.

PR Close #34460
2019-12-18 15:04:49 -08:00
Alex Rickabaugh 498a2ffba3 fix(ivy): don't produce template diagnostics when scope is invalid (#34460)
Previously, ngtsc would perform scope analysis (which directives/pipes are
available inside a component's template) and template type-checking of that
template as separate steps. If a component's scope was somehow invalid (e.g.
its NgModule imported something which wasn't another NgModule), the
component was treated as not having a scope. This meant that during template
type-checking, errors would be produced for any invalid expressions/usage of
other components that should have been in the scope.

This commit changes ngtsc to skip template type-checking of a component if
its scope is erroneous (as opposed to not present in the first place). Thus,
users aren't overwhelmed with diagnostic errors for the template and are
only informed of the root cause of the problem: an invalid NgModule scope.

Fixes #33849

PR Close #34460
2019-12-18 15:04:49 -08:00
Alex Rickabaugh 047488c5d8 refactor(ivy): move NgModule declaration checks to the 'scope' package (#34460)
Previously each NgModule trait checked its own scope for valid declarations
during 'resolve'. This worked, but caused the LocalModuleScopeRegistry to
declare that NgModule scopes were valid even if they contained invalid
declarations.

This commit moves the generation of diagnostic errors to the
LocalModuleScopeRegistry where it belongs. Now the registry can consider an
NgModule's scope to be invalid if it contains invalid declarations.

PR Close #34460
2019-12-18 15:04:49 -08:00
JoostK 3959511b80 fix(ivy): avoid duplicate errors in safe navigations and template guards (#34417)
The template type checker generates TypeScript expressions for any
expression that occurs in a template, so that TypeScript can check it
and produce errors. Some expressions as they occur in a template may be
translated into TypeScript code multiple times, for instance a binding
to a directive input that has a template guard.

One example would be the `NgIf` directive, which has a template guard to
narrow the type in the template as appropriate. Given the following
template:

```typescript
@Component({
  template: '<div *ngIf="person">{{ person.name }}</div>'
})
class AppComponent {
  person?: { name: string };
}
```

A type check block (TCB) with roughly the following structure is
created:

```typescript
function tcb(ctx: AppComponent) {
  const t1 = NgIf.ngTypeCtor({ ngIf: ctx.person });
  if (ctx.person) {
    "" + ctx.person.name;
  }
}
```

Notice how the `*ngIf="person"` binding is present twice: once in the
type constructor call and once in the `if` guard. As such, TypeScript
will check both instances and would produce duplicate errors, if any
were found.

Another instance is when the safe navigation operator is used, where an
expression such as `person?.name` is emitted into the TCB as
`person != null ? person!.name : undefined`. As can be seen, the
left-hand side expression `person` occurs twice in the TCB.

This commit adds the ability to insert markers into the TCB that
indicate that any errors within the expression should be ignored. This
is similar to `@ts-ignore`, however it can be applied more granularly.

PR Close #34417
2019-12-18 14:44:42 -08:00
JoostK 024e3b30ac refactor(ivy): cleanup translation of source spans in type checker (#34417)
This commit cleans up the template type checker regarding how
diagnostics are produced.

PR Close #34417
2019-12-18 14:44:42 -08:00
JoostK 8c6468a025 refactor(ivy): use absolute source spans in type checker (#34417)
Previously, the type checker would compute an absolute source span by
combining an expression AST node's `ParseSpan` (relative to the start of
the expression) together with the absolute offset of the expression as
represented in a `ParseSourceSpan`, to arrive at a span relative to the
start of the file. This information is now directly available on an
expression AST node in the `AST.sourceSpan` property, which can be used
instead.

PR Close #34417
2019-12-18 14:44:42 -08:00
Pete Bacon Darwin 9264f43511 refactor(ngcc): remove private declaration aliases (#34254)
Now that the source to typings matching is able to handle
aliasing of exports, there is no need to handle aliases in private
declarations analysis.

These were originally added to cope when the typings files had
to use the name that the original source files used when exporting.

PR Close #34254
2019-12-18 11:25:01 -08:00
Pete Bacon Darwin 918d8c9909 refactor(ngcc): slightly improve the info in error messages (#34254)
PR Close #34254
2019-12-18 11:25:01 -08:00
Pete Bacon Darwin 31be29a9f3 fix(ngcc): use the correct identifiers when updating typings files (#34254)
Previously the identifiers used in the typings files were the same as
those used in the source files.

When the typings files and the source files do not match exactly, e.g.
when one of them is flattened, while the other is a deep tree, it is
possible for identifiers to be renamed.

This commit ensures that the correct identifier is used in typings files
when the typings file does not export the same name as the source file.

Fixes https://github.com/angular/ngcc-validation/pull/608

PR Close #34254
2019-12-18 11:25:01 -08:00
Pete Bacon Darwin f22a6eb00e fix(ngcc): correctly match aliased classes between src and dts files (#34254)
The naïve matching algorithm we previously used to match declarations in
source files to declarations in typings files was based only on the name
of the thing being declared.  This did not handle cases where the declared
item had been exported via an alias - a common scenario when one of the two
file sets (source or typings) has been flattened, while the other has not.

The new algorithm tries to overcome this by creating two maps of export
name to declaration (i.e. `Map<string, ts.Declaration>`).
One for the source files and one for the typings files.
It then joins these two together by matching export names, resulting in a
new map that maps source declarations to typings declarations directly
(i.e. `Map<ts.Declaration, ts.Declaration>`).

This new map can handle the declaration names being different between the
source and typings as long as they are ultimately both exported with the
same alias name.

Further more, there is one map for "public exports", i.e. exported via the
root of the source tree (the entry-point), and another map for "private
exports", which are exported from individual files in the source tree but
not necessarily from the root. This second map can be used to "guess"
the mapping between exports in a deep (non-flat) file tree, which can be
used by ngcc to add required private exports to the entry-point.

Fixes #33593

PR Close #34254
2019-12-18 11:25:01 -08:00
Pete Bacon Darwin e9fb5fdb89 fix(ngcc): handle UMD re-exports (#34254)
In TS we can re-export imports using statements of the form:

```
export * from 'some-import';
```

This is downleveled in UMD to:

```
function factory(exports, someImport) {
  function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  }
  __export(someImport);
}
```

This commit adds support for this.

PR Close #34254
2019-12-18 11:25:01 -08:00
Pete Bacon Darwin 47666f548c fix(ngcc): handle CommonJS re-exports by reference (#34254)
In TS we can re-export imports using statements of the form:

```
export * from 'some-import';
```

This can be downleveled in CommonJS to either:

```
__export(require('some-import'));
```

or

```
var someImport = require('some-import');
__export(someImport);
```

Previously we only supported the first downleveled version.
This commit adds support for the second version.

PR Close #34254
2019-12-18 11:25:01 -08:00
Pete Bacon Darwin 0b837e2f0d refactor(ngcc): use bundle src to create reflection hosts (#34254)
Previously individual properties of the src bundle program were
passed to the reflection host constructors. But going forward,
more properties will be required. To prevent the signature getting
continually larger and more unwieldy, this change just passes the
whole src bundle to the constructor, allowing it to extract what it
needs.

PR Close #34254
2019-12-18 11:25:01 -08:00
George Kalpakas 7938ff34b1 refactor(compiler-cli): avoid unnecessarily calling `getSourceFile()` twice in `PartialEvaluator` (#34441)
This is not expected to have any noticeable perf impact, but it wasteful
nonetheless (and annoying when stepping through the code while debugging
`ngtsc`/`ngcc`).

PR Close #34441
2019-12-17 14:38:16 -08:00
Alex Rickabaugh 763f8d470a fix(ivy): validate the NgModule declarations field (#34404)
This commit adds three previously missing validations to
NgModule.declarations:

1. It checks that declared classes are actually within the current
   compilation.

2. It checks that declared classes are directives, components, or pipes.

3. It checks that classes are declared in at most one NgModule.

PR Close #34404
2019-12-17 11:39:48 -08:00
George Kalpakas 9cabd6638e refactor(ngcc): un-nest accidentally nested `describe()` blocks (#34437)
PR Close #34437
2019-12-17 11:39:18 -08:00
George Kalpakas cd8a837956 refactor(ngcc): add debug messages to help with debugging in parallel mode (#34437)
PR Close #34437
2019-12-17 11:39:18 -08:00
JoostK 12444a8afc test(ngcc): cleanup entry-point bundle testcases (#34415)
There was an issue with the program under test and two tests with the
same description, this has been fixed.

PR Close #34415
2019-12-16 07:45:36 -08:00
Alex Rickabaugh af95dddd7e perf(ivy): eagerly parse the template twice during analysis (#34334)
A quirk of the Angular template parser is that when parsing templates in the
"default" mode, with options specified by the user, the source mapping
information in the template AST may be inaccurate. As a result, the compiler
parses the template twice: once for "emit" and once to produce an AST with
accurate sourcemaps for diagnostic production.

Previously, only the first parse was performed during analysis. The second
parse occurred during the template type-checking phase, just in time to
produce the template type-checking file.

However, with the reuse of analysis results during incremental builds, it
makes more sense to do the diagnostic parse eagerly during analysis so that
the work isn't unnecessarily repeated in subsequent builds. This commit
refactors the `ComponentDecoratorHandler` to do both parses eagerly, which
actually cleans up some complexity around template parsing as well.

PR Close #34334
2019-12-12 14:13:16 -08:00
JoostK 8c2cbdd385 perf(ivy): use module resolution cache (#34332)
During TypeScript module resolution, a lot of filesystem requests are
done. This is quite an expensive operation, so a module resolution cache
can be used to speed up the process significantly.

This commit lets the Ivy compiler perform all module resolution with a
module resolution cache. Note that the module resolution behavior can be
changed with a custom compiler host, in which case that custom host
implementation is responsible for caching. In the case of the Angular
CLI a custom compiler host with proper module resolution caching is
already in place, so the CLI already has this optimization.

PR Close #34332
2019-12-12 14:06:37 -08:00
JoostK 2f5ddd9c96 perf(ivy): cache export scopes extracted from declaration files (#34332)
The export scope of NgModules from external compilations units, as
present in .d.ts declarations, does not change during a compilation so
can be easily shared. There was already a cache but the computed export
scope was not actually stored there. This commit fixes that.

PR Close #34332
2019-12-12 14:06:36 -08:00
Alex Rickabaugh 6ba5fdc208 fix(ivy): generate a better error for template var writes (#34339)
In Ivy it's illegal for a template to write to a template variable. So the
template:

```html
<ng-template let-somevar>
  <button (click)="somevar = 3">Set var to 3</button>
</ng-template>
```

is erroneous and previously would fail to compile with an assertion error
from the `TemplateDefinitionBuilder`. This error wasn't particularly user-
friendly, though, as it lacked the context of which template or where the
error occurred.

In this commit, a new check in template type-checking is added which detects
such erroneous writes and produces a true diagnostic with the appropriate
context information.

Closes #33674

PR Close #34339
2019-12-12 13:13:32 -08:00
Alex Rickabaugh 74edde0a94 perf(ivy): reuse prior analysis work during incremental builds (#34288)
Previously, the compiler performed an incremental build by analyzing and
resolving all classes in the program (even unchanged ones) and then using
the dependency graph information to determine which .js files were stale and
needed to be re-emitted. This algorithm produced "correct" rebuilds, but the
cost of re-analyzing the entire program turned out to be higher than
anticipated, especially for component-heavy compilations.

To achieve performant rebuilds, it is necessary to reuse previous analysis
results if possible. Doing this safely requires knowing when prior work is
viable and when it is stale and needs to be re-done.

The new algorithm implemented by this commit is such:

1) Each incremental build starts with knowledge of the last known good
   dependency graph and analysis results from the last successful build,
   plus of course information about the set of files changed.

2) The previous dependency graph's information is used to determine the
   set of source files which have "logically" changed. A source file is
   considered logically changed if it or any of its dependencies have
   physically changed (on disk) since the last successful compilation. Any
   logically unchanged dependencies have their dependency information copied
   over to the new dependency graph.

3) During the `TraitCompiler`'s loop to consider all source files in the
   program, if a source file is logically unchanged then its previous
   analyses are "adopted" (and their 'register' steps are run). If the file
   is logically changed, then it is re-analyzed as usual.

4) Then, incremental build proceeds as before, with the new dependency graph
   being used to determine the set of files which require re-emitting.

This analysis reuse avoids template parsing operations in many circumstances
and significantly reduces the time it takes ngtsc to rebuild a large
application.

Future work will increase performance even more, by tackling a variety of
other opportunities to reuse or avoid work.

PR Close #34288
2019-12-12 13:11:45 -08:00
Alex Rickabaugh 50cdc0ac1b refactor(ivy): move analysis side effects into a register phase (#34288)
Previously 'analyze' in the various `DecoratorHandler`s not only extracts
information from the decorators on the classes being analyzed, but also has
several side effects within the compiler:

* it can register metadata about the types involved in global metadata
  trackers.
* it can register information about which .ngfactory symbols are actually
  needed.

In this commit, these side-effects are moved into a new 'register' phase,
which runs after the 'analyze' step. Currently this is a no-op refactoring
as 'register' is always called directly after 'analyze'. In the future this
opens the door for re-use of prior analysis work (with only 'register' being
called, to apply the above side effects).

Also as part of this refactoring, the reification of NgModule scope
information into the incremental dependency graph is moved to the
`NgtscProgram` instead of the `TraitCompiler` (which now only manages trait
compilation and does not have other side effects).

PR Close #34288
2019-12-12 13:11:45 -08:00
Alex Rickabaugh 252e3e9487 refactor(ivy): formalize the compilation process for matched handlers (#34288)
Prior to this commit, the `IvyCompilation` tracked the state of each matched
`DecoratorHandler` on each class in the `ts.Program`, and how they
progressed through the compilation process. This tracking was originally
simple, but had grown more complicated as the compiler evolved. The state of
each specific "target" of compilation was determined by the nullability of
a number of fields on the object which tracked it.

This commit formalizes the process of compilation of each matched handler
into a new "trait" concept. A trait is some aspect of a class which gets
created when a `DecoratorHandler` matches the class. It represents an Ivy
aspect that needs to go through the compilation process.

Traits begin in a "pending" state and undergo transitions as various steps
of compilation take place. The `IvyCompilation` class is renamed to the
`TraitCompiler`, which manages the state of all of the traits in the active
program.

Making the trait concept explicit will support future work to incrementalize
the expensive analysis process of compilation.

PR Close #34288
2019-12-12 13:11:45 -08:00
Pete Bacon Darwin 05c1398b4d fix(ngcc): render UMD imports even if no prior imports (#34353)
Previously the UMD rendering formatter assumed that
there would already be import (and an export) arguments
to the UMD factory function.

This commit adds support for this corner case.

Fixes #34138

PR Close #34353
2019-12-12 09:09:41 -08:00
Pete Bacon Darwin c77656e2dd fix(ngcc): handle imports in dts files when processing UMD (#34356)
When statically evalulating UMD code it is possible to find
that we are looking for the declaration of an identifier that
actually came from a typings file (rather than a UMD file).

Previously, the UMD reflection host would always try to use
a UMD specific algorithm for finding identifier declarations,
but when the id is actually in a typings file this resulted in the
returned declaration being the containing file of the declaration
rather than the declaration itself.

Now the UMD reflection host will check to see if the file containing
the identifier is a typings file and use the appropriate stategy.

PR Close #34356
2019-12-11 13:20:49 -08:00
JoostK b72c7a89a9 refactor(ivy): include generic type for `ModuleWithProviders` in .d.ts files (#34235)
The `ModuleWithProviders` type has an optional type parameter that
should be specified to indicate what NgModule class will be provided.
This enables the Ivy compiler to statically determine the NgModule type
from the declaration files. This type parameter will become required in
the future, however to aid in the migration the compiler will detect
code patterns where using `ModuleWithProviders` as return type is
appropriate, in which case it transforms the emitted .d.ts files to
include the generic type argument.

This should reduce the number of occurrences where `ModuleWithProviders`
is referenced without its generic type argument.

Resolves FW-389

PR Close #34235
2019-12-10 16:34:47 -08:00
Alex Rickabaugh a8fced8846 refactor(ivy): abstract .d.ts file transformations (#34235)
This commit refactors the way the compiler transforms .d.ts files during
ngtsc builds. Previously the `IvyCompilation` kept track of a
`DtsFileTransformer` for each input file. Now, any number of
`DtsTransform` operations that need to be applied to a .d.ts file are
collected in the `DtsTransformRegistry`. These are then ran using a
single `DtsTransformer` so that multiple transforms can be applied
efficiently.

PR Close #34235
2019-12-10 16:34:46 -08:00
JoostK 0984fbc748 fix(compiler-cli): allow declaration-only template type check members (#34296)
The metadata collector for View Engine compilations emits error symbols
for static class members that have not been initialized, which prevents
a library from building successfully when `strictMetadataEmit` is
enabled, which is recommended for libraries to avoid issues in library
consumers. This is troublesome for libraries that are adopting static
members for the Ivy template type checker: these members don't need a
value assignment as only their type is of importance, however this
causes metadata errors. As such, a library used to be required to
initialize the special static members to workaround this error,
undesirably introducing a code-size overhead in terms of emitted
JavaScript code.

This commit modifies the collector logic to specifically ignore
the special static members for Ivy's template type checker, preventing
any errors from being recorded during the metadata collection.

PR Close #34296
2019-12-10 16:31:23 -08:00
JoostK 22ad701134 fix(ivy): inherit static coercion members from base classes (#34296)
For Ivy's template type checker it is possible to let a directive
specify static members to allow a wider type for some input:

```typescript
export class MatSelect {
  @Input() disabled: boolean;

  static ngAcceptInputType_disabled: boolean | string;
}
```

This allows a binding to the `MatSelect.disabled` input to be of type
boolean or string, whereas the `disabled` property itself is only of
type boolean.

Up until now, any static `ngAcceptInputType_*` property was not
inherited for subclasses of a directive class. This is cumbersome, as
the directive's inputs are inherited, so any acceptance member should as
well. To resolve this limitation, this commit extends the flattening of
directive metadata to include the acceptance members.

Fixes #33830
Resolves FW-1759

PR Close #34296
2019-12-10 16:31:23 -08:00
JoostK ead169a402 fix(ngcc): fix undecorated child migration when `exportAs` is present (#34014)
The undecorated child migration creates a synthetic decorator, which
contained `"exportAs": ["exportName"]` as obtained from the metadata of
the parent class. This is a problem, as `exportAs` needs to specified
as a comma-separated string instead of an array. This commit fixes the
bug by transforming the array of export names back to a comma-separated
string.

PR Close #34014
2019-12-09 16:13:09 -08:00
JoostK 95429d55ff fix(ngcc): log Angular error codes correctly (#34014)
Replaces the "TS-99" sequence with just "NG", so that error codes are
logged correctly.

PR Close #34014
2019-12-09 16:13:08 -08:00
JoostK 0f0fd25038 fix(ngcc): report diagnostics from migrations (#34014)
When ngcc is analyzing synthetically inserted decorators from a
migration, it is typically not expected that any diagnostics are
produced. In the situation where a diagnostic is produced, however, the
diagnostic would not be reported at all. This commit ensures that
diagnostics in migrations are reported.

PR Close #34014
2019-12-09 16:13:08 -08:00
Alex Rickabaugh 9fa2c398e7 fix(compiler): switch to modern diagnostic formatting (#34234)
The compiler exports a `formatDiagnostics` function which consumers can use
to print both ts and ng diagnostics. However, this function was previously
using the "old" style TypeScript diagnostics, as opposed to the modern
diagnostic printer which uses terminal colors and prints additional context
information.

This commit updates `formatDiagnostics` to use the modern formatter, plus to
update Ivy's negative error codes to Angular 'NG' errors.

The Angular CLI needs a little more work to use this function for printing
TS diagnostics, but this commit alone should fix Bazel builds as ngc-wrapped
goes through `formatDiagnostics`.

PR Close #34234
2019-12-09 11:37:49 -08:00
Alex Rickabaugh 718d7fe5fe fix(ivy): properly parenthesize ternary expressions when emitted (#34221)
Previously, ternary expressions were emitted as:

condExpr ? trueCase : falseCase

However, this causes problems when ternary operations are nested. In
particular, a template expression of the form:

a?.b ? c : d

would have compiled to:

a == null ? null : a.b ? c : d

The ternary operator is right-associative, so that expression is interpreted
as:

a == null ? null : (a.b ? c : d)

when in reality left-associativity is desired in this particular instance:

(a == null ? null : a.b) ? c : d

This commit adds a check in the expression translator to detect such
left-associative usages of ternaries and to enforce such associativity with
parentheses when necessary.

A test is also added for the template type-checking expression translator,
to ensure it correctly produces right-associative expressions for ternaries
in the user's template.

Fixes #34087

PR Close #34221
2019-12-06 13:01:48 -08:00
Pete Bacon Darwin 61e8ed6623 fix(ngcc): ensure that bundle `rootDir` is the package path (#34212)
Previously the `rootDir` was set to the entry-point path but
this is incorrect if the source files are stored in a directory outside
the entry-point path. This is the case in the latest versions of the
Angular CDK.

Instead the `rootDir` should be the containing package path, which is
guaranteed to include all the source for the entry-point.

---

A symptom of this is an error when ngcc is trying to process the source of
an entry-point format after the entry-point's typings have already been
processed by a previous processing run.

During processing the `_toR3Reference()` function gets called which in turn
makes a call to `ReflectionHost.getDtsDeclaration()`. If the typings files
are also being processed this returns the node from the dts typings files.

But if we have already processed the typings files and are now processing
only an entry-point format without typings, the call to
`ReflectionHost.getDtsDeclaration()` returns `null`.

When this value is `null`, a JS `valueRef` is passed through as the DTS
`typeRef` to the `ReferenceEmitter`. In this case, the `ReferenceEmitter`
fails during `emit()` because no `ReferenceEmitStrategy` is able to provide
an emission:

1) The `LocalIdentifierStrategy` is not able help because in this case
`ImportMode` is `ForceNewImport`.
2) The `LogicalProjectStrategy` cannot find the JS file below the `rootDir`.

The second strategy failure is fixed by this PR.

Fixes https://github.com/angular/ngcc-validation/issues/495

PR Close #34212
2019-12-05 10:13:02 -08:00
Andrew Kushnir 634887c0e7 test(ivy): update `ngI18nClosureMode` flag usage in tests (#34224)
Commit that updated i18n message ids rendering (e524322c43) also introduced a couple tests that relied on a previous version of `ngI18nClosureMode` flag format. The `ngI18nClosureMode` usage format was changed in the followup commit (c4ce24647b) and triggered a problem with the mentioned tests. This commit updates the tests to a new `ngI18nClosureMode` flag usage format.

PR Close #34224
2019-12-03 23:03:27 -08:00
Pete Bacon Darwin c4ce24647b fix(compiler-cli): ensure that `ngI18nClosureMode` is guarded in generated code (#34211)
If the `ngI18nClosureMode` global check actually makes it
through to the runtime, then checks for its existence should
be guarded to prevent `Reference undefined` errors in strict
mode.

(Normally, it is stripped out by dead code elimination during
build optimization.)

This comment ensures that generated template code guards
this global check.

PR Close #34211
2019-12-03 16:18:12 -08:00
Kristiyan Kostadinov cca2616637 refactor(common): add defaults to new generic parameters (#34206)
This is a follow-up to #33997 where some new generic parameters were added without defaults which is technically a breaking change. These changes add the defaults.

PR Close #34206
2019-12-03 16:16:30 -08:00
Andrew Kushnir c50faa97ca fix(ivy): correctly support `ngProjectAs` on templates (#34200)
Prior to this commit, if a template (for example, generated using structural directive such as *ngIf) contains `ngProjectAs` attribute, it was not included into attributes array in generated code and as a result, these templates were not matched at runtime during content projection. This commit adds the logic to append `ngProjectAs` values into corresponding element's attribute arrays, so content projection works as expected.

PR Close #34200
2019-12-03 16:12:55 -08:00
crisbeto e6909bda89 fix(ivy): incorrectly validating html foreign objects inside svg (#34178)
Fixes ngtsc incorrectly logging an unknown element diagnostic for HTML elements that are inside an SVG `foreignObject` with the `xhtml` namespace.

Fixes #34171.

PR Close #34178
2019-12-03 10:29:45 -08:00
Pete Bacon Darwin f16f6a290b fix(ngcc): render legacy i18n message ids by default (#34135)
By ensuring that legacy i18n message ids are rendered into the templates
of components for packages processed by ngcc, we ensure that these packages
can be used in an application that may provide translations in a legacy
format.

Fixes #34056

PR Close #34135
2019-12-03 10:15:53 -08:00
Pete Bacon Darwin cebe49d3c9 refactor(ngcc): store whether to render legacy i18n message ids in the bundle (#34135)
Placing this configuration in to the bundle avoids having to pass the
value around through lots of function calls, but also could enable
support for different behaviour per bundle in the future.

PR Close #34135
2019-12-03 10:15:53 -08:00
Pete Bacon Darwin e524322c43 refactor(compiler): i18n - render legacy i18n message ids (#34135)
Now that `@angular/localize` can interpret multiple legacy message ids in the
metablock of a `$localize` tagged template string, this commit adds those
ids to each i18n message extracted from component templates, but only if
the `enableI18nLegacyMessageIdFormat` is not `false`.

PR Close #34135
2019-12-03 10:15:53 -08:00
Pete Bacon Darwin e12933a3aa test(ngcc): tidy up helper function (#34135)
Thanks to @gkalpakl for the better regular expression approach.

PR Close #34135
2019-12-03 10:15:52 -08:00
Kara Erickson 67eac733d2 refactor(ivy): do not generate providedIn: null (#34116)
We should only generate the `providedIn` property in injectable
defs if it has a non-null value. `null` does not communicate
any information to the runtime that isn't communicated already
by the absence of the property.

This should give us some modest code size savings.

PR Close #34116
2019-12-03 10:14:52 -08:00
Kara Erickson 755d2d572f refactor(ivy): remove unnecessary fac wrapper (#34076)
For injectables, we currently generate a factory function in the
injectable def (prov) that delegates to the factory function in
the factory def (fac). It looks something like this:

```
factory: function(t) { return Svc.fac(t); }
```

The extra wrapper function is unnecessary since the args for
the factory functions are the same. This commit changes the
compiler to generate this instead:

```
factory: Svc.fac
```

Because we are generating less code for each injectable, we
should see some modest code size savings. AIO's main bundle
is about 1 KB smaller.

PR Close #34076
2019-12-02 11:35:24 -08:00
crisbeto 02958c07f6 fix(common): reflect input type in NgIf context (#33997)
Fixes the content of `NgIf` being typed to any.

Fixes #31556.

PR Close #33997
2019-12-02 11:34:26 -08:00
crisbeto a6b6d74c00 fix(common): reflect input type in NgForOf context (#33997)
Fixes `NgForOf` not reflecting the type of its input in the `NgForOfContext`.

PR Close #33997
2019-12-02 11:34:26 -08:00
Igor Minar 5a7f33496b refactor(compiler-cli): remove bogus packages/compiler-cli/integrationtest/benchmarks/ (#34142)
nobody uses this folder for anything and the README.md is misleading.

PR Close #34142
2019-12-02 11:22:45 -08:00
Pete Bacon Darwin 2fb9b7ff1b fix(ngcc): do not output duplicate ɵprov properties (#34085)
Previously, the Angular AOT compiler would always add a
`ɵprov` to injectables. But in ngcc this resulted in duplicate `ɵprov`
properties since published libraries already have this property.

Now in ngtsc, trying to add a duplicate `ɵprov` property is an error,
while in ngcc the additional property is silently not added.

// FW-1750

PR Close #34085
2019-11-27 12:46:37 -08:00
Andrew Kushnir 658087be7e fix(ivy): prevent unknown element check for AOT-compiled components (#34024)
Prior to this commit, the unknown element can happen twice for AOT-compiled components: once during compilation and once again at runtime. Due to the fact that `schemas` information is not present on Component and NgModule defs after AOT compilation, the second check (at runtime) may fail, even though the same check was successful at compile time. This commit updates the code to avoid the second check for AOT-compiled components by checking whether `schemas` information is present in a logic that executes the unknown element check.

PR Close #34024
2019-11-27 12:45:32 -08:00
Pete Bacon Darwin ee7857300b fix(ivy): i18n - ensure that escaped chars are handled in localized strings (#34065)
When creating synthesized tagged template literals, one must provide both
the "cooked" text and the "raw" (unparsed) text. Previously there were no
good APIs for creating the AST nodes with raw text for such literals.
Recently the APIs were improved to support this, and they do an extra
check to ensure that the raw text parses to be equal to the cooked text.

It turns out there is a bug in this check -
see https://github.com/microsoft/TypeScript/issues/35374.

This commit works around the bug by synthesizing a "head" node and morphing
it by changing its `kind` into the required node type.

// FW-1747

PR Close #34065
2019-11-27 10:36:36 -08:00
Joey Perrott 5e3f6d203d build: migrate references and scripts that set to build with ivy via compile=aot to use config=ivy (#33983)
Since config=ivy now sets the define=compile flag and the define=angular_ivy_enabled
flag to cause usage of Ivy, we can update all of the documentation and scripts that
reference compile=aot to use config=ivy.

PR Close #33983
2019-11-26 16:38:40 -05:00
Andrew Kushnir 5de7960f01 fix(ivy): take styles extracted from template into account in JIT mode (#34017)
Prior to this commit, all styles extracted from Component's template (defined using <style> tags) were ignored by JIT compiler, so only `styles` array values defined in @Component decorator were used. This change updates JIT compiler to take styles extracted from the template into account. It also ensures correct order where `styles` array values are applied first and template styles are applied second.

PR Close #34017
2019-11-25 22:38:42 -05:00
crisbeto 25dcc7631f fix(ivy): add flag to skip non-exported classes (#33921)
In ViewEngine we were only generating code for exported classes, however with Ivy we do it no matter whether the class has been exported or not. These changes add an extra flag that allows consumers to opt into the ViewEngine behavior. The flag works by treating non-exported classes as if they're set to `jit: true`.

Fixes #33724.

PR Close #33921
2019-11-25 16:36:44 -05:00
Pete Bacon Darwin 44225e4010 fix(ngcc): render UMD global imports correctly (#34012)
The current UMD rendering formatter did not handle
a number of corner cases, such as imports from namespaced
packages.

PR Close #34012
2019-11-25 11:38:36 -05:00
Alex Rickabaugh 4cf197998a fix(ivy): track changes across failed builds (#33971)
Previously, our incremental build system kept track of the changes between
the current compilation and the previous one, and used its knowledge of
inter-file dependencies to evaluate the impact of each change and emit the
right set of output files.

However, a problem arose if the compiler was not able to extract a
dependency graph successfully. This typically happens if the input program
contains errors. In this case the Angular analysis part of compilation is
never executed.

If a file changed in one of these failed builds, in the next build it
appears unchanged. This means that the compiler "forgets" to emit it!

To fix this problem, the compiler needs to know the set of changes made
_since the last successful build_, not simply since the last invocation.

This commit changes the incremental state system to much more explicitly
pass information from the previous to the next compilation, and in the
process to keep track of changes across multiple failed builds, until the
program can be analyzed successfully and the results of those changes
incorporated into the emit plan.

Fixes #32214

PR Close #33971
2019-11-22 17:39:35 -05:00
Igor Minar 955423c79b fix(bazel): ng_module should not emit shim files under bazel and Ivy (#33765)
Under bazel and Ivy we don't need the shim files to be emmited by default.

We still need to the shims for blaze however because google3 code imports them.

This improves build latency by 1-2 seconds per ng_module target.

PR Close #33765
2019-11-22 16:52:08 -05:00
Igor Minar 3c335c3590 fix(bazel): update to tsickle 0.37.1 to fix peerDep warnings (#33788)
tsickle 0.37.1 is compatible with typescript 3.6, so we should use it and fix peerDep warnings from npm/yarn.

PR Close #33788
2019-11-22 13:13:01 -05:00
JoostK 310ce6dcc2 fix(ngcc): do not crash on packages that specify typings as an array (#33973)
In a package.json file, the "typings" or "types" field could be an array
of typings files. ngcc would previously crash unexpectedly for such
packages, as it assumed that the typings field would be a string. This
commit lets ngcc skip over such packages, as having multiple typing
entry-points is not supported for Angular packages so it is safe to
ignore them.

Fixes #33646

PR Close #33973
2019-11-22 12:40:04 -05:00
Pete Bacon Darwin bf1bcd1e08 fix(ngcc): render localized strings when in ES5 format (#33857)
Recently the ngtsc translator was modified to be more `ScriptTarget`
aware, which basically means that it will not generate non-ES5 code
when the output format is ES5 or similar.

This commit enhances that change by also "downleveling" localized
messages. In ES2015 the messages use tagged template literals, which
are not available in ES5.

PR Close #33857
2019-11-21 10:54:59 -08:00
Pete Bacon Darwin 715d02aa14 fix(ngcc): report errors from `analyze` and `resolve` processing (#33964)
Previously, these errors were being swallowed, which made it
hard to debug problems with packages.

See https://github.com/angular/angular/issues/33685#issuecomment-557091719

PR Close #33964
2019-11-21 10:44:24 -08:00
Andrew Kushnir fc2f6b8456 fix(ivy): wrap functions from "providers" in parentheses in Closure mode (#33609)
Due to the fact that Tsickle runs between analyze and transform phases in Angular, Tsickle may transform nodes (add comments with type annotations for Closure) that we captured during the analyze phase. As a result, some patterns where a function is returned from another function may trigger automatic semicolon insertion, which breaks the code (makes functions return `undefined` instead of a function). In order to avoid the problem, this commit updates the code to wrap all functions in some expression ("privders" and "viewProviders") in parentheses. More info can be found in Tsickle source code here: d797426257/src/jsdoc_transformer.ts (L1021)

PR Close #33609
2019-11-20 14:58:35 -08:00
JoostK b07b6f1d40 fix(ivy): avoid infinite recursion when evaluation source files (#33772)
When ngtsc comes across a source file during partial evaluation, it
would determine all exported symbols from that module and evaluate their
values greedily. This greedy evaluation strategy introduces unnecessary
work and can fall into infinite recursion when the evaluation result of
an exported expression would circularly depend on the source file. This
would primarily occur in CommonJS code, where the `exports` variable can
be used to refer to an exported variable. This variable would be
resolved to the source file itself, thereby greedily evaluating all
exported symbols and thus ending up evaluating the `exports` variable
again. This variable would be resolved to the source file itself,
thereby greedily evaluating all exported symbols and thus ending u
evaluating the `exports` variable again. This variable would be
resolved to the source file itself, thereby greedily evaluating all
exported symbols and thus ending up evaluating the `exports` variable
again. This variable would be resolved to the source file itself,
thereby greedily evaluating all exported symbols and thus ending up
evaluating the `exports` variable again. This went on for some time
until all stack frames were exhausted.

This commit introduces a `ResolvedModule` that delays the evaluation of
its exports until they are actually requested. This avoids the circular
dependency when evaluating `exports`, thereby fixing the issue.

Fix #33734

PR Close #33772
2019-11-20 14:51:37 -08:00
JoostK 70311ebca1 fix(ivy): handle non-standard input/output names in template type checking (#33741)
The template type checker generates code to check directive inputs and
outputs, whose name may contain characters that can not be used as
identifier in TypeScript. Prior to this change, such names would be
emitted into the generated code as is, resulting in invalid code and
unexpected template type check errors.

This commit fixes the bug by representing the potentially invalid names
as string literal instead of raw identifier.

Fixes #33590

PR Close #33741
2019-11-20 14:51:12 -08:00
Alex Rickabaugh 08a4f10ee7 fix(ivy): move setClassMetadata calls into a pure iife (#33337)
This commit transforms the setClassMetadata calls generated by ngtsc from:

```typescript
/*@__PURE__*/ setClassMetadata(...);
```

to:

```typescript
/*@__PURE__*/ (function() {
  setClassMetadata(...);
})();
```

Without the IIFE, terser won't remove these function calls because the
function calls have arguments that themselves are function calls or other
impure expressions. In order to make the whole block be DCE-ed by terser,
we wrap it into IIFE and mark the IIFE as pure.

It should be noted that this change doesn't have any impact on CLI* with
build-optimizer, which removes the whole setClassMetadata block within
the webpack loader, so terser or webpack itself don't get to see it at
all. This is done to prevent cross-chunk retention issues caused by
webpack's internal module registry.

* actually we do expect a short-term size regression while
https://github.com/angular/angular-cli/pull/16228
is merged and released in the next rc of the CLI. But long term this
change does nothing to CLI + build-optimizer configuration and is done
primarly to correct the seemingly correct but non-function PURE annotation
that builds not using build-optimizer could rely on.

PR Close #33337
2019-11-20 12:55:58 -08:00
Alex Rickabaugh b54ed980ed fix(ivy): retain JIT metadata unless JIT mode is explicitly disabled (#33671)
NgModules in Ivy have a definition which contains various different bits
of metadata about the module. In particular, this metadata falls into two
categories:

* metadata required to use the module at runtime (for bootstrapping, etc)
in AOT-only applications.
* metadata required to depend on the module from a JIT-compiled app.

The latter metadata consists of the module's declarations, imports, and
exports. To support JIT usage, this metadata must be included in the
generated code, especially if that code is shipped to NPM. However, because
this metadata preserves the entire NgModule graph (references to all
directives and components in the app), it needs to be removed during
optimization for AOT-only builds.

Previously, this was done with a clever design:

1. The extra metadata was added by a function called `setNgModuleScope`.
A call to this function was generated after each NgModule.
2. This function call was marked as "pure" with a comment and used
`noSideEffects` internally, which causes optimizers to remove it.

The effect was that in dev mode or test mode (which use JIT), no optimizer
runs and the full NgModule metadata was available at runtime. But in
production (presumably AOT) builds, the optimizer runs and removes the JIT-
specific metadata.

However, there are cases where apps that want to use JIT in production, and
still make an optimized build. In this case, the JIT-specific metadata would
be erroneously removed. This commit solves that problem by adding an
`ngJitMode` global variable which guards all `setNgModuleScope` calls. An
optimizer can be configured to statically define this global to be `false`
for AOT-only builds, causing the extra metadata to be stripped.

A configuration for Terser used by the CLI is provided in `tooling.ts` which
sets `ngJitMode` to `false` when building AOT apps.

PR Close #33671
2019-11-20 12:55:43 -08:00
Alex Rickabaugh eb6975acaf fix(ivy): don't infer template context types when in full mode (#33537)
The Ivy template type-checker is capable of inferring the type of a
structural directive (such as NgForOf<T>). Previously, this was done with
fullTemplateTypeCheck: true, even if strictTemplates was false. View Engine
previously did not do this inference, and so this causes breakages if the
type of the template context is not what the user expected.

In particular, consider the template:

```html
<div *ngFor="let user of users as all">
  {{user.index}} out of {{all.length}}
</div>
```

As long as `users` is an array, this seems reasonable, because it appears
that `all` is an alias for the `users` array. However, this is misleading.

In reality, `NgForOf` is rendered with a template context that contains
both a `$implicit` value (for the loop variable `user`) as well as a
`ngForOf` value, which is the actual value assigned to `all`. The type of
`NgForOf`'s template context is `NgForContext<T>`, which declares `ngForOf`'s
type to be `NgIterable<T>`, which does not have a `length` property (due to
its incorporation of the `Iterable` type).

This commit stops the template type-checker from inferring template context
types unless strictTemplates is set (and strictInputTypes is not disabled).

Fixes #33527.

PR Close #33537
2019-11-20 11:47:42 -08:00
Alex Rickabaugh 97fbdab3b8 fix(ivy): report watch mode diagnostics correctly (#33862)
This commit changes the reporting of watch mode diagnostics for ngtsc to use
the same formatting as non-watch mode diagnostics. This prints rich and
contextual errors even in watch mode, which previously was not the case.

Fixes #32213

PR Close #33862
2019-11-20 11:46:02 -08:00
Alex Rickabaugh 4be8929844 fix(ivy): always re-analyze the program during incremental rebuilds (#33862)
Previously, the ngtsc compiler attempted to reuse analysis work from the
previous program during an incremental build. To do this, it had to prove
that the work was safe to reuse - that no changes made to the new program
would invalidate the previous analysis.

The implementation of this had a significant design flaw: if the previous
program had errors, the previous analysis would be missing significant
information, and the dependency graph extracted from it would not be
sufficient to determine which files should be re-analyzed to fill in the
gaps. This often meant that the build output after an error was resolved
would be wholly incorrect.

This commit switches ngtsc to take a simpler approach to incremental
rebuilds. Instead of attempting to reuse prior analysis work, the entire
program is re-analyzed with each compilation. This is actually not as
expensive as one might imagine - analysis is a fairly small part of overall
compilation time.

Based on the dependency graph extracted during this analysis, the compiler
then can make accurate decisions on whether to emit specific files. A new
suite of tests is added to validate behavior in the presence of source code
level errors.

This new approach is dramatically simpler than the previous algorithm, and
should always produce correct results for a semantically correct program.s

Fixes #32388
Fixes #32214

PR Close #33862
2019-11-20 11:46:02 -08:00
Alex Rickabaugh cf9aa4fd14 test(ivy): driveDiagnostics() works incrementally (#33862)
PR Close #33862
2019-11-20 11:46:02 -08:00
Alex Rickabaugh bb290cefae fix(core): make QueryList implement Iterable in the type system (#33536)
Originally, QueryList implemented Iterable and provided a Symbol.iterator
on its prototype. This caused issues with tree-shaking, so QueryList was
refactored and the Symbol.iterator added in its constructor instead. As
part of this change, QueryList no longer implemented Iterable directly.

Unfortunately, this meant that QueryList was no longer assignable to
Iterable or, consequently, NgIterable. NgIterable is used for NgFor's input,
so this meant that QueryList was not usable (in a type sense) for NgFor
iteration. View Engine's template type checking would not catch this, but
Ivy's did.

As a fix, this commit adds the declaration (but not the implementation) of
the Symbol.iterator function back to QueryList. This has no runtime effect,
so it doesn't affect tree-shaking of QueryList, but it ensures that
QueryList is assignable to NgIterable and thus usable with NgFor.

Fixes #29842

PR Close #33536
2019-11-19 13:43:53 -08:00
Alex Rickabaugh 850aee2448 fix(ivy): emit fs-relative paths when rootDir(s) aren't in effect (#33828)
Previously, the compiler assumed that all TS files logically within a
project existed under one or more "root directories". If the TS compiler
option `rootDir` or `rootDirs` was set, they would dictate the root
directories in use, otherwise the current directory was used.

Unfortunately this assumption was unfounded - it's common for projects
without explicit `rootDirs` to import from files outside the current
working directory. In such cases the `LogicalProjectStrategy` would attempt
to generate imports into those files, and fail. This would lead to no
`ReferenceEmitStrategy` being able to generate an import, and end in a
compiler assertion failure.

This commit introduces a new strategy to use when there are no `rootDirs`
explicitly present, the `RelativePathStrategy`. It uses simpler, filesystem-
relative paths to generate imports, even to files above the current working
directory.

Fixes #33659
Fixes #33562

PR Close #33828
2019-11-19 12:41:24 -08:00
Alex Rickabaugh 51720745dd test(ivy): support chdir() on the compiler's filesystem abstraction (#33828)
This commit adds the ability to change directories using the compiler's
internal filesystem abstraction. This is a prerequisite for writing tests
which are sensitive to the current working directory.

In addition to supporting the `chdir()` operation, this commit also fixes
`getDefaultLibLocation()` for mock filesystems to not assume `node_modules`
is in the current directory, but to resolve it similarly to how Node does
by progressively looking higher in the directory tree.

PR Close #33828
2019-11-19 12:41:24 -08:00