Commit Graph

1500 Commits

Author SHA1 Message Date
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
Kristiyan Kostadinov 8a052dc858 perf(ivy): chain styling instructions (#33837)
Adds support for chaining of `styleProp`, `classProp` and `stylePropInterpolateX` instructions whenever possible which should help generate less code. Note that one complication here is for `stylePropInterpolateX` instructions where we have to break into multiple chains if there are other styling instructions inbetween the interpolations which helps maintain the execution order.

PR Close #33837
2019-11-19 11:44:29 -08:00
Alex Rickabaugh 29b8666b10 fix(ngcc): properly detect origin of constructor param types (#33901)
The ReflectionHost supports enumeration of constructor parameters, and one
piece of information it returns describes the origin of the parameter's
type. Parameter types come in two flavors: local (the type is not imported
from anywhere) or non-local (the type comes via an import).

ngcc incorrectly classified all type parameters as 'local', because in the
source files that ngcc processes the type parameter is a real ts.Identifer.
However, that identifier may still have come from an import and thus might
be non-local.

This commit changes ngcc's ReflectionHost(s) to properly recognize and
report these non-local type references.

Fixes #33677

PR Close #33901
2019-11-19 11:38:33 -08:00
Pete Bacon Darwin a6247aafa1 fix(ivy): i18n - support "\", "`" and "${" sequences in i18n messages (#33820)
Since i18n messages are mapped to `$localize` tagged template strings,
the "raw" version must be properly escaped. Otherwise TS will throw an
error such as:

```
Error: Debug Failure. False expression: Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.
```

This commit ensures that we properly escape these raw strings before creating
TS AST nodes from them.

PR Close #33820
2019-11-18 16:00:22 -08:00
Pete Bacon Darwin 62f7d0fe5c fix(ivy): i18n - ensure that colons in i18n metadata are not rendered (#33820)
The `:` char is used as a metadata marker in `$localize` messages.
If this char appears in the metadata it must be escaped, as `\:`.
Previously, although the `:` char was being escaped, the TS AST
being generated was not correct and so it was being output double
escaped, which meant that it appeared in the rendered message.

As of TS 3.6.2 the "raw" string can be specified when creating tagged
template AST nodes, so it is possible to correct this.

PR Close #33820
2019-11-18 16:00:22 -08:00
Paul Gschwendtner 15fefdbb8d feat(core): missing-injectable migration should migrate empty object literal providers (#33709)
In View Engine, providers which neither used `useValue`, `useClass`,
`useFactory` or `useExisting`, were interpreted differently.

e.g.

```
{provide: X} -> {provide: X, useValue: undefined}, // this is how it works in View Engine
{provide: X} -> {provide: X, useClass: X}, // this is how it works in Ivy
```

The missing-injectable migration should migrate such providers to the
explicit `useValue` provider. This ensures that there is no unexpected
behavioral change when updating to v9.

PR Close #33709
2019-11-18 15:47:20 -08:00
JoostK 7215889b3c fix(ngcc): always add exports for `ModuleWithProviders` references (#33875)
In #32902 a bug was supposedly fixed where internal classes as used
within `ModuleWithProviders` are publicly exported, even when the
typings file already contained the generic type on the
`ModuleWithProviders`. This fix turns out to have been incomplete, as
the `ModuleWithProviders` analysis is not done when not processing the
typings files.

The effect of this bug is that formats that are processed after the
initial format had been processed would not have exports for internal
symbols, resulting in "export '...' was not found in '...'" errors.

This commit fixes the bug by always running the `ModuleWithProviders`
analyzer. An integration test has been added that would fail prior to
this change.

Fixes #33701

PR Close #33875
2019-11-18 09:11:34 -08:00
JoostK 32a4a549fd test(ngcc): expand integration tests with APF like package layouts (#33875)
ngcc has a basic integration test infrastructure that downlevels
TypeScript code into bundle formats that need to be processed by ngcc.
Until now, only ES5 bundles were created with a flat structure, however
more complex scenarios require an APF-like layout containing multiple
bundle formats.

PR Close #33875
2019-11-18 09:11:34 -08:00
JoostK 985cadb73d fix(ngcc): correctly include internal .d.ts files (#33875)
Some declaration files may not be referenced from an entry-point's
main typings file, as it may declare types that are only used internally.
ngcc has logic to include declaration files based on all source files,
to ensure internal declaration files are available.

For packages following APF layout, however, this logic was insufficient.
Consider an entry-point with base path of `/esm2015/testing` and typings
residing in `/testing`, the file
`/esm2015/testing/src/nested/internal.js` has its typings file at
`/testing/src/nested/internal.d.ts`. Previously, the declaration was
assumed to be located at `/esm2015/testing/testing/internal.d.ts` (by
means of `/esm2015/testing/src/nested/../../testing/internal.d.ts`)
which is not where the declaration file can be found. This commit
resolves the issue by looking in the correct directory.

PR Close #33875
2019-11-18 09:11:34 -08:00
JoostK e666d283dd fix(ngcc): correctly associate decorators with aliased classes (#33878)
In flat bundle formats, multiple classes that have the same name can be
suffixed to become unique. In ES5-like bundles this results in the outer
declaration from having a different name from the "implementation"
declaration within the class' IIFE, as the implementation declaration
may not have been suffixed.

As an example, the following code would fail to have a `Directive`
decorator as ngcc would search for `__decorate` calls that refer to
`AliasedDirective$1` by name, whereas the `__decorate` call actually
uses the `AliasedDirective` name.

```javascript
var AliasedDirective$1 = /** @class */ (function () {
    function AliasedDirective() {}
    AliasedDirective = tslib_1.__decorate([
        Directive({ selector: '[someDirective]' }),
    ], AliasedDirective);
    return AliasedDirective;
}());
```

This commit fixes the problem by not relying on comparing names, but
instead finding the declaration and matching it with both the outer
and inner declaration.

PR Close #33878
2019-11-18 09:10:35 -08:00
JoostK 19a6c158d2 test(ngcc): avoid using spy in `Esm2015ReflectionHost` test (#33878)
A testcase that was using a spy has shown itself to be brittle, and its
assertions can easily be moved into a related test.

PR Close #33878
2019-11-18 09:10:35 -08:00
Joey Perrott e6045ee0b7 build: fixes for cross-platform RBE (#33708)
The earlier update to nodejs rules 0.40.0 fixes the cross-platform RBE issues with nodejs_binary. This commit adds a work-around for rules_webtesting cross-platform RBE issues.

PR Close #33708
2019-11-15 10:49:55 -08:00
Misko Hevery ab0bcee144 fix(ivy): support for #id bootstrap selectors (#33784)
Fixes: #33485

PR Close #33784
2019-11-15 10:42:52 -08:00
Keen Yee Liau 9935aa43ad refactor(compiler-cli): Move diagnostics files to language service (#33809)
The following files are consumed only by the language service and do not
have to be in compiler-cli:

1. expression_diagnostics.ts
2. expression_type.ts
3. typescript_symbols.ts
4. symbols.ts

PR Close #33809
2019-11-14 09:29:07 -08:00
George Kalpakas 033aba9351 fix(ngcc): do not emit ES2015 code in ES5 files (#33514)
Previously, ngcc's `Renderer` would add some constants in the processed
files which were emitted as ES2015 code (e.g. `const` declarations).
This would result in invalid ES5 generated code that would break when
run on browsers that do not support the emitted format.

This commit fixes it by adding a `printStatement()` method to
`RenderingFormatter`, which can convert statements to JavaScript code in
a suitable format for the corresponding `RenderingFormatter`.
Additionally, the `translateExpression()` and `translateStatement()`
ngtsc helper methods are augmented to accept an extra hint to know
whether the code needs to be translated to ES5 format or not.

Fixes #32665

PR Close #33514
2019-11-13 13:49:31 -08:00
George Kalpakas 704775168d fix(ngcc): generate correct metadata for classes with getter/setter properties (#33514)
While processing class metadata, ngtsc generates a `setClassMetadata()`
call which (among other things) contains info about property decorators.
Previously, processing getter/setter pairs with some of ngcc's
`ReflectionHost`s resulted in multiple metadata entries for the same
property, which resulted in duplicate object keys, which in turn causes
an error in ES5 strict mode.

This commit fixes it by ensuring that there are no duplicate property
names in the `setClassMetadata()` calls.

In addition, `generateSetClassMetadataCall()` is updated to treat
`ClassMember#decorators: []` the same as `ClassMember.decorators: null`
(i.e. omitting the `ClassMember` from the generated `setClassMetadata()`
call). Alternatively, ngcc's `ReflectionHost`s could be updated to do
this transformation (`decorators: []` --> `decorators: null`) when
reflecting on class members, but this would require changes in many
places and be less future-proof.

For example, given a class such as:

```ts
class Foo {
  @Input() get bar() { return 'bar'; }
  set bar(value: any) {}
}
```

...previously the generated `setClassMetadata()` call would look like:

```ts
ɵsetClassMetadata(..., {
  bar: [{type: Input}],
  bar: [],
});
```

The same class will now result in a call like:

```ts
ɵsetClassMetadata(..., {
  bar: [{type: Input}],
});
```

Fixes #30569

PR Close #33514
2019-11-13 13:49:31 -08:00
George Kalpakas c79d50f38f refactor(compiler-cli): avoid superfluous parenthesis around statements (#33514)
Previously, due to a bug a `Context` with `isStatement: false` could be
returned in places where a `Context` with `isStatement: true` was
requested. As a result, some statements would be unnecessarily wrapped
in parenthesis.

This commit fixes the bug in `Context#withStatementMode` to always
return a `Context` with the correct `isStatement` value. Note that this
does not have any impact on the generated code other than avoiding some
superfluous parenthesis on certain statements.

PR Close #33514
2019-11-13 13:49:30 -08:00
crisbeto fcdada53f1 fix(ivy): constant object literals shared across element and component instances (#33705)
Currently if a consumer does something like the following, the object literal will be shared across the two elements and any instances of the component template. The same applies to array literals:

```
<div [someDirective]="{}"></div>
<div [someDirective]="{}"></div>
```

These changes make it so that we generate a pure function even if an object is constant so that each instance gets its own object.

Note that the original design for this fix included moving the pure function factories into the `consts` array. In the process of doing so I realized that pure function are also used inside of directive host bindings which means that we don't have access to the `consts`.

These changes also:
* Fix an issue that meant that the `pureFunction0` instruction could only be run during creation mode.
* Make the `getConstant` utility slightly more convenient to use. This isn't strictly required for these changes to work, but I had made it as a part of a larger refactor that I ended up reverting.

PR Close #33705
2019-11-13 13:36:41 -08:00
Joey Perrott 1d563a7acd build: set up all packages to publish via wombot proxy (#33747)
PR Close #33747
2019-11-13 11:34:33 -08:00
Pete Bacon Darwin 1e1e242570 fix(ngcc): support minified ES5 scenarios (#33777)
The reflection hosts have been updated to support the following
code forms, which were found in some minified library code:

* The class IIFE not being wrapped in parentheses.
* Calls to `__decorate()` being combined with the IIFE return statement.

PR Close #33777
2019-11-13 11:11:48 -08:00
Pete Bacon Darwin d21471e24e fix(ngcc): remove `__decorator` calls even when part of the IIFE return statement (#33777)
Previously we only removed `__decorate()` calls that looked like:

```
SomeClass = __decorate(...);
```

But in some minified scenarios this call gets wrapped up with the
return statement of the IIFE.

```
return SomeClass = __decorate(...);
```

This is now removed also, leaving just the return statement:

```
return SomeClass;
```

PR Close #33777
2019-11-13 11:11:48 -08:00
Pete Bacon Darwin 9c6ee5fcd0 refactor(ngcc): move `stripParentheses` to `Esm5ReflectionHost` for re-use (#33777)
PR Close #33777
2019-11-13 11:11:48 -08:00
Pete Bacon Darwin 7f24975a60 refactor(ngcc): remove unused function (#33777)
PR Close #33777
2019-11-13 11:11:48 -08:00
George Kalpakas 95715fc71e fix(ngcc): add default config for `ng2-dragula` (#33797)
The `dist/` directory has a duplicate `package.json` pointing to the
same files, which (under certain configurations) can causes ngcc to try
to process the files twice and fail.

This commit adds a default ngcc config for `ng2-dragula` to ignore the
`dist/` entry-point.

Fixes #33718

PR Close #33797
2019-11-13 11:09:59 -08:00
JoostK 15f8638b1c fix(ivy): ensure module scope is rebuild on dependent change (#33522)
During incremental compilations, ngtsc needs to know which metadata
from a previous compilation can be reused, versus which metadata has to
be recomputed as some dependency was updated. Changes to
directives/components should cause the NgModule in which they are
declared to be recompiled, as the NgModule's compilation is dependent
on its directives/components.

When a dependent source file of a directive/component is updated,
however, a more subtle dependency should also cause to NgModule's source
file to be invalidated. During the reconciliation of state from a
previous compilation into the new program, the component's source file
is invalidated because one of its dependency has changed, ergo the
NgModule needs to be invalidated as well. Up until now, this implicit
dependency was not imposed on the NgModule. Additionally, any change to
a dependent file may influence the module scope to change, so all
components within the module must be invalidated as well.

This commit fixes the bug by introducing additional file dependencies,
as to ensure a proper rebuild of the module scope and its components.

Fixes #32416

PR Close #33522
2019-11-12 13:56:30 -08:00
JoostK 6899ee5ddd fix(ivy): recompile component when template changes in ngc watch mode (#33551)
When the Angular compiler is operated through the ngc binary in watch
mode, changing a template in an external file would not cause the
component to be recompiled if Ivy is enabled.

There was a problem with how a cached compiler host was present that was
unaware of the changed resources, therefore failing to trigger a
recompilation of a component whenever its template changes. This commit
fixes the issue by ensuring that information about modified resources is
correctly available to the cached compiler host.

Fixes #32869

PR Close #33551
2019-11-12 13:55:09 -08:00
Pete Bacon Darwin 641c671bac fix(core): support `ngInjectableDef` on types with inherited `ɵprov` (#33732)
The `ngInjectableDef` property was renamed to `ɵprov`, but core must
still support both because there are published libraries that use the
older term.

We are only interested in such properties that are defined directly on
the type being injected, not on base classes. So there is a check that
the defintion is specifically for the given type.

Previously if you tried to inject a class that had `ngInjectableDef` but
also inherited `ɵprov` then the check would fail on the `ɵprov` property
and never even try the `ngInjectableDef` property resulting in a failed
injection.

This commit fixes this by attempting to find each of the properties
independently.

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

PR Close #33732
2019-11-12 11:54:15 -08:00
crisbeto e31f62045d perf(ivy): chain listener instructions (#33720)
Chains multiple listener instructions on a particular element into a single call which results in less generated code. Also handles listeners on templates, host listeners and synthetic host listeners.

PR Close #33720
2019-11-12 09:59:13 -08:00
Keen Yee Liau 8b91ea5532 fix(language-service): Resolve template variable in nested ngFor (#33676)
This commit fixes a bug whereby template variables in nested scope are
not resolved properly and instead are simply typed as `any`.

PR closes https://github.com/angular/vscode-ng-language-service/issues/144

PR Close #33676
2019-11-11 16:06:00 -08:00
Pete Bacon Darwin b3c3000004 fix(ngcc): ensure that adjacent statements go after helper calls (#33689)
Previously the renderers were fixed so that they inserted extra
"adjacent" statements after the last static property of classes.

In order to help the build-optimizer (in Angular CLI) to be able to
tree-shake classes effectively, these statements should also appear
after any helper calls, such as `__decorate()`.

This commit moves the computation of this positioning into the
`NgccReflectionHost` via the `getEndOfClass()` method, which
returns the last statement that is related to the class.

FW-1668

PR Close #33689
2019-11-11 13:01:15 -08:00
Pete Bacon Darwin 52d1500155 refactor(ngcc): allow look up of multiple helpers (#33689)
This change is a precursor to finding the end of a
class, which needs to search for helpers of many
different names.

PR Close #33689
2019-11-11 13:01:15 -08:00
Keen Yee Liau a33162bb66 fix(compiler-cli): Pass SourceFile to getFullText() (#33660)
Similar to https://github.com/angular/angular/pull/33633, this commit is
needed to fix an outage with the Angular Kythe indexer.

Crash logs:

```
TypeError: Cannot read property 'text' of undefined
    at NodeObject.getFullText (typescript/stable/lib/typescript.js:121443:57)
    at FactoryGenerator.generate (angular2/rc/packages/compiler-cli/src/ngtsc/shims/src/factory_generator.ts:67:34)
    at GeneratedShimsHostWrapper.getSourceFile (angular2/rc/packages/compiler-cli/src/ngtsc/shims/src/host.ts:88:26)
    at findSourceFile (typescript/stable/lib/typescript.js:90654:29)
    at typescript/stable/lib/typescript.js:90553:85
    at getSourceFileFromReferenceWorker (typescript/stable/lib/typescript.js:90520:34)
    at processSourceFile (typescript/stable/lib/typescript.js:90553:13)
    at processRootFile (typescript/stable/lib/typescript.js:90383:13)
    at typescript/stable/lib/typescript.js:89399:60
    at Object.forEach (typescript/stable/lib/typescript.js:280:30)

```

PR Close #33660
2019-11-07 16:47:07 -08:00
JoostK 81828ae7f4 fix(ngcc): add reexports only once (#33658)
When ngcc is configured to generate reexports for a package using the
`generateDeepReexports` configuration option, it could incorrectly
render the reexports as often as the number of compiled classes in the
declaration file. This would cause compilation errors due to duplicated
declarations.

PR Close #33658
2019-11-07 20:29:13 +00:00
Andrew Scott 7c5c2139ab revert: "fix(ivy): recompile component when template changes in ngc watch mode (#33551)" (#33661)
This reverts commit 8912b11f56.

PR Close #33661
2019-11-07 19:57:56 +00:00
JoostK 8912b11f56 fix(ivy): recompile component when template changes in ngc watch mode (#33551)
When the Angular compiler is operated through the ngc binary in watch
mode, changing a template in an external file would not cause the
component to be recompiled if Ivy is enabled.

There was a problem with how a cached compiler host was present that was
unaware of the changed resources, therefore failing to trigger a
recompilation of a component whenever its template changes. This commit
fixes the issue by ensuring that information about modified resources is
correctly available to the cached compiler host.

Fixes #32869

PR Close #33551
2019-11-07 17:52:58 +00:00
Keen Yee Liau 10583f951d fix(compiler-cli): Fix typo $implict (#33633)
Should be $implicit instead.

PR Close #33633
2019-11-07 01:54:17 +00:00
Pete Bacon Darwin fe12d0dc78 fix(ngcc): render adjacent statements after static properties (#33630)
See https://github.com/angular/angular/pull/33337#issuecomment-545487737

Fixes FW-1664

PR Close #33630
2019-11-06 19:54:05 +00:00
JoostK e2d7b25e0d fix(ivy): avoid implicit any errors in event handlers (#33550)
When template type checking is configured with `strictDomEventTypes` or
`strictOutputEventTypes` disabled, in compilation units that have
`noImplicitAny` enabled but `strictNullChecks` disabled, a template type
checking error could be produced for certain event handlers.

The error is avoided by letting an event handler in the generated TCB
always have an explicit `any` return type.

Fixes #33528

PR Close #33550
2019-11-06 19:45:45 +00:00
Alan Agius d749dd3ea1 fix(ngcc): handle new `__spreadArrays` tslib helper (#33617)
We already have special cases for the `__spread` helper function and with this change we handle the new tslib helper introduced in version 1.10 `__spreadArrays`.

For more context see: https://github.com/microsoft/tslib/releases/tag/1.10.0

Fixes: #33614

PR Close #33617
2019-11-06 19:43:07 +00:00
JiaLiPassion 8c6fb17d29 build: reference zone.js from source directly instead of npm. (#33046)
Close #32482

PR Close #33046
2019-11-06 00:48:34 +00:00
Keen Yee Liau 4b62ba9017 fix(compiler-cli): Pass SourceFile to getLeadingTriviaWidth (#33588)
This commit fixes a crash in the Angular Kythe indexer caused by failure
to retrieve `SourceFile` in a `Statement`.

Crash logs:
  TypeError: Cannot read property 'text' of undefined
    at Object.getTokenPosOfNode (typescript/stable/lib/typescript.js:8957:72)
    at NodeObject.getStart (typescript/stable/lib/typescript.js:121419:23)
    at NodeObject.getLeadingTriviaWidth (typescript/stable/lib/typescript.js:121439:25)
    at FactoryGenerator.generate (angular2/rc/packages/compiler-cli/src/ngtsc/shims/src/factory_generator.ts:64:49)
    at GeneratedShimsHostWrapper.getSourceFile (angular2/rc/packages/compiler-cli/src/ngtsc/shims/src/host.ts:88:26)
    at findSourceFile (typescript/stable/lib/typescript.js:90654:29)
    at typescript/stable/lib/typescript.js:90553:85
    at getSourceFileFromReferenceWorker (typescript/stable/lib/typescript.js:90520:34)
    at processSourceFile (typescript/stable/lib/typescript.js:90553:13)
    at processRootFile (typescript/stable/lib/typescript.js:90383:13)

PR Close #33588
2019-11-05 21:02:45 +00:00
Pete Bacon Darwin 85298e345d fix(ngcc): render new definitions using the inner name of the class (#33533)
When decorating classes with ivy definitions (e.g. `ɵfac` or `ɵdir`)
the inner name of the class declaration must be used.

This is because in ES5 the definitions are inside the class's IIFE
where the outer declaration has not yet been initialized.

PR Close #33533
2019-11-05 17:25:02 +00:00
Pete Bacon Darwin 93a23b9ae0 fix(ngcc): override `getInternalNameOfClass()` and `getAdjacentNameOfClass()` for ES5 (#33533)
In ES5 the class consists of an outer variable declaration that is
initialised by an IIFE. Inside the IIFE the class is implemented by
an inner function declaration that is returned from the IIFE.
This inner declaration may have a different name to the outer
declaration.

This commit overrides `getInternalNameOfClass()` and
`getAdjacentNameOfClass()` in `Esm5ReflectionHost` with methods that
can find the correct inner declaration name identifier.

PR Close #33533
2019-11-05 17:25:01 +00:00
Pete Bacon Darwin 90f33dd11d refactor(ngcc): remove unnecessary ! operator (#33533)
PR Close #33533
2019-11-05 17:25:01 +00:00
Alex Rickabaugh 8d0de89ece refactor(ivy): split `type` into `type`, `internalType` and `adjacentType` (#33533)
When compiling an Angular decorator (e.g. Directive), @angular/compiler
generates an 'expression' to be added as a static definition field
on the class, a 'type' which will be added for that field to the .d.ts
file, and a statement adjacent to the class that calls `setClassMetadata()`.

Previously, the same WrappedNodeExpr of the class' ts.Identifier was used
within each of this situations.

In the ngtsc case, this is proper. In the ngcc case, if the class being
compiled is within an ES5 IIFE, the outer name of the class may have
changed. Thus, the class has both an inner and outer name. The outer name
should continue to be used elsewhere in the compiler and in 'type'.

The 'expression' will live within the IIFE, the `internalType` should be used.
The adjacent statement will also live within the IIFE, the `adjacentType` should be used.

This commit introduces `ReflectionHost.getInternalNameOfClass()` and
`ReflectionHost.getAdjacentNameOfClass()`, which the compiler can use to
query for the correct name to use.

PR Close #33533
2019-11-05 17:25:01 +00:00
Andrew Kushnir d9a38928f5 fix(ivy): more descriptive errors for nested i18n sections (#33583)
This commit moves nested i18n section detection to an earlier stage where we convert HTML AST to Ivy AST. This also gives a chance to produce better diagnistic message for nested i18n sections, that also includes a file name and location.

PR Close #33583
2019-11-05 17:20:47 +00:00
crisbeto 66725b7b37 perf(ivy): move local references into consts array (#33129)
Follow-up from #32798. Moves the local references array into the component def's `consts` in order to make it compress better.

Before:
```
const _c0 = ['foo', ''];

SomeComp.ngComponentDef = defineComponent({
  template: function() {
    element(0, 'div', null, _c0);
  }
});
```

After:
```
SomeComp.ngComponentDef = defineComponent({
  consts: [['foo', '']],
  template: function() {
    element(0, 'div', null, 0);
  }
});
```

PR Close #33129
2019-11-04 16:30:53 +00:00
Charles Lyding fc8eecad3f fix(compiler-cli): remove unused CLI private exports (#33242)
These exports are no longer used by the CLI since 7.1.0.  Since major versions of the CLI are now locked to major versions of the framework, a CLI user will not be able to use FW 9.0+ on an outdated version (<7.1.0) of the CLI that uses these old APIs.

PR Close #33242
2019-11-01 17:43:47 +00:00
JoostK ce30888a26 feat(ivy): graceful evaluation of unknown or invalid expressions (#33453)
During static evaluation of expressions within ngtsc, it may occur that
certain expressions or just parts thereof cannot be statically
interpreted for some reason. The static interpreter keeps track of the
failure reason and the code path that was evaluated by means of
`DynamicValue`, which will allow descriptive errors. In some situations
however, the static interpreter would throw an exception instead,
resulting in a crash of the compilation. Not only does this cause
non-descriptive errors, more importantly does it prevent the evaluated
result from being partial, i.e. parts of the result can be dynamic if
their value does not have to be statically available to the compiler.

This commit refactors the static interpreter to never throw errors for
certain expressions that it cannot evaluate.

Resolves FW-1582

PR Close #33453
2019-11-01 00:04:02 +00:00
Alex Rickabaugh 38758d856a fix(ivy): don't crash on unknown pipe (#33454)
Previously the compiler would crash if a pipe was encountered which did not
match any pipe in the scope of a template.

This commit introduces a new diagnostic error for unknown pipes instead.

PR Close #33454
2019-10-31 23:43:32 +00:00
Alex Rickabaugh 9db59d010d fix(ivy): don't crash on an unknown localref target (#33454)
Previously the template binder would crash when encountering an unknown
localref (# reference) such as `<div #ref="foo">` when no directive has
`exportAs: "foo"`.

With this commit, the compiler instead generates a template diagnostic error
informing the user about the invalid reference.

PR Close #33454
2019-10-31 23:43:32 +00:00
Pete Bacon Darwin 1d141a8ab1 fix(compiler-cli): attach the correct `viaModule` to namespace imports (#33495)
Previously declarations that were imported via a namespace import
were given the same `bestGuessOwningModule` as the context
where they were imported to. This causes problems with resolving
`ModuleWithProviders` that have a type that has been imported in
this way, causing errors like:

```
ERROR in Symbol UIRouterModule declared in
.../@uirouter/angular/uiRouterNgModule.d.ts
is not exported from
.../@uirouter/angular/uirouter-angular.d.ts
(import into .../src/app/child.module.ts)
```

This commit modifies the `TypescriptReflectionHost.getDirectImportOfIdentifier()`
method so that it also understands how to attach the correct `viaModule` to
the identifier of the namespace import.

Resolves #32166

PR Close #33495
2019-10-31 22:25:48 +00:00
Keen Yee Liau 1de757993d fix(language-service): Improve signature selection for pipes with args (#33456)
Pipes with arguments like `slice:0` or `slice:0:1` should not produce
diagnostic errors.

PR closes https://github.com/angular/vscode-ng-language-service/issues/345

PR Close #33456
2019-10-29 14:40:35 -07:00
crisbeto c3e93564d0 perf(ivy): avoid generating selectors array for directives without a selector (#33431)
Now that we've replaced `ngBaseDef` with an abstract directive definition, there are a lot more cases where we generate a directive definition without a selector. These changes make it so that we don't generate the `selectors` array if it's going to be empty.

PR Close #33431
2019-10-29 12:06:15 -07:00
Greg Magolan 4ee354da99 build: switch to @build_bazel_rules_nodejs//:index.bzl load point (#33433)
The defs.bzl load point will be removed for the rules_nodejs 1.0 release.

PR Close #33433
2019-10-28 10:10:48 -07:00
crisbeto 14c4b1b205 refactor(ivy): remove ngBaseDef (#33264)
Removes `ngBaseDef` from the compiler and any runtime code that was still referring to it. In the cases where we'd previously generate a base def we now generate a definition for an abstract directive.

PR Close #33264
2019-10-25 13:11:34 -07:00
JoostK 8d15bfa6ee fix(ivy): allow abstract directives to have an invalid constructor (#32987)
For abstract directives, i.e. directives without a selector, it may
happen that their constructor is called explicitly from a subclass,
hence its parameters are not required to be valid for Angular's DI
purposes. Prior to this commit however, having an abstract directive
with a constructor that has parameters that are not eligible for
Angular's DI would produce a compilation error.

A similar scenario may occur for `@Injectable`s, where an explicit
`use*` definition allows for the constructor to be irrelevant. For
example, the situation where `useFactory` is specified allows for the
constructor to be called explicitly with any value, so its constructor
parameters are not required to be valid. For `@Injectable`s this is
handled by generating a DI factory function that throws.

This commit implements the same solution for abstract directives, such
that a compilation error is avoided while still producing an error at
runtime if the type is instantiated implicitly by Angular's DI
mechanism.

Fixes #32981

PR Close #32987
2019-10-25 12:13:23 -07:00
Alex Rickabaugh b381497126 feat(ngcc): add a migration for undecorated child classes (#33362)
In Angular View Engine, there are two kinds of decorator inheritance:

1) both the parent and child classes have decorators

This case is supported by InheritDefinitionFeature, which merges some fields
of the definitions (such as the inputs or queries).

2) only the parent class has a decorator

If the child class is missing a decorator, the compiler effectively behaves
as if the parent class' decorator is applied to the child class as well.
This is the "undecorated child" scenario, and this commit adds a migration
to ngcc to support this pattern in Ivy.

This migration has 2 phases. First, the NgModules of the application are
scanned for classes in 'declarations' which are missing decorators, but
whose base classes do have decorators. These classes are the undecorated
children. This scan is performed recursively, so even if a declared class
has a base class that itself inherits a decorator, this case is handled.

Next, a synthetic decorator (either @Component or @Directive) is created
on the child class. This decorator copies some critical information such
as 'selector' and 'exportAs', as well as supports any decorated fields
(@Input, etc). A flag is passed to the decorator compiler which causes a
special feature `CopyDefinitionFeature` to be included on the compiled
definition. This feature copies at runtime the remaining aspects of the
parent definition which `InheritDefinitionFeature` does not handle,
completing the "full" inheritance of the child class' decorator from its
parent class.

PR Close #33362
2019-10-25 09:16:50 -07:00
JoostK 6b267482d7 feat(ngcc): enable migrations to apply schematics to libraries (#33362)
When upgrading an Angular application to a new version using the Angular
CLI, built-in schematics are being run to update user code from
deprecated patterns to the new way of working. For libraries that have
been built for older versions of Angular however, such schematics have
not been executed which means that deprecated code patterns may still be
present, potentially resulting in incorrect behavior.

Some of the logic of schematics has been ported over to ngcc migrations,
which are automatically run on libraries. These migrations achieve the
same goal of the regular schematics, but operating on published library
sources instead of used code.

PR Close #33362
2019-10-25 09:16:50 -07:00
JoostK 2e5e1dd5f5 refactor(ngcc): rework undecorated parent migration (#33362)
Previously, the (currently disabled) undecorated parent migration in
ngcc would produce errors when a base class could not be determined
statically or when a class extends from a class in another package. This
is not ideal, as it would cause the library to fail compilation without
a workaround, whereas those problems are not guaranteed to cause issues.

Additionally, inheritance chains were not handled. This commit reworks
the migration to address these limitations.

PR Close #33362
2019-10-25 09:16:50 -07:00
JoostK 3858b26211 refactor(ivy): mark synthetic decorators explicitly (#33362)
In ngcc's migration system, synthetic decorators can be injected into a
compilation to ensure that certain classes are compiled with Angular
logic, where the original library code did not include the necessary
decorators. Prior to this change, synthesized decorators would have a
fake AST structure as associated node and a made-up identifier. In
theory, this may introduce issues downstream:

1) a decorator's node is used for diagnostics, so it must have position
information. Having fake AST nodes without a position is therefore a
problem. Note that this is currently not a problem in practice, as
injected synthesized decorators would not produce any diagnostics.

2) the decorator's identifier should refer to an imported symbol.
Therefore, it is required that the symbol is actually imported.
Moreover, bundle formats such as UMD and CommonJS use namespaces for
imports, so a bare `ts.Identifier` would not be suitable to use as
identifier. This was also not a problem in practice, as the identifier
is only used in the `setClassMetadata` generated code, which is omitted
for synthetically injected decorators.

To remedy these potential issues, this commit makes a decorator's
identifier optional and switches its node over from a fake AST structure
to the class' name.

PR Close #33362
2019-10-25 09:16:49 -07:00
JoostK 31b9492951 feat(ngcc): migrate services that are missing `@Injectable()` (#33362)
A class that is provided as Angular service is required to have an
`@Injectable()` decorator so that the compiler generates its injectable
definition for the runtime. Applications are automatically migrated
using the "missing-injectable" schematic, however libraries built for
older version of Angular may not yet satisfy this requirement.

This commit ports the "missing-injectable" schematic to a migration that
is ran when ngcc is processing a library. This ensures that any service
that is provided from an NgModule or Directive/Component will have an
`@Injectable()` decorator.

PR Close #33362
2019-10-25 09:16:49 -07:00
JoostK 0de2dbfec1 fix(ngcc): prevent reflected decorators from being clobbered (#33362)
ngcc has an internal cache of computed decorator information for
reflected classes, which could previously be mutated by consumers of the
reflection host. With the ability to inject synthesized decorators, such
decorators would inadvertently be added into the array of decorators
that was owned by the internal cache of the reflection host, incorrectly
resulting in synthesized decorators to be considered real decorators on
a class. This commit fixes the issue by cloning the cached array before
returning it.

PR Close #33362
2019-10-25 09:16:49 -07:00
Matias Niemelä dcdb433b7d perf(ivy): apply [style]/[class] bindings directly to style/className (#33336)
This patch ensures that the `[style]` and `[class]` based bindings
are directly applied to an element's style and className attributes.

This patch optimizes the algorithm so that it...
- Doesn't construct an update an instance of `StylingMapArray` for
  `[style]` and `[class]` bindings
- Doesn't apply `[style]` and `[class]` based entries using
  `classList` and `style` (direct attributes are used instead)
- Doesn't split or iterate over all string-based tokens in a
  string value obtained from a `[class]` binding.

This patch speeds up the following cases:
- `<div [class]>` and `<div class="..." [class]>`
- `<div [style]>` and `<div style="..." [style]>`

The overall speec increase is by over 5x.

PR Close #33336
2019-10-24 17:42:46 -07:00
JoostK 0d9be22023 feat(ivy): strictness flags for template type checking (#33365)
The template type checking abilities of the Ivy compiler are far more
advanced than the level of template type checking that was previously
done for Angular templates. Up until now, a single compiler option
called "fullTemplateTypeCheck" was available to configure the level
of template type checking. However, now that more advanced type checking
is being done, new errors may surface that were previously not reported,
in which case it may not be feasible to fix all new errors at once.

Having only a single option to disable a large number of template type
checking capabilities does not allow for incrementally addressing newly
reported types of errors. As a solution, this commit introduces some new
compiler options to be able to enable/disable certain kinds of template
type checks on a fine-grained basis.

PR Close #33365
2019-10-24 16:16:14 -07:00
Alex Rickabaugh 113411c9b0 fix(ivy): split checkTypeOfReferences into DOM and non-DOM flags. (#33365)
View Engine correctly infers the type of local refs to directives or to
<ng-template>s, just not to DOM nodes. This commit splits the
checkTypeOfReferences flag into two separate halves, allowing the compiler
to align with this behavior.

PR Close #33365
2019-10-24 16:16:14 -07:00
JoostK d8ce2129d5 feat(ivy): add flag to disable checking of text attributes (#33365)
For elements that have a text attribute, it may happen that the element
is matched by a directive that consumes the attribute as an input. In
that case, the template type checker will validate the correctness of
the attribute with respect to the directive's declared type of the
input, which would typically be `boolean` for the `disabled` input.
Since empty attributes are assigned the empty string at runtime, the
template type checker would report an error for this template.

This commit introduces a strictness flag to help alleviate this
particular situation, effectively ignoring text attributes that happen
to be consumed by a directive.

PR Close #33365
2019-10-24 16:16:14 -07:00
JoostK 4aa51b751b feat(ivy): verify whether TypeScript version is supported (#33377)
During the creation of an Angular program in the compiler, a check is
done to verify whether the version of TypeScript is considered
supported, producing an error if it is not. This check was missing in
the Ivy compiler, so users may have ended up running an unsupported
TypeScript version inadvertently.

Resolves FW-1643

PR Close #33377
2019-10-24 15:46:23 -07:00
JoostK a42057d0f8 fix(ivy): support abstract directives in template type checking (#33131)
Recently it was made possible to have a directive without selector,
which are referred to as abstract directives. Such directives should not
be registered in an NgModule, but can still contain decorators for
inputs, outputs, queries, etc. The information from these decorators and
the `@Directive()` decorator itself needs to be registered with the
central `MetadataRegistry` so that other areas of the compiler can
request information about a given directive, an example of which is the
template type checker that needs to know about the inputs and outputs of
directives.

Prior to this change, however, abstract directives would only register
themselves with the `MetadataRegistry` as being an abstract directive,
without all of its other metadata like inputs and outputs. This meant
that the template type checker was unable to resolve the inputs and
outputs of these abstract directives, therefore failing to check them
correctly. The typical error would be that some property does not exist
on a DOM element, whereas said property should have been bound to the
abstract directive's input.

This commit fixes the problem by always registering the metadata of a
directive or component with the `MetadataRegistry`. Tests have been
added to ensure abstract directives are handled correctly in the
template type checker, together with tests to verify the form of
abstract directives in declaration files.

Fixes #30080

PR Close #33131
2019-10-24 12:44:30 -07:00
Alex Rickabaugh 63f0ded5cf fix(ivy): fix broken typechecking test on Windows (#33376)
One of the template type-checking tests relies on the newline character,
which is different on Windows. This commit fixes the issue.

PR Close #33376
2019-10-24 11:13:01 -07:00
Alex Rickabaugh f1269d98dc feat(ivy): input type coercion for template type-checking (#33243)
Often the types of an `@Input`'s field don't fully reflect the types of
assignable values. This can happen when an input has a getter/setter pair
where the getter always returns a narrow type, and the setter coerces a
wider value down to the narrow type.

For example, you could imagine an input of the form:

```typescript
@Input() get value(): string {
  return this._value;
}

set value(v: {toString(): string}) {
  this._value = v.toString();
}
```

Here, the getter always returns a `string`, but the setter accepts any value
that can be `toString()`'d, and coerces it to a string.

Unfortunately TypeScript does not actually support this syntax, and so
Angular users are forced to type their setters as narrowly as the getters,
even though at runtime the coercion works just fine.

To support these kinds of patterns (e.g. as used by Material), this commit
adds a compiler feature called "input coercion". When a binding is made to
the 'value' input of a directive like MatInput, the compiler will look for a
static field with the name ngAcceptInputType_value. If such a field is found
the type-checking expression for the input will use the static field's type
instead of the type for the @Input field,allowing for the expression of a
type conversion between the binding expression and the value being written
to the input's field.

To solve the case above, for example, MatInput might write:

```typescript
class MatInput {
  // rest of the directive...

  static ngAcceptInputType_value: {toString(): string};
}
```

FW-1475 #resolve

PR Close #33243
2019-10-24 09:49:38 -07:00
JoostK e2211ed211 fix(ivy): handle method calls of local variables in template type checker (#33132)
Prior to this change, a method call of a local template variable would
incorrectly be considered a call to a method on the component class.
For example, this pattern would produce an error:

```
<ng-template let-method>{{ method(1) }}</ng-template>
```

Here, the method call should be targeting the `$implicit` variable on
the template context, not the component class. This commit corrects the
behavior by first resolving methods in the template before falling back
on the component class.

Fixes #32900

PR Close #33132
2019-10-23 13:33:15 -07:00
Alex Rickabaugh 77240e1b60 fix(ivy): align VE + Ivy #ref types in fullTemplateTypeCheck: false (#33261)
In View Engine, with fullTemplateTypeCheck mode disabled, the type of any
inferred based on the entity being referenced. This is a bug, since the
goal with fullTemplateTypeCheck: false is for Ivy and VE to be aligned in
terms of type inference.

This commit adds a 'checkTypeOfReference' flag in the TypeCheckingConfig
to control this inference, and sets it to false when fullTemplateTypeCheck
is disabled.

PR Close #33261
2019-10-23 13:02:32 -07:00
Paul Gschwendtner 355e54a410 fix(compiler): do not throw when using abstract directive from other compilation unit (#33347)
Libraries can expose directive/component base classes that will be
used by consumer applications. Using such a base class from another
compilation unit works fine with "ngtsc", but when using "ngc", the
compiler will thrown an error saying that the base class is not
part of a NgModule. e.g.

```
Cannot determine the module for class X in Y! Add X to the NgModule to fix it.
```

This seems to be because the logic for distinguishing directives from
abstract directives is scoped to the current compilation unit within
ngc. This causes abstract directives from other compilation units to
be considered as actual directives (causing the exception).

PR Close #33347
2019-10-23 11:59:24 -07:00
Pete Bacon Darwin 5d86e4a9b1 fix(compiler): ensure that legacy ids are rendered for ICUs (#33318)
When computing i18n messages for templates there are two passes.
This is because messages must be computed before any whitespace
is removed. Then on a second pass, the messages must be recreated
but reusing the message ids from the first pass.

Previously ICUs were losing their legacy ids that had been computed
via the first pass. This commit fixes that by keeping track of the
message from the first pass (`previousMessage`) for ICU placeholder
nodes.

// FW-1637

PR Close #33318
2019-10-22 13:30:16 -04:00
Alex Rickabaugh e030375d9a feat(ngcc): enable private NgModule re-exports in ngcc on request (#33177)
This commit adapts the private NgModule re-export system (using aliasing) to
ngcc. Not all ngcc compilations are compatible with these re-exports, as
they assume a 1:1 correspondence between .js and .d.ts files. The primary
concern here is supporting them for commonjs-only packages.

PR Close #33177
2019-10-22 13:14:31 -04:00
Alex Rickabaugh c4733c15c0 feat(ivy): enable re-export of the compilation scope of NgModules privately (#33177)
This commit refactors the aliasing system to support multiple different
AliasingHost implementations, which control specific aliasing behavior
in ngtsc (see the README.md).

A new host is introduced, the `PrivateExportAliasingHost`. This solves a
longstanding problem in ngtsc regarding support for "monorepo" style private
libraries. These are libraries which are compiled separately from the main
application, and depended upon through TypeScript path mappings. Such
libraries are frequently not in the Angular Package Format and do not have
entrypoints, but rather make use of deep import style module specifiers.
This can cause issues with ngtsc's ability to import a directive given the
module specifier of its NgModule.

For example, if the application uses a directive `Foo` from such a library
`foo`, the user might write:

```typescript
import {FooModule} from 'foo/module';
```

In this case, foo/module.d.ts is path-mapped into the program. Ordinarily
the compiler would see this as an absolute module specifier, and assume that
the `Foo` directive can be imported from the same specifier. For such non-
APF libraries, this assumption fails. Really `Foo` should be imported from
the file which declares it, but there are two problems with this:

1. The compiler would have to reverse the path mapping in order to determine
   a path-mapped path to the file (maybe foo/dir.d.ts).
2. There is no guarantee that the file containing the directive is path-
   mapped in the program at all.

The compiler would effectively have to "guess" 'foo/dir' as a module
specifier, which may or may not be accurate depending on how the library and
path mapping are set up.

It's strongly desirable that the compiler not break its current invariant
that the module specifier given by the user for the NgModule is always the
module specifier from which directives/pipes are imported. Thus, for any
given NgModule from a particular module specifier, it must always be
possible to import any directives/pipes from the same specifier, no matter
how it's packaged.

To make this possible, when compiling a file containing an NgModule, ngtsc
will automatically add re-exports for any directives/pipes not yet exported
by the user, with a name of the form: ɵngExportɵModuleNameɵDirectiveName

This has several effects:

1. It guarantees anyone depending on the NgModule will be able to import its
   directives/pipes from the same specifier.
2. It maintains a stable name for the exported symbol that is safe to depend
   on from code on NPM. Effectively, this private exported name will be a
   part of the package's .d.ts API, and cannot be changed in a non-breaking
   fashion.

Fixes #29361
FW-1610 #resolve

PR Close #33177
2019-10-22 13:14:31 -04:00
Matias Niemelä c0ebecf54d revert: feat(ivy): input type coercion for template type-checking (#33243) (#33299)
This reverts commit 1b4eaea6d4.

PR Close #33299
2019-10-21 12:00:24 -04:00
George Kalpakas d7dc6cbc04 refactor(compiler-cli): remove unused method `FileSystem#mkdir()` (#33237)
Previously, the `FileSystem` abstraction featured a `mkdir()` method. In
`NodeJSFileSystem` (the default `FileSystem` implementation used in
actual code), the method behaved similar to Node.js' `fs.mkdirSync()`
(i.e. failing if any parent directory is missing or the directory exists
already). In contrast, `MockFileSystem` (which is the basis or mock
`FileSystem` implementations used in tests) implemented `mkdir()` as an
alias to `ensureDir()`, which behaved more like Node.js'
`fs.mkdirSync()` with the `recursive` option set to `true` (i.e.
creating any missing parent directories and succeeding if the directory
exists already).

This commit fixes this inconsistency by removing the `mkdir()` method,
which was not used anyway and only keeping `ensureDir()` (which is
consistent across our different `FileSystem` implementations).

PR Close #33237
2019-10-21 11:26:57 -04:00
George Kalpakas 8017229292 fix(ngcc): do not fail when multiple workers try to create the same directory (#33237)
When `ngcc` is running in parallel mode (usually when run from the
command line) and the `createNewEntryPointFormats` option is set to true
(e.g. via the `--create-ivy-entry-points` command line option), it can
happen that two workers end up trying to create the same directory at
the same time. This can lead to a race condition, where both check for
the directory existence, see that the directory does not exist and both
try to create it, with the second failing due the directory's having
already been created by the first one. Note that this only affects
directories and not files, because `ngcc` tasks operate on different
sets of files.

This commit avoids this race condition by allowing `FileSystem`'s
`ensureDir()` method to not fail if one of the directories it is trying
to create already exists (and is indeed a directory). This is fine for
the `ensureDir()` method, since it's purpose is to ensure that the
specified directory exists. So, even if the `mkdir()` call failed
(because the directory exists), `ensureDir()` has still completed its
mission.

Related discussion: https://github.com/angular/angular/pull/33049#issuecomment-540485703
FW-1635 #resolve

PR Close #33237
2019-10-21 11:26:57 -04:00
Alex Rickabaugh 1b4eaea6d4 feat(ivy): input type coercion for template type-checking (#33243)
Often the types of an `@Input`'s field don't fully reflect the types of
assignable values. This can happen when an input has a getter/setter pair
where the getter always returns a narrow type, and the setter coerces a
wider value down to the narrow type.

For example, you could imagine an input of the form:

```typescript
@Input() get value(): string {
  return this._value;
}

set value(v: {toString(): string}) {
  this._value = v.toString();
}
```

Here, the getter always returns a `string`, but the setter accepts any value
that can be `toString()`'d, and coerces it to a string.

Unfortunately TypeScript does not actually support this syntax, and so
Angular users are forced to type their setters as narrowly as the getters,
even though at runtime the coercion works just fine.

To support these kinds of patterns (e.g. as used by Material), this commit
adds a compiler feature called "input coercion". When a binding is made to
the 'value' input of a directive like MatInput, the compiler will look for a
static function with the name ngCoerceInput_value. If such a function is
found, the type-checking expression for the input will be wrapped in a call
to the function, allowing for the expression of a type conversion between
the binding expression and the value being written to the input's field.

To solve the case above, for example, MatInput might write:

```typescript
class MatInput {
  // rest of the directive...

  static ngCoerceInput_value(value: {toString(): string}): string {
    return null!;
  }
}
```

FW-1475 #resolve

PR Close #33243
2019-10-21 11:25:07 -04:00
Alex Rickabaugh d4db746898 feat(ivy): give shim generation its own compiler options (#33256)
As a hack to get the Ivy compiler ngtsc off the ground, the existing
'allowEmptyCodegenFiles' option was used to control generation of ngfactory
and ngsummary shims during compilation. This option was selected since it's
enabled in google3 but never enabled in external projects.

As ngtsc is now mature and the role shims play in compilation is now better
understood across the ecosystem, this commit introduces two new compiler
options to control shim generation:

* generateNgFactoryShims controls the generation of .ngfactory shims.
* generateNgSummaryShims controls the generation of .ngsummary shims.

The 'allowEmptyCodegenFiles' option is still honored if either of the above
flags are not set explicitly.

PR Close #33256
2019-10-21 11:24:26 -04:00
crisbeto 0e08ad628a fix(ivy): throw better error for missing generic type in ModuleWithProviders (#33187)
Currently if a `ModuleWithProviders` is missng its generic type, we throw a cryptic error like:

```
error TS-991010: Value at position 3 in the NgModule.imports of TodosModule is not a reference: [object Object]
```

These changes add a better error to make it easier to debug.

PR Close #33187
2019-10-18 14:49:54 -04:00
JoostK 6958d11d95 feat(ivy): type checking of event bindings (#33125)
Until now, the template type checker has not checked any of the event
bindings that could be present on an element, for example

```
<my-cmp
  (changed)="handleChange($event)"
  (click)="handleClick($event)"></my-cmp>
```

has two event bindings: the `change` event corresponding with an
`@Output()` on the `my-cmp` component and the `click` DOM event.

This commit adds functionality to the template type checker in order to
type check both kind of event bindings. This means that the correctness
of the bindings expressions, as well as the type of the `$event`
variable will now be taken into account during template type checking.

Resolves FW-1598

PR Close #33125
2019-10-18 14:41:53 -04:00
Pete Bacon Darwin bfd07b3c94 fix(ngcc): Esm5ReflectionHost.getDeclarationOfIdentifier should handle aliased inner declarations (#33252)
In ES5 modules, the class declarations consist of an IIFE with inner
and outer declarations that represent the class. The `EsmReflectionHost`
has logic to ensure that `getDeclarationOfIdentifier()` always returns the
outer declaration.

Before this commit, if an identifier referred to an alias of the inner
declaration, then `getDeclarationOfIdentifier()` was failing to find
the outer declaration - instead returning the inner declaration.

Now the identifier is correctly resolved up to the outer declaration
as expected.

This should fix some of the failing 3rd party packages discussed in
https://github.com/angular/ngcc-validation/issues/57.

PR Close #33252
2019-10-18 14:41:25 -04:00
Igor Minar 86e1e6c082 feat: typescript 3.6 support (#32946)
BREAKING CHANGE: typescript 3.4 and 3.5 are no longer supported, please update to typescript 3.6

Fixes #32380

PR Close #32946
2019-10-18 13:15:16 -04:00
Alex Rickabaugh de445709d4 fix(ivy): use ReflectionHost to check exports when writing an import (#33192)
This commit fixes ngtsc's import generator to use the ReflectionHost when
looking through the exports of an ES module to find the export of a
particular declaration that's being imported. This is necessary because
some module formats like CommonJS have unusual export mechanics, and the
normal TypeScript ts.TypeChecker does not understand them.

This fixes an issue with ngcc + CommonJS where exports were not being
enumerated correctly.

FW-1630 #resolve

PR Close #33192
2019-10-17 19:43:39 -04:00
Alex Rickabaugh 50710838bf fix(ngcc): better detection of end of decorator expression (#33192)
for removal of decorator from __decorate calls.

FW-1629 #resolve

PR Close #33192
2019-10-17 19:43:39 -04:00
Alex Rickabaugh 4da2dda647 feat(ngcc): support ignoreMissingDependencies in ngcc config (#33192)
Normally, when ngcc encounters a package with missing dependencies while
attempting to determine a compilation ordering, it will ignore that package.
This commit adds a configuration for a flag to tell ngcc to compile the
package anyway, regardless of any missing dependencies.

FW-1931 #resolve

PR Close #33192
2019-10-17 19:43:39 -04:00
Alex Rickabaugh afcff73be3 fix(ngcc): report the correct viaModule when reflecting over commonjs (#33192)
In the ReflectionHost API, a 'viaModule' indicates that a particular value
originated in another absolute module. It should always be 'null' for values
originating in relatively-imported modules.

This commit fixes a bug in the CommonJsReflectionHost where viaModule would
be reported even for relatively-imported values, which causes invalid import
statements to be generated during compilation.

A test is added to verify the correct behavior.

FW-1628 #resolve

PR Close #33192
2019-10-17 19:43:39 -04:00
Alex Rickabaugh 2196114501 feat(ngcc): support --async flag (defaults to true) (#33192)
This allows disabling parallelism in ngcc if desired, which is mainly useful
for debugging. The implementation creates the flag and passes its value to
mainNgcc.

No tests are added since the feature mainly exists already - ngcc supports
both parallel and serial execution. This commit only allows switching the
flag via the commandline.

PR Close #33192
2019-10-17 19:43:39 -04:00
Alex Eagle 422eb14dc0 build: remove vendored Babel typings (#33226)
These were getting included in the @angular/localize package.
Instead, patch the upstream files to work with TS typeRoots option

See bazelbuild/rules_nodejs#1033

PR Close #33226
2019-10-17 18:45:52 -04:00
crisbeto 9d54679e66 test: clean up explicit dynamic query usages (#33015)
Cleans up all the places where we explicitly set `static: false` on queries.

PR Close #33015
2019-10-17 16:10:10 -04:00
Andrew Kushnir 7e64bbe5a8 fix(ivy): use container i18n meta if a message is a single ICU (#33191)
Prior to this commit, metadata defined on ICU container element was not inherited by the ICU if the whole message is a single ICU (for example: `<ng-container i18n="meaning|description@@id">{count, select, ...}</ng-container>). This commit updates the logic to use parent container i18n meta information for the cases when a message consists of a single ICU.

Fixes #33171

PR Close #33191
2019-10-17 16:07:07 -04:00
Kara Erickson 1a8bd22fa3 refactor(core): rename ngLocaleIdDef to ɵloc (#33212)
LocaleID defs are not considered public API, so the property
that contains them should be prefixed with Angular's marker
for "private" ('ɵ') to discourage apps from relying on def
APIs directly.

This commit adds the prefix and shortens the name from
ngLocaleIdDef to loc. This is because property names
cannot be minified by Uglify without turning on property
mangling (which most apps have turned off) and are thus
size-sensitive.

PR Close #33212
2019-10-17 16:06:16 -04:00
George Kalpakas 78214e72ea fix(ngcc): avoid warning when reflecting on index signature member (#33198)
Previously, when `ngcc` was reflecting on class members it did not
account for the fact that a member could be of the kind
`IndexSignature`. This can happen, for example, on abstract classes (as
is the case for [JsonCallbackContext][1]).

Trying to reflect on such members (and failing to recognize their kind),
resulted in warnings, such as:
```
Warning: Unknown member type: "[key: string]: (data: any) => void;
```

While these warnings are harmless, they can be confusing and worrisome
for users.

This commit avoids such warnings by detecting class members of the
`IndexSignature` kind and ignoring them.

[1]: https://github.com/angular/angular/blob/4659cc26e/packages/common/http/src/jsonp.ts#L39

PR Close #33198
2019-10-17 16:05:48 -04:00
JoostK 08cb2fa80f fix(ivy): ignore non-property bindings to inputs in template type checker (#33130)
Prior to this change, the template type checker would incorrectly bind
non-property bindings such as `[class.strong]`, `[style.color]` and
`[attr.enabled]` to directive inputs of the same name. This is
undesirable, as those bindings are never actually bound to the inputs at
runtime.

Fixes #32099
Fixes #32496
Resolves FW-1596

PR Close #33130
2019-10-17 14:15:36 -04:00
Kara Erickson 86104b82b8 refactor(core): rename ngInjectableDef to ɵprov (#33151)
Injectable defs are not considered public API, so the property
that contains them should be prefixed with Angular's marker
for "private" ('ɵ') to discourage apps from relying on def
APIs directly.

This commit adds the prefix and shortens the name from
ngInjectableDef to "prov" (for "provider", since injector defs
are known as "inj"). This is because property names cannot
be minified by Uglify without turning on property mangling
(which most apps have turned off) and are thus size-sensitive.

PR Close #33151
2019-10-16 16:36:19 -04:00
Kara Erickson cda9248b33 refactor(core): rename ngInjectorDef to ɵinj (#33151)
Injector defs are not considered public API, so the property
that contains them should be prefixed with Angular's marker
for "private" ('ɵ') to discourage apps from relying on def
APIs directly.

This commit adds the prefix and shortens the name from
ngInjectorDef to inj. This is because property names
cannot be minified by Uglify without turning on property
mangling (which most apps have turned off) and are thus
size-sensitive.

PR Close #33151
2019-10-16 16:36:19 -04:00
Gabriel Medeiros Coelho 4659cc26ea style: emove unreachable 'return null' statement (#33174)
There's another return statement before this one, therefore 'return null' will never be reached.

PR Close #33174
2019-10-16 10:58:38 -04:00
Pete Bacon Darwin ad72c90447 fix(ivy): i18n - add XLIFF aliases for legacy message id support (#33160)
The `legacyMessageIdFormat` is taken from the `i18nInFormat` property but we were only considering
`xmb`, `xlf` and `xlf2` values.

The CLI also supports `xliff` and `xliff2` values for the
`i18nInFormat`.

This commit adds support for those aliases.

PR Close #33160
2019-10-15 21:04:17 +00:00
Kara Erickson fc93dafab1 refactor(core): rename ngModuleDef to ɵmod (#33142)
Module defs are not considered public API, so the property
that contains them should be prefixed with Angular's marker
for "private" ('ɵ') to discourage apps from relying on def
APIs directly.

This commit adds the prefix and shortens the name from
ngModuleDef to mod. This is because property names
cannot be minified by Uglify without turning on property
mangling (which most apps have turned off) and are thus
size-sensitive.

PR Close #33142
2019-10-14 23:08:10 +00:00
Kara Erickson d62eff7316 refactor(core): rename ngPipeDef to ɵpipe (#33142)
Pipe defs are not considered public API, so the property
that contains them should be prefixed with Angular's marker
for "private" ('ɵ') to discourage apps from relying on def
APIs directly.

This commit adds the prefix and shortens the name from
ngPipeDef to pipe. This is because property names
cannot be minified by Uglify without turning on property
mangling (which most apps have turned off) and are thus
size-sensitive.

PR Close #33142
2019-10-14 23:08:10 +00:00
Kara Erickson 0de2a5e408 refactor(core): rename ngFactoryDef to ɵfac (#33116)
Factory defs are not considered public API, so the property
that contains them should be prefixed with Angular's marker
for "private" ('ɵ') to discourage apps from relying on def
APIs directly.

This commit adds the prefix and shortens the name from
ngFactoryDef to fac. This is because property names
cannot be minified by Uglify without turning on property
mangling (which most apps have turned off) and are thus
size-sensitive.

Note that the other "defs" (ngPipeDef, etc) will be
prefixed and shortened in follow-up PRs, in an attempt to
limit how large and conflict-y this change is.

PR Close #33116
2019-10-14 20:27:25 +00:00