Commit Graph

1770 Commits

Author SHA1 Message Date
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
JoostK cd7b199219 feat(ivy): check regular attributes that correspond with directive inputs (#33066)
Prior to this change, a static attribute that corresponds with a
directive's input would not be type-checked against the type of the
input. This is unfortunate, as a static value always has type `string`,
whereas the directive's input type might be something different. This
typically occurs when a developer forgets to enclose the attribute name
in brackets to make it a property binding.

This commit lets static attributes be considered as bindings with string
values, so that they will be properly type-checked.

PR Close #33066
2019-10-14 20:25:20 +00:00
JoostK ece0b2d7ce feat(ivy): disable strict null checks for input bindings (#33066)
This commit introduces an internal config option of the template type
checker that allows to disable strict null checks of input bindings to
directives. This may be particularly useful when a directive is from a
library that is not compiled with `strictNullChecks` enabled.

Right now, strict null checks are enabled when  `fullTemplateTypeCheck`
is turned on, and disabled when it's off. In the near future, several of
the internal configuration options will be added as public Angular
compiler options so that users can have fine-grained control over which
areas of the template type checker to enable, allowing for a more
incremental migration strategy.

PR Close #33066
2019-10-14 20:25:20 +00:00
JoostK 50bf17aca0 fix(ivy): do not always accept `undefined` for directive inputs (#33066)
Prior to this change, the template type checker would always allow a
value of type `undefined` to be passed into a directive's inputs, even
if the input's type did not allow for it. This was due to how the type
constructor for a directive was generated, where a `Partial` mapped
type was used to allow for inputs to be unset. This essentially
introduces the `undefined` type as acceptable type for all inputs.

This commit removes the `Partial` type from the type constructor, which
means that we can no longer omit any properties that were unset.
Instead, any properties that are not set will still be included in the
type constructor call, having their value assigned to `any`.

Before:

```typescript
class NgForOf<T> {
  static ngTypeCtor<T>(init: Partial<Pick<NgForOf<T>,
    'ngForOf'|'ngForTrackBy'|'ngForTemplate'>>): NgForOf<T>;
}

NgForOf.ngTypeCtor(init: {ngForOf: ['foo', 'bar']});
```

After:

```typescript
class NgForOf<T> {
  static ngTypeCtor<T>(init: Pick<NgForOf<T>,
    'ngForOf'|'ngForTrackBy'|'ngForTemplate'>): NgForOf<T>;
}

NgForOf.ngTypeCtor(init: {
  ngForOf: ['foo', 'bar'],
  ngForTrackBy: null as any,
  ngForTemplate: null as any,
});
```

This change only affects generated type check code, the generated
runtime code is not affected.

Fixes #32690
Resolves FW-1606

PR Close #33066
2019-10-14 20:25:20 +00:00
Andrius 39587ad127 fix(compiler-cli): resolve type of exported *ngIf variable. (#33016)
Currently, method `getVarDeclarations()` does not try to resolve the type of
exported variable from *ngIf directive. It always returns `any` type.
By resolving the real type of exported variable, it is now possible to use this
type information in language service and provide completions, go to definition
and quick info functionality in expressions that use exported variable.
Also language service will provide more accurate diagnostic errors during
development.

PR Close #33016
2019-10-14 20:24:43 +00:00
Ayaz Hafiz b04488d692 feat(compiler): record absolute span of template expressions in parser (#31897)
Currently, the spans of expressions are recorded only relative to the
template node that they reside in, not their source file.

Introduce a `sourceSpan` property on expression ASTs that records the
location of an expression relative to the entire source code file that
it is in. This may allow for reducing duplication of effort in
ngtsc/typecheck/src/diagnostics later on as well.

Child of #31898

PR Close #31897
2019-10-14 20:14:16 +00:00
Alan Agius e2d5bc2514 feat: change tslib from direct dependency to peerDependency (#32167)
BREAKING CHANGE:

We no longer directly have a direct depedency on `tslib`. Instead it is now listed a `peerDependency`.

Users not using the CLI will need to manually install `tslib` via;
```
yarn add tslib
```
or
```
npm install tslib --save
```

PR Close #32167
2019-10-14 16:34:47 +00:00
George Kalpakas 25af147a8c refactor(ngcc): fix formatting of missing dependencies error (#33139)
Previously, the list of missing dependencies was not explicitly joined,
which resulted in the default `,` joiner being used during
stringification.

This commit explicitly joins the missing dependency lines to avoid
unnecessary commas.

Before:
```
The target entry-point "some-entry-point" has missing dependencies:
 - dependency 1
, - dependency 2
, - dependency 3
```

After:
```
The target entry-point "some-entry-point" has missing dependencies:
 - dependency 1
 - dependency 2
 - dependency 3
```

PR Close #33139
2019-10-14 16:30:39 +00:00
George Kalpakas 1a34fbce25 fix(ngcc): rename the executable from `ivy-ngcc` to `ngcc` (#33140)
Previously, the executable for the Angular Compatibility Compiler
(`ngcc`) was called `ivy-ngcc`. This would be confusing for users not
familiar with our internal terminology, especially given that we call it
`ngcc` in all our docs and presentations.

This commit renames the executable to `ngcc` and replaces `ivy-ngcc`
with a script that errors with an informative message (prompting the
user to use `ngcc` instead).

Jira issue: [FW-1624](https://angular-team.atlassian.net/browse/FW-1624)

PR Close #33140
2019-10-14 16:29:14 +00:00
Kara Erickson 1a67d70bf8 refactor(core): rename ngDirectiveDef to ɵdir (#33110)
Directive 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
ngDirectiveDef to dir. 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" (ngFactoryDef, 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 #33110
2019-10-14 16:20:11 +00:00
JoostK d8249d1230 feat(ivy): better error messages for unknown components (#33064)
For elements in a template that look like custom elements, i.e.
containing a dash in their name, the template type checker will now
issue an error with instructions on how the resolve the issue.
Additionally, a property binding to a non-existent property will also
produce a more descriptive error message.

Resolves FW-1597

PR Close #33064
2019-10-14 16:19:13 +00:00
Kara Erickson 64fd0d6db9 refactor(core): rename ngComponentDef to ɵcmp (#33088)
Component 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
`ngComponentDef` to `cmp`. 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" (ngDirectiveDef, 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 #33088
2019-10-11 15:45:22 -07:00
Andrius 2ddc851090 fix(compiler-cli): produce diagnostic messages in expression of PrefixNot node. (#33087)
PR Close #33087
2019-10-10 15:25:46 -07:00
Danny Skoog 6ab5f3648a refactor: utilize type narrowing (#33075)
PR Close #33075
2019-10-10 15:18:44 -07:00
Pete Bacon Darwin 90007e97ca feat(ngcc): support version ranges in project/default configurations (#33008)
By appending a version range to the package name, it is now possible to
target configuration to specific versions of a package.

PR Close #33008
2019-10-10 13:59:57 -07:00
Pete Bacon Darwin 916762440c feat(ngcc): support fallback to a default configuration (#33008)
It is now possible to include a set of default ngcc configurations
that ship with ngcc out of the box. This allows ngcc to handle a
set of common packages, which are unlikely to be fixed, without
requiring the application developer to write their own configuration
for them.

Any packages that are configured at the package or project level
will override these default configurations. This allows a reasonable
level of control at the package and user level.

PR Close #33008
2019-10-10 13:59:57 -07:00
Pete Bacon Darwin f640a4a494 fix(ivy): i18n - turn on legacy message-id support by default (#33053)
For v9 we want the migration to the new i18n to be as
simple as possible.

Previously the developer had to positively choose to use
legacy messsage id support in the case that their translation
files had not been migrated to the new format by setting the
`legacyMessageIdFormat` option in tsconfig.json to the format
of their translation files.

Now this setting has been changed to `enableI18nLegacyMessageFormat`
as is a boolean that defaults to `true`. The format is then read from
the `i18nInFormat` option, which was previously used to trigger translations
in the pre-ivy angular compiler.

PR Close #33053
2019-10-10 13:58:30 -07:00
crisbeto d5b87d32b0 perf(ivy): move attributes array into component def (#32798)
Currently Ivy stores the element attributes into an array above the component def and passes it into the relevant instructions, however the problem is that upon minification the array will get a unique name which won't compress very well. These changes move the attributes array into the component def and pass in the index into the instructions instead.

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

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

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

A couple of cases that this PR doesn't handle:
* Template references are still in a separate array.
* i18n attributes are still in a separate array.

PR Close #32798
2019-10-09 13:16:55 -07:00
Pete Bacon Darwin b2b917d2d8 feat(ngcc): expose `--create-ivy-entry-points` option on ivy-ngcc (#33049)
This allows a postinstall hook to generate the same
output as the CLI integration does.

See https://github.com/angular/angular/pull/32999#issuecomment-539937368

PR Close #33049
2019-10-09 13:16:16 -07:00
Pete Bacon Darwin bcbf3e4123 feat(ivy): i18n - render legacy message ids in `$localize` if requested (#32937)
The `$localize` library uses a new message digest function for
computing message ids. This means that translations in legacy
translation files will no longer match the message ids in the code
and so will not be translated.

This commit adds the ability to specify the format of your legacy
translation files, so that the appropriate message id can be rendered
in the `$localize` tagged strings. This results in larger code size
and requires that all translations are in the legacy format.

Going forward the developer should migrate their translation files
to use the new message id format.

PR Close #32937
2019-10-03 12:12:55 -07:00
Martin Probst 5332b04f35 build: TypeScript 3.6 compatibility. (#32908)
This PR updates Angular to compile with TypeScript 3.6 while retaining
compatibility with TS3.5. We achieve this by inserting several `as any`
casts for compatiblity around `ts.CompilerHost` APIs.

PR Close #32908
2019-10-03 09:09:11 -07:00
Pete Bacon Darwin 9188751adc fix(ivy): i18n - do not render message ids unnecessarily (#32867)
In an attempt to be compatible with previous translation files
the Angular compiler was generating instructions that always
included the message id. This was because it was not possible
to accurately re-generate the id from the calls to `$localize()` alone.

In line with https://hackmd.io/EQF4_-atSXK4XWg8eAha2g this
commit changes the compiler so that it only renders ids if they are
"custom" ones provided by the template author.

NOTE:

When translating messages generated by the Angular compiler
from i18n tags in templates, the `$localize.translate()` function
will compute message ids, if no custom id is provided, using a
common digest function that only relies upon the information
available in the `$localize()` calls.

This computed message id will not be the same as the message
ids stored in legacy translation files. Such files will need to be
migrated to use the new common digest function.

This only affects developers who have been trialling `$localize`, have
been calling `loadTranslations()`, and are not exclusively using custom
ids in their templates.

PR Close #32867
2019-10-02 14:52:00 -07:00
Pete Bacon Darwin d24ade91b8 fix(ivy): i18n - support colons in $localize metadata (#32867)
Metadata blocks are delimited by colons. Previously the code naively just
looked for the next colon in the string as the end marker.

This commit supports escaping colons within the metadata content.
The Angular compiler has been updated to add escaping as required.

PR Close #32867
2019-10-02 14:52:00 -07:00
Pete Bacon Darwin 9b15588188 refactor(ivy): i18n - move marker block serialization to helpers (#32867)
Previously the metadata and placeholder blocks were serialized in
a variety of places. Moreover the code for creating the `LocalizedString`
AST node was doing serialization, which break the separation of concerns.

Now this is all done by the code that renders the AST and is refactored into
helper functions to avoid repeating the behaviour.

PR Close #32867
2019-10-02 14:52:00 -07:00
crisbeto 4e35e348af refactor(ivy): generate ngFactoryDef for injectables (#32433)
With #31953 we moved the factories for components, directives and pipes into a new field called `ngFactoryDef`, however I decided not to do it for injectables, because they needed some extra logic. These changes set up the `ngFactoryDef` for injectables as well.

For reference, the extra logic mentioned above is that for injectables we have two code paths:

1. For injectables that don't configure how they should be instantiated, we create a `factory` that proxies to `ngFactoryDef`:

```
// Source
@Injectable()
class Service {}

// Output
class Service {
  static ngInjectableDef = defineInjectable({
    factory: () => Service.ngFactoryFn(),
  });

  static ngFactoryFn: (t) => new (t || Service)();
}
```

2. For injectables that do configure how they're created, we keep the `ngFactoryDef` and generate the factory based on the metadata:

```
// Source
@Injectable({
  useValue: DEFAULT_IMPL,
})
class Service {}

// Output
export class Service {
  static ngInjectableDef = defineInjectable({
    factory: () => DEFAULT_IMPL,
  });

  static ngFactoryFn: (t) => new (t || Service)();
}
```

PR Close #32433
2019-10-02 13:04:26 -07:00
JoostK 747f0cff9e fix(ngcc): handle presence of both `ctorParameters` and `__decorate` (#32901)
Recently ng-packagr was updated to include a transform that used to be
done in tsickle (https://github.com/ng-packagr/ng-packagr/pull/1401),
where only constructor parameter decorators are emitted in tsickle's
format, not any of the other decorators.

ngcc used to extract decorators from only a single format, so once it
saw the `ctorParameters` static property it assumed the library is using
the tsickle format. Therefore, none of the `__decorate` calls were
considered. This resulted in missing decorator information, preventing
proper processing of a package.

This commit changes how decorators are extracted by always looking at
both the static properties and the `__decorate` calls, merging these
sources appropriately.

Resolves FW-1573

PR Close #32901
2019-09-30 14:11:45 -07:00
JoostK 002a97d852 fix(ngcc): ensure private exports are added for `ModuleWithProviders` (#32902)
ngcc may need to insert public exports into the bundle's source as well
as to the entry-point's declaration file, as the Ivy compiler may need
to create import statements to internal library types. The way ngcc
knows which exports to add is through the references registry, to which
references to things that require a public export are added by the
various analysis steps that are executed.

One of these analysis steps is the augmentation of declaration files
where functions that return `ModuleWithProviders` are updated so that a
generic type argument is added that corresponds with the `NgModule` that
is actually imported. This type has to be publicly exported, so the
analyzer step has to add the module type to the references registry.

A problem occurs when `ModuleWithProviders` already has a generic type
argument, in which case no update of the declaration file is necessary.
This may happen when 1) ngcc is processing additional bundle formats, so
that the declaration file has already been updated while processing the
first bundle format, or 2) when a package is processed which already
contains the generic type in its source. In both scenarios it may occur
that the referenced `NgModule` type does not yet have a public export,
so it is crucial that a reference to the type is added to the
references registry, which ngcc failed to do.

This commit fixes the issue by always adding the referenced `NgModule`
type to the references registry, so that a public export will always be
created if necessary.

Resolves FW-1575

PR Close #32902
2019-09-30 14:11:16 -07:00
Andrew Kushnir 966c2a326a fix(ivy): include `ngProjectAs` into attributes array (#32784)
Prior to this commit, the `ngProjectAs` attribute was only included with a special flag and in a parsed format. As a result, projected node was missing `ngProjectAs` attribute as well as other attributes added after `ngProjectAs` one. This is problematic since app code might rely on the presence of `ngProjectAs` attribute (for example in CSS). This commit fixes the problem by including `ngProjectAs` into attributes array as a regular attribute and also makes sure that the parsed version of the `ngProjectAs` attribute with a special marker is added after regular attributes (thus we set them correctly at runtime). This change also aligns View Engine and Ivy behavior.

PR Close #32784
2019-09-27 10:12:18 -07:00
Pete Bacon Darwin 0ea4875b10 fix(ngcc): make the build-marker error more clear (#32712)
The previous message was confusing as it could be
interpreted as only deleting the package mentioned.

Now we compute and display the actual node_modules
path to remove.

See https://github.com/angular/angular/issues/31354#issuecomment-532080537

PR Close #32712
2019-09-25 11:29:45 -07:00
Greg Magolan c1346462db build: update to nodejs rules 0.37.1 (#32151)
This release includes a ts_config runfiles fix so also cleaning up the one line work-around from #31943.

This also updates to upstream rules_webtesting browser repositories load("@io_bazel_rules_webtesting//web/versioned:browsers-0.3.2.bzl", "browser_repositories") to fix a breaking change in the chromedriver distro. This bumps up the version of chromium to the version here: https://github.com/bazelbuild/rules_webtesting/blob/master/web/versioned/browsers-0.3.2.bzl

PR Close #32151
2019-09-25 11:29:12 -07:00
Pete Bacon Darwin b741a1c3e7 fix(ivy): i18n - update the compiler to output `MessageId`s (#32594)
Now that the `$localize` translations are `MessageId` based the
compiler must render `MessageId`s in its generated `$localize` code.
This is because the `MessageId` used by the compiler is computed
from information that does not get passed through to the `$localize`
tagged string.

For example, the generated code for the following template

```html
<div id="static" i18n-title="m|d" title="introduction"></div>
```

will contain these localization statements

```ts
if (ngI18nClosureMode) {
  /**
    * @desc d
    * @meaning m
    */
  const MSG_EXTERNAL_8809028065680254561$$APP_SPEC_TS_1 = goog.getMsg("introduction");
  I18N_1 = MSG_EXTERNAL_8809028065680254561$$APP_SPEC_TS_1;
}
else {
  I18N_1 = $localize \`:m|d@@8809028065680254561:introduction\`;
}
```

Since `$localize` is not able to accurately regenerate the source-message
(and so the `MessageId`) from the generated code, it must rely upon the
`MessageId` being provided explicitly in the generated code.

The compiler now prepends all localized messages with a "metadata block"
containing the id (and the meaning and description if defined).

Note that this metadata block will also allow translation file extraction
from the compiled code - rather than relying on the legacy ViewEngine
extraction code. (This will be implemented post-v9).

Although these metadata blocks add to the initial code size, compile-time
inlining will completely remove these strings and so will not impact on
production bundle size.

PR Close #32594
2019-09-17 09:17:45 -07:00
Pete Bacon Darwin e5a3de575f fix(ngcc): support UMD global factory in comma lists (#32709)
Previously we were looking for a global factory call that looks like:

```ts
(factory((global.ng = global.ng || {}, global.ng.common = {}), global.ng.core))"
```

but in some cases it looks like:

```ts
(global = global || self, factory((global.ng = global.ng || {}, global.ng.common = {}), global.ng.core))"
```

Note the `global = global || self` at the start of the statement.

This commit makes the test when finding the global factory
function call resilient to being in a comma list.

PR Close #32709
2019-09-17 09:16:08 -07:00
Matias Niemelä 4f41473048 refactor(ivy): remove styling state storage and introduce direct style writing (#32591)
This patch is a final major refactor in styling Angular.

This PR includes three main fixes:

All temporary state taht is persisted between template style/class application
and style/class application in host bindings is now removed.
Removes the styling() and stylingApply() instructions.
Introduces a "direct apply" mode that is used apply prop-based
style/class in the event that there are no map-based bindings as
well as property collisions.

PR Close #32259

PR Close #32591
2019-09-16 14:12:48 -07:00
cran-cg f6d66671b6 fix(compiler-cli): fix typo in diagnostic template info. (#32684)
Fixes #32662

PR Close #32684
2019-09-16 08:59:48 -07:00
Andrew Kushnir 5328bb223a fix(ivy): avoid unnecessary i18n instructions generation for <ng-template> with structural directives (#32623)
If an <ng-template> contains a structural directive (for example *ngIf), Ngtsc generates extra template function with 1 template instruction call. When <ng-template> tag also contains i18n attribute on it, we generate i18nStart and i18nEnd instructions around it, which is unnecessary and breaking runtime. This commit adds a logic to make sure we do not generate i18n instructions in case only `template` is present.

PR Close #32623
2019-09-13 10:01:55 -07:00
JoostK 3c7da767d8 fix(ngcc): resolve imports in `.d.ts` files for UMD/CommonJS bundles (#32619)
In ngcc's reflection host for UMD and CommonJS bundles, custom logic is
present to resolve import details of an identifier. However, this custom
logic is unable to resolve an import for an identifier inside of
declaration files, as such files use the regular ESM import syntax.

As a consequence of this limitation, ngtsc is unable to resolve
`ModuleWithProviders` imports that are declared in an external library.
In that situation, ngtsc determines the type of the actual `NgModule`
that is imported, by looking in the library's declaration files for the
generic type argument on `ModuleWithProviders`. In this process, ngtsc
resolves the import for the `ModuleWithProviders` identifier to verify
that it is indeed the `ModuleWithProviders` type from `@angular/core`.
So, when the UMD reflection host was in use this resolution would fail,
therefore no `NgModule` type could be detected.

This commit fixes the bug by using the regular import resolution logic
in addition to the custom resolution logic that is required for UMD
and CommonJS bundles.

Fixes #31791

PR Close #32619
2019-09-12 13:18:20 -07:00
JoostK c4e039a43a fix(ngcc): correctly read static properties for aliased classes (#32619)
In ESM2015 bundles, a class with decorators may be emitted as follows:

```javascript
var MyClass_1;
let MyClass = MyClass_1 = class MyClass {};
MyClass.decorators = [/* here be decorators */];
```

Such a class has two declarations: the publicly visible `let MyClass`
and the implementation `class MyClass {}` node. In #32539 a refactoring
took place to handle such classes more consistently, however the logic
to find static properties was mistakenly kept identical to its broken
state before the refactor, by looking for static properties on the
implementation symbol (the one for `class MyClass {}`) whereas the
static properties need to be obtained from the symbol corresponding with
the `let MyClass` declaration, as that is where the `decorators`
property is assigned to in the example above.

This commit fixes the behavior by looking for static properties on the
public declaration symbol. This fixes an issue where decorators were not
found for classes that do in fact have decorators, therefore preventing
the classes from being compiled for Ivy.

Fixes #31791

PR Close #32619
2019-09-12 13:18:20 -07:00
JoostK 373e1337de fix(ngcc): consistently use outer declaration for classes (#32539)
In ngcc's reflection hosts for compiled JS bundles, such as ESM2015,
special care needs to be taken for classes as there may be an outer
declaration (referred to as "declaration") and an inner declaration
(referred to as "implementation") for a given class. Therefore, there
will also be two `ts.Symbol`s bound per class, and ngcc needs to switch
between those declarations and symbols depending on where certain
information can be found.

Prior to this commit, the `NgccReflectionHost` interface had methods
`getClassSymbol` and `findClassSymbols` that would return a `ts.Symbol`.
These class symbols would be used to kick off compilation of components
using ngtsc, so it is important for these symbols to correspond with the
publicly visible outer declaration of the class. However, the ESM2015
reflection host used to return the `ts.Symbol` for the inner
declaration, if the class was declared as follows:

```javascript
var MyClass = class MyClass {};
```

For the above code, `Esm2015ReflectionHost.getClassSymbol` would return
the `ts.Symbol` corresponding with the `class MyClass {}` declaration,
whereas it should have corresponded with the `var MyClass` declaration.
As a consequence, no `NgModule` could be resolved for the component, so
no components/directives would be in scope for the component. This
resulted in errors during runtime.

This commit resolves the issue by introducing a `NgccClassSymbol` that
contains references to both the outer and inner `ts.Symbol`, instead of
just a single `ts.Symbol`. This avoids the unclarity of whether a
`ts.Symbol` corresponds with the outer or inner declaration.

More details can be found here: https://hackmd.io/7nkgWOFWQlSRAuIW_8KPPw

Fixes #32078
Closes FW-1507

PR Close #32539
2019-09-12 11:12:10 -07:00
JoostK 2279cb8dc0 refactor(ngcc): move `ClassSymbol` to become `NgccClassSymbol` (#32539)
PR Close #32539
2019-09-12 11:12:10 -07:00
Matias Niemelä 53dbff66d7 revert: refactor(ivy): remove styling state storage and introduce direct style writing (#32259)
This reverts commit 15aeab1620.
2019-09-11 15:24:10 -07:00
Matias Niemelä 15aeab1620 refactor(ivy): remove styling state storage and introduce direct style writing (#32259) (#32596)
This patch is a final major refactor in styling Angular.

This PR includes three main fixes:

All temporary state taht is persisted between template style/class application
and style/class application in host bindings is now removed.
Removes the styling() and stylingApply() instructions.
Introduces a "direct apply" mode that is used apply prop-based
style/class in the event that there are no map-based bindings as
well as property collisions.

PR Close #32259

PR Close #32596
2019-09-11 16:27:10 -04:00
Matias Niemelä c84c27f7f4 revert: refactor(ivy): remove styling state storage and introduce direct style writing (#32259) 2019-09-10 18:08:05 -04:00
Matias Niemelä 3b37469735 refactor(ivy): remove styling state storage and introduce direct style writing (#32259)
This patch is a final major refactor in styling Angular.

This PR includes three main fixes:

All temporary state taht is persisted between template style/class application
and style/class application in host bindings is now removed.
Removes the styling() and stylingApply() instructions.
Introduces a "direct apply" mode that is used apply prop-based
style/class in the event that there are no map-based bindings as
well as property collisions.

PR Close #32259
2019-09-10 15:54:58 -04:00
crisbeto 664e0015d4 perf(ivy): replace select instruction with advance (#32516)
Replaces the `select` instruction with a new one called `advance`. Instead of the jumping to a specific index, the new instruction goes forward X amount of elements. The advantage of doing this is that it should generate code the compresses better.

PR Close #32516
2019-09-10 06:30:28 -04:00
Pete Bacon Darwin ea6a2e9f25 fix(ivy): template compiler should render correct $localize placeholder names (#32509)
The `goog.getMsg()` function requires placeholder names to be camelCased.

This is not the case for `$localize`. Here placeholder names need
match what is serialized to translation files.

Specifically such placeholder names keep their casing but have all characters
that are not in `a-z`, `A-Z`, `0-9` and `_` converted to `_`.

PR Close #32509
2019-09-09 19:11:36 -04:00
Carlos Ortiz García 9166baf709 refactor(core): Migrate TestBed.get to TestBed.inject (#32382)
This is cleanup/followup for PR #32200

PR Close #32382
2019-09-09 19:10:54 -04:00
JoostK a64eded521 fix(ivy): capture template source mapping details during preanalysis (#32544)
Prior to this change, the template source mapping details were always
built during the analysis phase, under the assumption that pre-analysed
templates would always correspond with external templates. This has
turned out to be a false assumption, as inline templates are also
pre-analyzed to be able to preload any stylesheets included in the
template.

This commit fixes the bug by capturing the template source mapping
details at the moment the template is parsed, which is either during the
preanalysis phase when preloading is available, or during the analysis
phase when preloading is not supported.

Tests have been added to exercise the template error mapping in
asynchronous compilations where preloading is enabled, similar to how
the CLI performs compilations.

Fixes #32538

PR Close #32544
2019-09-09 19:10:34 -04:00
George Kalpakas c714330856 refactor(ngcc): add debug logging for the duration of different operations (#32427)
This gives an overview of how much time is spent in each operation/phase
and makes it easy to do rough comparisons of how different
configurations or changes affect performance.

PR Close #32427
2019-09-09 15:55:14 -04:00
George Kalpakas e36e6c85ef perf(ngcc): process tasks in parallel in async mode (#32427)
`ngcc` supports both synchronous and asynchronous execution. The default
mode when using `ngcc` programmatically (which is how `@angular/cli` is
using it) is synchronous. When running `ngcc` from the command line
(i.e. via the `ivy-ngcc` script), it runs in async mode.

Previously, the work would be executed in the same way in both modes.

This commit improves the performance of `ngcc` in async mode by
processing tasks in parallel on multiple processes. It uses the Node.js
built-in [`cluster` module](https://nodejs.org/api/cluster.html) to
launch a cluster of Node.js processes and take advantage of multi-core
systems.

Preliminary comparisons indicate a 1.8x to 2.6x speed improvement when
processing the angular.io app (apparently depending on the OS, number of
available cores, system load, etc.). Further investigation is needed to
better understand these numbers and identify potential areas of
improvement.

Inspired by/Based on @alxhub's prototype: alxhub/angular@cb631bdb1
Original design doc: https://hackmd.io/uYG9CJrFQZ-6FtKqpnYJAA?view

Jira issue: [FW-1460](https://angular-team.atlassian.net/browse/FW-1460)

PR Close #32427
2019-09-09 15:55:13 -04:00
George Kalpakas f4e4bb2085 refactor(ngcc): implement task selection for parallel task execution (#32427)
This commit adds a new `TaskQueue` implementation that supports
executing multiple tasks in parallel (while respecting interdependencies
between them).

This new implementation is currently not used, thus the behavior of
`ngcc` is not affected by this change. The parallel `TaskQueue` will be
used in a subsequent commit that will introduce parallel task execution.

PR Close #32427
2019-09-09 15:55:13 -04:00
George Kalpakas 2844dd2972 refactor(ngcc): abstract task selection behind an interface (#32427)
This change does not alter the current behavior, but makes it easier to
introduce `TaskQueue`s implementing different task selection algorithms,
for example to support executing multiple tasks in parallel (while
respecting interdependencies between them).

Inspired by/Based on @alxhub's prototype: alxhub/angular@cb631bdb1

PR Close #32427
2019-09-09 15:55:13 -04:00
George Kalpakas 0cf94e3ed5 refactor(ngcc): remove unused `EntryPointProcessingMetadata` data and types (#32427)
Previously, `ngcc` needed to store some metadata related to the
processing of each entry-point. This metadata was stored in a `Map`, in
the form of `EntryPointProcessingMetadata` and passed around as needed.

After some recent refactorings, it turns out that this metadata (with
its only remaining property, `hasProcessedTypings`) was no longer used,
because the relevant information was extracted from other sources (such
as the `processDts` property on `Task`s).

This commit cleans up the code by removing the unused code and types.

PR Close #32427
2019-09-09 15:55:13 -04:00
George Kalpakas 9270d3f279 refactor(ngcc): take advantage of early knowledge about format property processability (#32427)
In the past, a task's processability didn't use to be known in advance.
It was possible that a task would be created and added to the queue
during the analysis phase and then later (during the compilation phase)
it would be found out that the task (i.e. the associated format
property) was not processable.

As a result, certain checks had to be delayed, until a task's processing
had started or even until all tasks had been processed. Examples of
checks that had to be delayed are:
- Whether a task can be skipped due to `compileAllFormats: false`.
- Whether there were entry-points for which no format at all was
  successfully processed.

It turns out that (as made clear by the refactoring in 9537b2ff8), once
a task starts being processed it is expected to either complete
successfully (with the associated format being processed) or throw an
error (in which case the process will exit). In other words, a task's
processability is known in advance.

This commit takes advantage of this fact by moving certain checks
earlier in the process (e.g. in the analysis phase instead of the
compilation phase), which in turn allows avoiding some unnecessary work.
More specifically:

- When `compileAllFormats` is `false`, tasks are created _only_ for the
  first suitable format property for each entry-point, since the rest of
  the tasks would have been skipped during the compilation phase anyway.
  This has the following advantages:
  1. It avoids the slight overhead of generating extraneous tasks and
     then starting to process them (before realizing they should be
     skipped).
  2. In a potential future parallel execution mode, unnecessary tasks
     might start being processed at the same time as the first (useful)
     task, even if their output would be later discarded, wasting
     resources. Alternatively, extra logic would have to be added to
     prevent this from happening. The change in this commit avoids these
     issues.
- When an entry-point is not processable, an error will be thrown
  upfront without having to wait for other tasks to be processed before
  failing.

PR Close #32427
2019-09-09 15:55:13 -04:00
George Kalpakas 3127ba3c35 refactor(ngcc): add support for asynchronous execution (#32427)
Previously, `ngcc`'s programmatic API would run and complete
synchronously. This was necessary for specific usecases (such as how the
`@angular/cli` invokes `ngcc` as part of the TypeScript module
resolution process), but not for others (e.g. running `ivy-ngcc` as a
`postinstall` script).

This commit adds a new option (`async`) that enables turning on
asynchronous execution. I.e. it signals that the caller is OK with the
function call to complete asynchronously, which allows `ngcc` to
potentially run in a more efficient mode.

Currently, there is no difference in the way tasks are executed in sync
vs async mode, but this change sets the ground for adding new execution
options (that require asynchronous operation), such as processing tasks
in parallel on multiple processes.

NOTE:
When using the programmatic API, the default value for `async` is
`false`, thus retaining backwards compatibility.
When running `ngcc` from the command line (i.e. via the `ivy-ngcc`
script), it runs in async mode (to be able to take advantage of future
optimizations), but that is transparent to the caller.

PR Close #32427
2019-09-09 15:55:13 -04:00
George Kalpakas 5c213e5474 refactor(ngcc): abstract work orchestration/execution behind an interface (#32427)
This change does not alter the current behavior, but makes it easier to
introduce new types of `Executors` , for example to do the required work
in parallel (on multiple processes).

Inspired by/Based on @alxhub's prototype: alxhub/angular@cb631bdb1

PR Close #32427
2019-09-09 15:55:13 -04:00
George Kalpakas 3d9dd6df0e refactor(ngcc): abstract updating `package.json` files behind an interface (#32427)
To persist some of its state, `ngcc` needs to update `package.json`
files (both in memory and on disk).

This refactoring abstracts these operations behind the
`PackageJsonUpdater` interface, making it easier to orchestrate them
from different contexts (e.g. when running tasks in parallel on multiple
processes).

Inspired by/Based on @alxhub's prototype: alxhub/angular@cb631bdb1

PR Close #32427
2019-09-09 15:55:13 -04:00
George Kalpakas 38359b166e fix(ngcc): only back up the original `prepublishOnly` script and not the overwritten one (#32427)
In order to prevent `ngcc`'d packages (e.g. libraries) from getting
accidentally published, `ngcc` overwrites the `prepublishOnly` npm
script to log a warning and exit with an error. In case we want to
restore the original script (e.g. "undo" `ngcc` processing), we keep a
backup of the original `prepublishOnly` script.

Previously, running `ngcc` a second time (e.g. for a different format)
would create a backup of the overwritten `prepublishOnly` script (if
there was originally no `prepublishOnly` script). As a result, if we
ever tried to "undo" `ngcc` processing and restore the original
`prepublishOnly` script, the error-throwing script would be restored
instead.

This commit fixes it by ensuring that we only back up a `prepublishOnly`
script, iff it is not the one we created ourselves (i.e. the
error-throwing one).

PR Close #32427
2019-09-09 15:55:13 -04:00
George Kalpakas bd1de32b33 refactor(ngcc): minor code clean-up following #32052 (#32427)
This commit addresses the review feedback from #32052, which was merged
before addressing the feedback there.

PR Close #32427
2019-09-09 15:55:13 -04:00
Andrew Kushnir f00d03356f fix(ivy): handle expressions in i18n attributes properly (#32309)
Prior to this commit, complex expressions (that require additional statements to be generated) were handled incorrectly in case they were used in attributes annotated with i18n flags. The problem was caused by the fact that extra statements were not appended to the temporary vars block, so they were missing in generated code. This commit updated the logic to use the `convertPropertyBinding`, which contains the necessary code to append extra statements. The `convertExpressionBinding` function was removed as it duplicates the `convertPropertyBinding` one (for the most part) and is no longer used.

PR Close #32309
2019-09-05 13:35:16 -04:00
Pete Bacon Darwin a731119f9f fix(ivy): i18n - do not generate jsdoc comments for `$localize` (#32473)
Previously the template compiler would generate the same jsdoc comment
block for `$localize` as for `goog.getMsg()`. But it turns out that
the closure compiler will complain if the `@desc` and `@meaning`
tags are used for non-`getMsg()` calls.

For now we do not generate the comments for `$localize` calls. They are
not being used at the moment.

In the future it would be good to be able to extract the descriptions and
meanings from the `$localize` calls rather than relying upon the `getMsg()`
calls, which we do now. So we need to find a workaround for this constraint.

PR Close #32473
2019-09-04 15:40:23 -07:00
Pete Bacon Darwin 5d8eb74634 fix(ivy): i18n - handle translated text containing HTML comments (#32475)
Fixes FW-1536

PR Close #32475
2019-09-04 12:48:44 -07:00
Pete Bacon Darwin c024d89448 refactor(ivy): remove `i18nLocalize` instruction (#31609)
This has been replaced by the `$localize` tag.

PR Close #31609
2019-08-30 12:53:26 -07:00
Pete Bacon Darwin fa79f51645 refactor(ivy): update the compiler to emit `$localize` tags (#31609)
This commit changes the Angular compiler (ivy-only) to generate `$localize`
tagged strings for component templates that use `i18n` attributes.

BREAKING CHANGE

Since `$localize` is a global function, it must be included in any applications
that use i18n. This is achieved by importing the `@angular/localize` package
into an appropriate bundle, where it will be executed before the renderer
needs to call `$localize`. For CLI based projects, this is best done in
the `polyfills.ts` file.

```ts
import '@angular/localize';
```

For non-CLI applications this could be added as a script to the index.html
file or another suitable script file.

PR Close #31609
2019-08-30 12:53:26 -07:00
JoostK f7471eea3c fix(ngcc): handle compilation diagnostics (#31996)
Previously, any diagnostics reported during the compilation of an
entry-point would not be shown to the user, but either be ignored or
cause a hard crash in case of a `FatalDiagnosticError`. This is
unfortunate, as such error instances contain information on which code
was responsible for producing the error, whereas only its error message
would not. Therefore, it was quite hard to determine where the error
originates from.

This commit introduces behavior to deal with error diagnostics in a more
graceful way. Such diagnostics will still cause the compilation to fail,
however the error message now contains formatted diagnostics.

Closes #31977
Resolves FW-1374

PR Close #31996
2019-08-29 12:38:02 -07:00
JoostK 4161d19374 test(ivy): normalize rooted paths to include a drive letter in Windows (#31996)
The Angular compiler has an emulation system for various kinds of
filesystems and runs its testcases for all those filesystems. This
allows to verify that the compiler behaves correctly in all of the
supported platforms, without needing to run the tests on the actual
platforms.

Previously, the emulated Windows mode would normalize rooted paths to
always include a drive letter, whereas the native mode did not perform
this normalization. The consequence of this discrepancy was that running
the tests in native Windows was behaving differently compared to how
emulated Windows mode behaves, potentially resulting in test failures
in native Windows that would succeed for emulated Windows.

This commit adds logic to ensure that paths are normalized equally for
emulated Windows and native Windows mode, therefore resolving the
discrepancy.

PR Close #31996
2019-08-29 12:38:02 -07:00
Pete Bacon Darwin d5101dff3b fix(ivy): ngcc - improve the "ngcc version changed" error message (#32396)
If a project has nested projects that contain node_modules folders
that get processed by ngcc, it can be confusing when the ngcc
version changes since the error message is very generic:

```
The ngcc compiler has changed since the last ngcc build.
Please completely remove `node_modules` and try again.
```

This commit augments the error message with the path of
the entry-point that failed so that it is more obvious which
node_modules folder to remove.

BREAKING CHANGE:

This commit removes the public export of `hasBeenProcessed()`.

This was exported to be availble to the CLI integration but was never
used. The change to the function signature is a breaking change in itself
so we remove the function altogether to simplify and lower the public
API surface going forward.

PR Close #32396
2019-08-29 12:32:54 -07:00
Kristiyan Kostadinov c885178d5f refactor(ivy): move directive, component and pipe factories to ngFactoryFn (#31953)
Reworks the compiler to output the factories for directives, components and pipes under a new static field called `ngFactoryFn`, instead of the usual `factory` property in their respective defs. This should eventually allow us to inject any kind of decorated class (e.g. a pipe).

**Note:** these changes are the first part of the refactor and they don't include injectables. I decided to leave injectables for a follow-up PR, because there's some more cases we need to handle when it comes to their factories. Furthermore, directives, components and pipes make up most of the compiler output tests that need to be refactored and it'll make follow-up PRs easier to review if the tests are cleaned up now.

This is part of the larger refactor for FW-1468.

PR Close #31953
2019-08-27 13:57:00 -07:00
Kara Erickson c3f9893d81 refactor(core): remove innerHTML and outerHTML testing utilities from DomAdapters (#32278)
PR Close #32278
2019-08-26 10:39:09 -07:00
JoostK e563d77128 fix(ngcc): do not analyze dependencies for non Angular entry-points (#32303)
When ngcc is called for a specific entry-point, it has to determine
which dependencies to transitively process. To accomplish this, ngcc
traverses the full import graph of the entry-points it encounters, for
which it uses a dependency host to find all module imports. Since
imports look different in the various bundle formats ngcc supports, a
specific dependency host is used depending on the information provided
in an entry-points `package.json` file. If there's not enough
information in the `package.json` file for ngcc to be able to determine
which dependency host to use, ngcc would fail with an error.

If, however, the entry-point is not compiled by Angular, it is not
necessary to process any of its dependencies. None of them can have
been compiled by Angular so ngcc does not need to know about them.
Therefore, this commit changes the behavior to avoid recursing into
dependencies of entry-points that are not compiled by Angular.

In particular, this fixes an issue for packages that have dependencies
on the `date-fns` package. This package has various secondary
entry-points that have a `package.json` file only containing a `typings`
field, without providing additional fields for ngcc to know which
dependency host to use. By not needing a dependency host at all, the
error is avoided.

Fixes #32302

PR Close #32303
2019-08-26 10:08:44 -07:00
Paul Gschwendtner 4f7c971ee7 fix(ivy): ngtsc throws if "flatModuleOutFile" is set to null (#32235)
In ngc is was valid to set the "flatModuleOutFile" option to "null". This is sometimes
necessary if a tsconfig extends from another one but the "fatModuleOutFile" option
needs to be unset (note that "undefined" does not exist as value in JSON)

Now if ngtsc is used to compile the project, ngtsc will fail with an error because it
tries to do string manipulation on the "flatModuleOutFile". This happens because
ngtsc only skips flat module indices if the option is set to "undefined".

Since this is not compatible with what was supported in ngc and such exceptions
should be avoided, the flat module check is now aligned with ngc.

```
TypeError: Cannot read property 'replace' of null
    at Object.normalizeSeparators (/home/circleci/project/node_modules/@angular/compiler-cli/src/ngtsc/util/src/path.js:35:21)
    at new NgtscProgram (/home/circleci/project/node_modules/@angular/compiler-cli/src/ngtsc/program.js:126:52)
```

Additionally setting the `flatModuleOutFile` option to an empty string
currently results in unexpected behavior. No errors is thrown, but the
flat module index file will be `.ts` (no file name; just extension).

This is now also fixed by treating an empty string similarly to
`null`.

PR Close #32235
2019-08-22 10:14:38 -07:00
Alex Rickabaugh 0677cf0cbe feat(ivy): use the schema registry to check DOM bindings (#32171)
Previously, ngtsc attempted to use the .d.ts schema for HTML elements to
check bindings to DOM properties. However, the TypeScript lib.dom.d.ts
schema does not perfectly align with the Angular DomElementSchemaRegistry,
and these inconsistencies would cause issues in apps. There is also the
concern of supporting both CUSTOM_ELEMENTS_SCHEMA and NO_ERRORS_SCHEMA which
would have been very difficult to do in the existing system.

With this commit, the DomElementSchemaRegistry is employed in ngtsc to check
bindings to the DOM. Previous work on producing template diagnostics is used
to support generation of this different kind of error with the same high
quality of error message.

PR Close #32171
2019-08-22 10:12:45 -07:00
Alex Rickabaugh 0287b234ea feat(ivy): convert all ngtsc diagnostics to ts.Diagnostics (#31952)
Historically, the Angular Compiler has produced both native TypeScript
diagnostics (called ts.Diagnostics) and its own internal Diagnostic format
(called an api.Diagnostic). This was done because TypeScript ts.Diagnostics
cannot be produced for files not in the ts.Program, and template type-
checking diagnostics are naturally produced for external .html template
files.

This design isn't optimal for several reasons:

1) Downstream tooling (such as the CLI) must support multiple formats of
diagnostics, adding to the maintenance burden.

2) ts.Diagnostics have gotten a lot better in recent releases, with support
for suggested changes, highlighting of the code in question, etc. None of
these changes have been of any benefit for api.Diagnostics, which have
continued to be reported in a very primitive fashion.

3) A future plugin model will not support anything but ts.Diagnostics, so
generating api.Diagnostics is a blocker for ngtsc-as-a-plugin.

4) The split complicates both the typings and the testing of ngtsc.

To fix this issue, this commit changes template type-checking to produce
ts.Diagnostics instead. Instead of reporting a special kind of diagnostic
for external template files, errors in a template are always reported in
a ts.Diagnostic that highlights the portion of the template which contains
the error. When this template text is distinct from the source .ts file
(for example, when the template is parsed from an external resource file),
additional contextual information links the error back to the originating
component.

A template error can thus be reported in 3 separate ways, depending on how
the template was configured:

1) For inline template strings which can be directly mapped to offsets in
the TS code, ts.Diagnostics point to real ranges in the source.

This is the case if an inline template is used with a string literal or a
"no-substitution" string. For example:

```typescript
@Component({..., template: `
<p>Bar: {{baz}}</p>
`})
export class TestCmp {
  bar: string;
}
```

The above template contains an error (no 'baz' property of `TestCmp`). The
error produced by TS will look like:

```
<p>Bar: {{baz}}</p>
          ~~~

test.ts:2:11 - error TS2339: Property 'baz' does not exist on type 'TestCmp'. Did you mean 'bar'?
```

2) For template strings which cannot be directly mapped to offsets in the
TS code, a logical offset into the template string will be included in
the error message. For example:

```typescript
const SOME_TEMPLATE = '<p>Bar: {{baz}}</p>';

@Component({..., template: SOME_TEMPLATE})
export class TestCmp {
  bar: string;
}
```

Because the template is a reference to another variable and is not an
inline string constant, the compiler will not be able to use "absolute"
positions when parsing the template. As a result, errors will report logical
offsets into the template string:

```
<p>Bar: {{baz}}</p>
          ~~~

test.ts (TestCmp template):2:15 - error TS2339: Property 'baz' does not exist on type 'TestCmp'.

  test.ts:3:28
    @Component({..., template: TEMPLATE})
                               ~~~~~~~~

    Error occurs in the template of component TestCmp.
```

This error message uses logical offsets into the template string, and also
gives a reference to the `TEMPLATE` expression from which the template was
parsed. This helps in locating the component which contains the error.

3) For external templates (templateUrl), the error message is delivered
within the HTML template file (testcmp.html) instead, and additional
information contextualizes the error on the templateUrl expression from
which the template file was determined:

```
<p>Bar: {{baz}}</p>
          ~~~

testcmp.html:2:15 - error TS2339: Property 'baz' does not exist on type 'TestCmp'.

  test.ts:10:31
    @Component({..., templateUrl: './testcmp.html'})
                                  ~~~~~~~~~~~~~~~~

    Error occurs in the template of component TestCmp.
```

PR Close #31952
2019-08-21 10:51:59 -07:00
Alex Rickabaugh bfc26bcd8c fix(ivy): run template type-checking for all components (#31952)
PR Close #31952
2019-08-21 10:51:59 -07:00
JoostK 0db1b5d8f1 fix(ivy): handle empty bindings in template type checker (#31594)
When a template contains a binding without a value, the template parser
creates an `EmptyExpr` node. This would previously be translated into
an `undefined` value, which would cause a crash downstream as `undefined`
is not included in the allowed type, so it was not handled properly.

This commit prevents the crash by returning an actual expression for empty
bindings.

Fixes #30076
Fixes #30929

PR Close #31594
2019-08-21 10:14:44 -07:00
Alan 424ab48672 fix(compiler): return enableIvy true when using `readConfiguration` (#32234)
PR Close #32234
2019-08-21 10:06:25 -07:00
Alex Rickabaugh ec4381dd40 feat: make the Ivy compiler the default for ngc (#32219)
This commit switches the default value of the enableIvy flag to true.
Applications that run ngc will now by default receive an Ivy build!

This does not affect the way Bazel builds in the Angular repo work, since
those are still switched based on the value of the --define=compile flag.
Additionally, projects using @angular/bazel still use View Engine builds
by default.

Since most of the Angular repo tests are still written against View Engine
(particularly because we still publish VE packages to NPM), this switch
also requires lots of `enableIvy: false` flags in tsconfigs throughout the
repo.

Congrats to the team for reaching this milestone!

PR Close #32219
2019-08-20 16:41:08 -07:00
Alex Rickabaugh 2b64031ddc refactor(ivy): remove the tsc passthrough option (#32219)
This option makes ngc behave as tsc, and was originally implemented before
ngtsc existed. It was designed so we could build JIT-only versions of
Angular packages to begin testing Ivy early, and is not used at all in our
current setup.

PR Close #32219
2019-08-20 16:41:08 -07:00
atscott cfed0c0cf1 fix(ivy): Support selector-less directive as base classes (#32125)
Following #31379, this adds support for directives without a selector to
Ivy.

PR Close #32125
2019-08-20 09:56:54 -07:00
Elvis Begovic f8b995dbf9 fix(ngcc): ignore format properties that exist but are undefined (#32205)
Previously, `ngcc` assumed that if a format property was defined in
`package.json` it would point to a valid format-path (i.e. a file that
is an entry-point for a specific format). This is generally the case,
except if a format property is set to a non-string value (such as
`package.json`) - either directly in the `package.json` (which is unusual)
or in ngcc.config.js (which is a valid usecase, when one wants a
format property to be ignored by `ngcc`).

For example, the following config file would cause `ngcc` to throw:

```
module.exports = {
  packages: {
    'test-package': {
      entryPoints: {
        '.': {
          override: {
            fesm2015: undefined,
          },
        },
      },
    },
  },
};
```

This commit fixes it by ensuring that only format properties whose value
is a string are considered by `ngcc`.

For reference, this regression was introduced in #32052.

Fixes #32188

PR Close #32205
2019-08-20 09:55:25 -07:00
JoostK 4bbf16e654 fix(ngcc): handle deep imports that already have an extension (#32181)
During the dependency analysis phase of ngcc, imports are resolved to
files on disk according to certain module resolution rules. Since module
specifiers are typically missing extensions, or can refer to index.js
barrel files within a directory, the module resolver attempts several
postfixes when searching for a module import on disk. Module  specifiers
that already include an extension, however, would fail to be resolved as
ngcc's module resolver failed to check the location on disk without
adding any postfixes.

Closes #32097

PR Close #32181
2019-08-19 10:12:03 -07:00
JoostK ae142a6827 refactor(ngcc): avoid repeated file resolution during dependency scan (#32181)
During the recursive processing of dependencies, ngcc resolves the
requested file to an actual location on disk, by testing various
extensions. For recursive calls however, the path is known to have been
resolved in the module resolver. Therefore, it is safe to move the path
resolution to the initial caller into the recursive process.

Note that this is not expected to improve the performance of ngcc, as
the call to `resolveFileWithPostfixes` is known to succeed immediately,
as the provided path is known to exist without needing to add any
postfixes. Furthermore, the FileSystem caches whether files exist, so
the additional check that we used to do was cheap.

PR Close #32181
2019-08-19 10:12:03 -07:00
Alex Rickabaugh 964d72610f fix(ivy): ngcc should only index .d.ts exports within the package (#32129)
ngcc needs to solve a unique problem when compiling typings for an
entrypoint: it must resolve a declaration within a .js file to its
representation in a .d.ts file. Since such .d.ts files can be used in deep
imports without ever being referenced from the "root" .d.ts, it's not enough
to simply match exported types to the root .d.ts. ngcc must build an index
of all .d.ts files.

Previously, this operation had a bug: it scanned all .d.ts files in the
.d.ts program, not only those within the package. Thus, if a class in the
program happened to share a name with a class exported from a dependency's
.d.ts, ngcc might accidentally modify the wrong .d.ts file, causing a
variety of issues downstream.

To fix this issue, ngcc's .d.ts scanner now limits the .d.ts files it
indexes to only those declared in the current package.

PR Close #32129
2019-08-15 14:46:00 -07:00
Alex Rickabaugh 02bab8cf90 fix(ivy): in ngcc, handle inline exports in commonjs code (#32129)
One of the compiler's tasks is to enumerate the exports of a given ES
module. This can happen for example to resolve `foo.bar` where `foo` is a
namespace import:

```typescript
import * as foo from './foo';

@NgModule({
  directives: [foo.DIRECTIVES],
})
```

In this case, the compiler must enumerate the exports of `foo.ts` in order
to evaluate the expression `foo.DIRECTIVES`.

When this operation occurs under ngcc, it must deal with the different
module formats and types of exports that occur. In commonjs code, a problem
arises when certain exports are downleveled.

```typescript
export const DIRECTIVES = [
  FooDir,
  BarDir,
];
```

can be downleveled to:

```javascript
exports.DIRECTIVES = [
  FooDir,
  BarDir,
```

Previously, ngtsc and ngcc expected that any export would have an associated
`ts.Declaration` node. `export class`, `export function`, etc. all retain
`ts.Declaration`s even when downleveled. But the `export const` construct
above does not. Therefore, ngcc would not detect `DIRECTIVES` as an export
of `foo.ts`, and the evaluation of `foo.DIRECTIVES` would therefore fail.

To solve this problem, the core concept of an exported `Declaration`
according to the `ReflectionHost` API is split into a `ConcreteDeclaration`
which has a `ts.Declaration`, and an `InlineDeclaration` which instead has
a `ts.Expression`. Differentiating between these allows ngcc to return an
`InlineDeclaration` for `DIRECTIVES` and correctly keep track of this
export.

PR Close #32129
2019-08-15 14:45:59 -07:00
Alex Rickabaugh 4055150910 feat(compiler): allow selector-less directives as base classes (#31379)
In Angular today, the following pattern works:

```typescript
export class BaseDir {
  constructor(@Inject(ViewContainerRef) protected vcr: ViewContainerRef) {}
}

@Directive({
  selector: '[child]',
})
export class ChildDir extends BaseDir {
  // constructor inherited from BaseDir
}
```

A decorated child class can inherit a constructor from an undecorated base
class, so long as the base class has metadata of its own (for JIT mode).
This pattern works regardless of metadata in AOT.

In Angular Ivy, this pattern does not work: without the @Directive
annotation identifying the base class as a directive, information about its
constructor parameters will not be captured by the Ivy compiler. This is a
result of Ivy's locality principle, which is the basis behind a number of
compilation optimizations.

As a solution, @Directive() without a selector will be interpreted as a
"directive base class" annotation. Such a directive cannot be declared in an
NgModule, but can be inherited from. To implement this, a few changes are
made to the ngc compiler:

* the error for a selector-less directive is now generated when an NgModule
  declaring it is processed, not when the directive itself is processed.
* selector-less directives are not tracked along with other directives in
  the compiler, preventing other errors (like their absence in an NgModule)
  from being generated from them.

PR Close #31379
2019-08-14 12:03:05 -07:00
Keen Yee Liau a91ab15525 fix(language-service): Remove 'context' used for module resolution (#32015)
The language service relies on a "context" file that is used as the
canonical "containing file" when performing module resolution.
This file is unnecessary since the language service host's current
directory always default to the location of tsconfig.json for the
project, which would give the correct result.

This refactoring allows us to simplify the "typescript host" and also
removes the need for custom logic to find tsconfig.json.

PR Close #32015
2019-08-13 11:19:18 -07:00
Kristiyan Kostadinov 4ea3e7e000 refactor(ivy): combine query load instructions (#32100)
Combines the `loadViewQuery` and `loadContentQuery` instructions since they have the exact same internal logic. Based on a discussion here: https://github.com/angular/angular/pull/32067#pullrequestreview-273001730

PR Close #32100
2019-08-12 10:32:08 -07:00
Kara Erickson 37de490e23 Revert "feat(compiler): allow selector-less directives as base classes (#31379)" (#32089)
This reverts commit f90c7a9df0 due to breakages in G3.

PR Close #32089
2019-08-09 18:20:53 -07:00
Pete Bacon Darwin 0ddf0c4895 fix(compiler): do not remove whitespace wrapping i18n expansions (#31962)
Similar to interpolation, we do not want to completely remove whitespace
nodes that are siblings of an expansion.

For example, the following template

```html
<div>
  <strong>items left<strong> {count, plural, =1 {item} other {items}}
</div>
```

was being collapsed to

```html
<div><strong>items left<strong>{count, plural, =1 {item} other {items}}</div>
```

which results in the text looking like

```
items left4
```

instead it should be collapsed to

```html
<div><strong>items left<strong> {count, plural, =1 {item} other {items}}</div>
```

which results in the text looking like

```
items left 4
```

---

**Analysis of the code and manual testing has shown that this does not cause
the generated ids to change, so there is no breaking change here.**

PR Close #31962
2019-08-09 12:03:50 -07:00
Pete Bacon Darwin eb5412d76f fix(ivy): reuse compilation scope for incremental template changes. (#31932)
Previously if only a component template changed then we would know to
rebuild its component source file. But the compilation was incorrect if the
component was part of an NgModule, since we were not capturing the
compilation scope information that had a been acquired from the NgModule
and was not being regenerated since we were not needing to recompile
the NgModule.

Now we register compilation scope information for each component, via the
`ComponentScopeRegistry` interface, so that it is available for incremental
compilation.

The `ComponentDecoratorHandler` now reads the compilation scope from a
`ComponentScopeReader` interface which is implemented as a compound
reader composed of the original `LocalModuleScopeRegistry` and the
`IncrementalState`.

Fixes #31654

PR Close #31932
2019-08-09 10:50:40 -07:00
Alex Rickabaugh f90c7a9df0 feat(compiler): allow selector-less directives as base classes (#31379)
In Angular today, the following pattern works:

```typescript
export class BaseDir {
  constructor(@Inject(ViewContainerRef) protected vcr: ViewContainerRef) {}
}

@Directive({
  selector: '[child]',
})
export class ChildDir extends BaseDir {
  // constructor inherited from BaseDir
}
```

A decorated child class can inherit a constructor from an undecorated base
class, so long as the base class has metadata of its own (for JIT mode).
This pattern works regardless of metadata in AOT.

In Angular Ivy, this pattern does not work: without the @Directive
annotation identifying the base class as a directive, information about its
constructor parameters will not be captured by the Ivy compiler. This is a
result of Ivy's locality principle, which is the basis behind a number of
compilation optimizations.

As a solution, @Directive() without a selector will be interpreted as a
"directive base class" annotation. Such a directive cannot be declared in an
NgModule, but can be inherited from. To implement this, a few changes are
made to the ngc compiler:

* the error for a selector-less directive is now generated when an NgModule
  declaring it is processed, not when the directive itself is processed.
* selector-less directives are not tracked along with other directives in
  the compiler, preventing other errors (like their absence in an NgModule)
  from being generated from them.

PR Close #31379
2019-08-09 10:45:22 -07:00
Alan Agius 46304a4f83 feat(ivy): show error when trying to publish NGCC'd packages (#32031)
Publishing of NGCC packages should not be allowed. It is easy for a user to publish an NGCC'd version of a library they have workspace libraries which are being used in a workspace application.

If a users builds a library and afterwards the application, the library will be transformed with NGCC and since NGCC taints the distributed files that should be published.

With this change we use the npm/yarn `prepublishOnly` hook to display and error and abort the process with a non zero error code when a user tries to publish an NGCC version of the package.

More info: https://docs.npmjs.com/misc/scripts

PR Close #32031
2019-08-08 11:17:38 -07:00
George Kalpakas 29d3b68554 fix(ivy): ngcc - correctly update `package.json` when `createNewEntryPointFormats` is true (#32052)
Previously, when run with `createNewEntryPointFormats: true`, `ngcc`
would only update `package.json` with the new entry-point for the first
format property that mapped to a format-path. Subsequent properties
mapping to the same format-path would be detected as processed and not
have their new entry-point format recorded in `package.json`.

This commit fixes this by ensuring `package.json` is updated for all
matching format properties, when writing an `EntryPointBundle`.

PR Close #32052
2019-08-08 11:14:38 -07:00
George Kalpakas 93d27eefd5 refactor(ivy): ngcc - remove redundant `entryPoint` argument from `writeBundle()` (#32052)
The entry-point is already available through the `bundle` argument, so
passing it separately is redundant.

PR Close #32052
2019-08-08 11:14:38 -07:00
George Kalpakas ed70f73794 refactor(ivy): ngcc - remove `formatProperty` from `EntryPointBundle` (#32052)
Remove the `formatProperty` property from the `EntryPointBundle`
interface, because the property is not directly related to that type.

It was only used in one place, when calling `fileWriter.writeBundle()`,
but we can pass `formatProperty` directrly to `writeBundle()`.

PR Close #32052
2019-08-08 11:14:38 -07:00
George Kalpakas ef12e10e59 refactor(ivy): ngcc - split work into distinct analyze/compile/execute phases (#32052)
This refactoring more clearly separates the different phases of the work
performed by `ngcc`, setting the ground for being able to run each phase
independently in the future and improve performance via parallelization.

Inspired by/Based on @alxhub's prototype: alxhub/angular@cb631bdb1

PR Close #32052
2019-08-08 11:14:38 -07:00
George Kalpakas 2954d1b5ca refactor(ivy): ngcc - only try to process the necessary properties (#32052)
This change basically moves some checks to happen up front and ensures
we don't try to process any more properties than we absolutely need.
(The properties would not be processed before either, but we would
consider them, before finding out that they have already been processed
or that they do not exist in the entry-point's `package.json`.)

This change should make no difference in the work done by `ngcc`, but it
transforms the code in a way that makes the actual work known earlier,
thus making it easier to parallelize the processing of each property in
the future.

PR Close #32052
2019-08-08 11:14:38 -07:00
George Kalpakas 3077c9a1f8 refactor(ivy): ngcc - make `EntryPointJsonProperty`-related types and checks a little more strict (#32052)
PR Close #32052
2019-08-08 11:14:38 -07:00
George Kalpakas 9537b2ff84 refactor(ivy): ngcc - fix return type on `makeEntryPointBundle()` (#32052)
In commit 7b55ba58b (part of PR #29092), the implementation of
`makeEntryPointBundle()` was changed such that it now always return
`EntryPointBundle` (and not `null`).
However, the return type was not updated and as result we continued to
unnecessarily handle `null` as a potential return value in some places.

This commit fixes the return type to reflect the implementation and
removes the redundant code that was dealing with `null`.

PR Close #32052
2019-08-08 11:14:37 -07:00
Pete Bacon Darwin 961d663fbe fix(ivy): ngcc - report an error if a target has missing dependencies (#31872)
Previously, we either crashed with an obscure error or silently did
nothing. Now we throw an exception but with a helpful message.

PR Close #31872
2019-08-05 13:06:49 -07:00
JoostK 57e15fc08b fix(ivy): ngcc - do not consider builtin NodeJS modules as missing (#31872)
ngcc analyzes the dependency structure of the entrypoints it needs to
process, as the compilation of entrypoints is ordering sensitive: any
dependent upon entrypoint must be compiled before its dependees. As part
of the analysis of the dependency graph, it is detected when a
dependency of entrypoint is not installed, in which case that entrypoint
will be marked as ignored.

For libraries that work with Angular Universal to run in NodeJS, imports
into builtin NodeJS modules can be present. ngcc's dependency analyzer
can only resolve imports within the TypeScript compilation, which
builtin modules are not part of. Therefore, such imports would
erroneously cause the entrypoint to become ignored.

This commit fixes the problem by taking the NodeJS builtins into account
when dealing with missing imports.

Fixes #31522

PR Close #31872
2019-08-05 13:06:49 -07:00
JoostK b70746a113 fix(ivy): ngcc - prevent crash when analyzed target is ignored (#31872)
ngcc analyzes the dependency structure of the entrypoints it needs to
process, as the compilation of entrypoints is ordering sensitive: any
dependent upon entrypoint must be compiled before its dependees. As part
of the analysis of the dependency graph, it is detected when a
dependency of entrypoint is not installed, in which case that entrypoint
will be marked as ignored.

When a target entrypoint to compile is provided, it could occur that
given target is considered ignored because one of its dependencies might
be missing. This situation was not dealt with currently, instead
resulting in a crash of ngcc.

This commit prevents the crash by taking the above scenario into account.

PR Close #31872
2019-08-05 13:06:49 -07:00
George Kalpakas 7db269ba6a fix(ivy): ngcc - correctly detect formats processed in previous runs (#32003)
Previously, `ngcc` would avoid processing a `formatPath` that a property
in `package.json` mapped to, if either the _property_ was marked as
processed or the `formatPath` (i.e. the file(s)) was processed in the
same `ngcc` run (since the `compiledFormats` set was not persisted
across runs).
This could lead in a situation where a `formatPath` would be compiled
twice (if for example properties `a` and `b` both mapped to the same
`formatPath` and one would run `ngcc` for property `a` and then `b`).

This commit fixes it by ensuring that as soon as a `formatPath` has been
processed all corresponding properties are marked as processed (which
persists across `ngcc` runs).

PR Close #32003
2019-08-05 12:54:17 -07:00
George Kalpakas 8e5567d964 perf(ivy): ngcc - avoid unnecessary operations when we only need one format processed (#32003)
Previously, when `ngcc` was called with `compileAllFormats === false`
(i.e. how `@angular/cli` calls it), it would not attempt to process
more properties, once the first was successfully processed. However, it
_would_ continue looping over them and perform some unnecessary
operations, such as:
- Determining the format each property maps to (which can be an
  expensive operation for some properties mapping to either UMD or
  CommonJS).
- Checking whether each property has been processed (which involves
  checking whether any property has been processed with a different
  version of `ngcc` each time).
- Potentially marking properties as processed (which involves a
  file-write operation).

This commit avoids the unnecessary operations by entirely skipping
subsequent properties, once the first one has been successfully
processed. While this theoretically improves performance, it is not
expected to have any noticeable impact in practice, since the list of
`propertiesToConsider` is typically small and the most expensive
operation (marking a property as processed) has low likelihood of
happening (plus these operations are a tiny fraction of `ngcc`'s work).

PR Close #32003
2019-08-05 12:54:17 -07:00
George Kalpakas 541ce98432 perf(ivy): ngcc - avoid unnecessary file-write operations when marking properties as processed (#32003)
Previously, when `ngcc` needed to mark multiple properties as processed
(e.g. a processed format property and `typings` or all supported
properties for a non-Angular entry-point), it would update each one
separately and write the file to disk multiple times.

This commit changes this, so that multiple properties can be updated at
once with one file-write operation. While this theoretically improves
performance (reducing the I/O operations), it is not expected to have
any noticeable impact in practice, since these operations are a tiny
fraction of `ngcc`'s work.

This change will be useful for a subsequent change to mark all
properties that map to the same `formatPath` as processed, once it is
processed the first time.

PR Close #32003
2019-08-05 12:54:17 -07:00
George Kalpakas e7e3f5d952 refactor(ivy): ngcc - remove unused check for format support (#32003)
Now that `ngcc` supports all `EntryPointFormat`s, there is no need to
check if a format is supported, so this operation was a no-op.

PR Close #32003
2019-08-05 12:54:17 -07:00
Alex Rickabaugh f2d47c96c4 fix(ivy): ngcc emits static fields before extra statements (#31933)
This commit changes the emit order of ngcc when a class has multiple static
fields being assigned. Previously, ngcc would emit each static field
followed immediately by any extra statements specified for that field. This
causes issues with downstream tooling such as build optimizer, which expects
all of the static fields for a class to be grouped together. ngtsc already
groups static fields and additional statements. This commit changes ngcc's
ordering to match.

PR Close #31933
2019-08-01 10:45:36 -07:00
Alex Rickabaugh 82b97280f3 fix(ivy): speed up ngtsc if project has no templates to check (#31922)
If a project being built with ngtsc has no templates to check, then ngtsc
previously generated an empty typecheck file. This seems to trigger some
pathological behavior in TS where the entire user program is re-checked,
which is extremely expensive. This likely has to do with the fact that the
empty file is not considered an ES module, meaning the module structure of
the program has changed.

This commit causes an export to be produced in the typecheck file regardless
of its other contents, which guarantees that it will be an ES module. The
pathological behavior is avoided and template type-checking is fast once
again.

PR Close #31922
2019-07-31 16:20:38 -07:00
Ayaz Hafiz 4db959260b docs(ivy): Add README to indexer module (#31260)
Describe the indexer module for Angular compiler developers. Include
scope of analysis provided by the module and the indexers it targets as
first-party.

PR Close #31260
2019-07-31 11:37:11 -07:00
JoostK fc6f48185c fix(ivy): ngcc - render decorators in UMD and CommonJS bundles correctly (#31614)
In #31426 a fix was implemented to render namespaced decorator imports
correctly, however it turns out that the fix only worked when decorator
information was extracted from static properties, not when using
`__decorate` calls.

This commit fixes the issue by creating the decorator metadata with the
full decorator expression, instead of only its name.

Closes #31394

PR Close #31614
2019-07-29 16:10:58 -07:00
JoostK 80f290e301 fix(ivy): ngcc - recognize suffixed tslib helpers (#31614)
An identifier may become repeated when bundling multiple source files
into a single bundle, so bundlers have a strategy of suffixing non-unique
identifiers with a suffix like $2. Since ngcc operates on such bundles,
it needs to process potentially suffixed identifiers in their canonical
form without the suffix. The "ngx-pagination" package was previously not
compiled fully, as most decorators were not recognized.

This commit ensures that identifiers are first canonicalized by removing
the suffix, such that they are properly recognized and processed by ngcc.

Fixes #31540

PR Close #31614
2019-07-29 16:10:58 -07:00
JoostK 5e5be43acd refactor(ivy): ngcc - categorize the various decorate calls upfront (#31614)
Any decorator information present in TypeScript is emitted into the
generated JavaScript sources by means of `__decorate` call. This call
contains both the decorators as they existed in the original source
code, together with calls to `tslib` helpers that convey additional
information on e.g. type information and parameter decorators. These
different kinds of decorator calls were not previously distinguished on
their own, but instead all treated as `Decorator` by themselves. The
"decorators" that were actually `tslib` helper calls were conveniently
filtered out because they were not imported from `@angular/core`, a
characteristic that ngcc uses to drop certain decorators.

Note that this posed an inconsistency in ngcc when it processes
`@angular/core`'s UMD bundle, as the `tslib` helper functions have been
inlined in said bundle. Because of the inlining, the `tslib` helpers
appear to be from `@angular/core`, so ngcc would fail to drop those
apparent "decorators". This inconsistency does not currently cause any
issues, as ngtsc is specifically looking for decorators based on  their
name and any remaining decorators are simply ignored.

This commit rewrites the decorator analysis of a class to occur all in a
single phase, instead of all throughout the `ReflectionHost`. This
allows to categorize the various decorate calls in a single sweep,
instead of constantly needing to filter out undesired decorate calls on
the go. As an added benefit, the computed decorator information is now
cached per class, such that subsequent reflection queries that need
decorator information can reuse the cached info.

PR Close #31614
2019-07-29 16:10:57 -07:00
Greg Magolan 5f0d5e9ccf build: update to nodejs rules 0.34.0 and bazel 0.28.1 (#31824)
nodejs rules 0.34.0 now includes protractor_web_test_suite rule (via new @bazel/protractor rule) so we switch to that location for that rule in this PR so that /packages/bazel/src/protractor can be removed in a future PR

this PR also brings in node toolchain support which was released in nodejs rules 0.33.0. this is a prerequisite for RBE for mac & windows users

bazel schematics also updated with the same. @bazel/bazel 0.28.1 npm package includes transitive dep on hide-bazel-files so we're able to remove an explicit dep on that as well.

PR Close #31824
2019-07-26 15:01:25 -07:00
JoostK 397d0ba9a3 test(ivy): fix broken testcase in Windows (#31860)
In #30181, several testcases were added that were failing in Windows.
The reason was that a recent rebase missed a required change to interact
with the compiler's virtualized filesystems. This commit introduces the
required usage of the VFS layer to fix the testcase.

PR Close #31860
2019-07-26 12:22:12 -07:00
Ayaz Hafiz 859ebdd836 fix(ivy): correctly bind `targetToIdentifier` to the TemplateVisitor (#31861)
`TemplateVisitor#visitBoundAttribute` currently has to invoke visiting
expressions manually (this is fixed in #31813). Previously, it did not
bind `targetToIdentifier` to the visitor before deferring to the
expression visitor, which breaks the `targetToIdentifier` code. This
fixes that and adds a test to ensure the closure processed correctly.

This change is urgent; without it, many indexing targets in g3 are
broken.

PR Close #31861
2019-07-26 12:03:16 -07:00
Igor Minar 6ece7db37a build: TypeScript 3.5 upgrade (#31615)
https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#typescript-35

PR Close #31615
2019-07-25 17:05:23 -07:00
JoostK 3a2b195a58 feat(ivy): translate type-check diagnostics to their original source (#30181)
PR Close #30181
2019-07-25 16:36:32 -07:00
JoostK 489cef6ea2 feat(ivy): include value spans for attributes, variables and references (#30181)
Template AST nodes for (bound) attributes, variables and references will
now retain a reference to the source span of their value, which allows
for more accurate type check diagnostics.

PR Close #30181
2019-07-25 16:36:32 -07:00
JoostK 985513351b feat(ivy): let ngtsc annotate type check blocks with source positions (#30181)
The type check blocks (TCB) that ngtsc generates for achieving type
checking of Angular templates needs to be annotated with positional
information in order to translate TypeScript's diagnostics for the TCB
code back to the location in the user's template. This commit augments
the TCB by attaching trailing comments with AST nodes, such that a node
can be traced back to its source location.

PR Close #30181
2019-07-25 16:36:32 -07:00
JoostK 8f3dd85600 refactor(ivy): move ngtsc's TCB generation test util to separate file (#30181)
PR Close #30181
2019-07-25 16:36:32 -07:00
Ayaz Hafiz 6b67cd5620 feat(ivy): index template references, variables, bound attributes/events (#31535)
Adds support for indexing template referenecs, variables, and property
and method calls inside bound attributes and bound events. This is
mostly an extension of the existing indexing infrastructure.

PR Close #31535
2019-07-25 13:09:10 -07:00
crisbeto 3d7303efc0 perf(ivy): avoid extra parameter in query instructions (#31667)
Currently we always generate the `read` parameter for the view and content query instructions, however since most of the time the `read` parameter won't be set, we'll end up generating `null` which adds 5 bytes for each query when minified. These changes make it so that the `read` parameter only gets generated if it has a value.

PR Close #31667
2019-07-24 14:37:51 -07:00
Ayaz Hafiz 44039a4b16 feat(ivy): pass information about used directive selectors on elements (#31782)
Extend indexing API interface to provide information about used
directives' selectors on template elements. This enables an indexer to
xref element attributes to the directives that match them.

The current way this matching is done is by mapping selectors to indexed
directives. However, this fails in cases where the directive is not
indexed by the indexer API, like for transitive dependencies. This
solution is much more general.

PR Close #31782
2019-07-23 21:13:49 -07:00
Pete Bacon Darwin 59c3700c8c feat(ivy): ngcc - implement `UndecoratedParentMigration` (#31544)
Implementing the "undecorated parent" migration described in
https://hackmd.io/sfb3Ju2MTmKHSUiX_dLWGg#Design

PR Close #31544
2019-07-23 21:11:40 -07:00
Pete Bacon Darwin 4d93d2406f feat(ivy): ngcc - support ngcc "migrations" (#31544)
This commit implements support for the ngcc migrations
as designed in https://hackmd.io/KhyrFV1VQHmeQsgfJq6AyQ

PR Close #31544
2019-07-23 21:11:40 -07:00
Pete Bacon Darwin d39a2beae1 refactor(ivy): ngcc - move decorator analysis types into their own file (#31544)
PR Close #31544
2019-07-23 21:11:39 -07:00
Pete Bacon Darwin c038992fae refactor(ivy): use ReflectionHost to find base classes (#31544)
When analyzing components, directives, etc we capture its base class.
Previously this assumed that the code is in TS format, which is not
always the case (e.g. ngcc).
Now this code is replaced with a call to
`ReflectionHost.getBaseClassExpression()`, which abstracts the work
of finding the base class.

PR Close #31544
2019-07-23 21:11:39 -07:00
Pete Bacon Darwin 8a470b9af9 feat(ivy): add `getBaseClassIdentifier()` to `ReflectionHost` (#31544)
This method will be useful for writing ngcc `Migrations` that
need to be able to find base classes.

PR Close #31544
2019-07-23 21:11:39 -07:00
Pete Bacon Darwin 399935c32b refactor(ivy): ngtsc - remove unnecessary type on helpers (#31544)
The `ClassDeclaration` already contains the `{name: ts.Identifier}`
type so there is no need to include it explicitly here.

PR Close #31544
2019-07-23 21:11:39 -07:00
Pete Bacon Darwin 97ab52c618 test(ivy): ensure that `runInEachFileSystem` cleans up after itself (#31544)
Previously the last file-system being tested was left as the current
file-system. Now it is reset to an `InvalidFileSystem` to ensure future
tests are not affected.

PR Close #31544
2019-07-23 21:11:39 -07:00
crisbeto 0aff4a6919 fix(ivy): incorrect ChangeDetectorRef injected into pipes used in component inputs (#31438)
When injecting a `ChangeDetectorRef` into a pipe, the expected result is that the ref will be tied to the component in which the pipe is being used. This works for most cases, however when a pipe is used inside a property binding of a component (see test case as an example), the current `TNode` is pointing to component's host so we end up injecting the inner component's view. These changes fix the issue by only looking up the component view of the `TNode` if the `TNode` is a parent.

This PR resolves FW-1419.

PR Close #31438
2019-07-23 15:46:23 -07:00
Kara Erickson 215ef3c5f4 fix(ivy): ensure NgClass does not overwrite other dir data (#31788)
We currently have a handwritten version of the Ivy directive def for NgClass so
we can switch between Ivy and View Engine behavior. This generated code needs to
be kept up-to-date with what the Ivy compiler generates.

PR 30742 recently changed `classMap` such that it now requires allocation of
host binding slots. This means that the `allocHostVars()` function must be
called in the NgClass directive def to match compiler output, but the
handwritten directive def was not updated. This caused a bug where NgClass
was inappropriately overwriting data for other directives because space was
not allocated for its values.

PR Close #31788
2019-07-22 16:56:27 -07:00
Ayaz Hafiz f65db20c6d feat(ivy): record absolute position of template expressions (#31391)
Currently, template expressions and statements have their location
recorded relative to the HTML element they are in, with no handle to
absolute location in a source file except for a line/column location.
However, the line/column location is also not entirely accurate, as it
points an entire semantic expression, and not necessarily the start of
an expression recorded by the expression parser.

To support record of the source code expressions originate from, add a
new `sourceSpan` field to `ASTWithSource` that records the absolute byte
offset of an expression within a source code.

Implement part 2 of [refactoring template parsing for
stability](https://hackmd.io/@X3ECPVy-RCuVfba-pnvIpw/BkDUxaW84/%2FMA1oxh6jRXqSmZBcLfYdyw?type=book).

PR Close #31391
2019-07-22 09:48:35 -07:00
Matias Niemelä 9c954ebc62 refactor(ivy): make styling instructions use the new styling algorithm (#30742)
This commit is the final patch of the ivy styling algorithm refactor.
This patch swaps functionality from the old styling mechanism to the
new refactored code by changing the instruction code the compiler
generates and by pointing the runtime instruction code to the new
styling algorithm.

PR Close #30742
2019-07-19 16:40:40 -07:00
Pete Bacon Darwin 376ad9c3cd refactor(ivy): remove deep imports into the compiler (#31376)
The compiler-cli should only reference code that can
be imported from the main entry-point of compiler.

PR Close #31376
2019-07-18 14:23:32 -07:00
Matt Lewis 4aecf9253b fix(ivy): support older CLI versions that do not pass a list of changed files (#31322)
Versions of CLI prior to angular/angular-cli@0e339ee did not expose the host.getModifiedResourceFiles() method.

This meant that null was being passed through to the IncrementalState.reconcile() method
to indicate that there were either no changes or the host didn't support that method.

This commit fixes a bug where we were checking for undefined rather than null when
deciding whether any resource files had changed, causing a null reference error to be thrown.

This bug was not caught by the unit testing because the tests set up the changed files
via a slightly different process, not having access to the CompilerHost, and these test
were making the erroneous assumption that undefined indicated that there were no
changed files.

PR Close #31322
2019-07-18 14:22:07 -07:00
Paul Gschwendtner 647d7bdd88 refactor: fix typescript strict flag failures in all tests (#30993)
Fixes all TypeScript failures caused by enabling the `--strict`
flag for test source files. We also want to enable the strict
options for tests as the strictness enforcement improves the
overall codehealth, unveiled common issues and additionally it
allows us to enable `strict` in the `tsconfig.json` that is picked
up by IDE's.

PR Close #30993
2019-07-18 14:21:26 -07:00
JoostK a5f9a86520 feat(ivy): support undefined and null in static interpreter (#31150)
Previously, the usage of `null` and `undefined` keywords in code that is
statically interpreted by ngtsc resulted in a `DynamicValue`, as they were
not recognized as special entities. This commit adds support to interpret
these keywords.

PR Close #31150
2019-07-18 10:30:51 -07:00
Pete Bacon Darwin dd664f694c fix(ivy): ngcc - render namespaced imported decorators correctly (#31426)
The support for decorators that were imported via a namespace,
e.g. `import * as core from `@angular/core` was implemented
piecemeal. This meant that it was easy to miss situations where
a decorator identifier needed to be handled as a namepsaced
import rather than a direct import.

One such issue was that UMD processing of decorators was not
correct: the namespace was being omitted from references to
decorators.

Now the types have been modified to make it clear that a
`Decorator.identifier` could hold a namespaced identifier,
and the corresponding code that uses these types has been
fixed.

Fixes #31394

PR Close #31426
2019-07-18 10:17:50 -07:00
crisbeto 12fd06916b fix(ivy): don't match directives against attribute bindings (#31541)
Fixes Ivy matching directives against attribute bindings (e.g. `[attr.some-directive]="foo"`). Works by excluding attribute bindings from the attributes array during compilation. This has the added benefit of generating less code.

**Note:** My initial approach to implementing this was to have a different marker for attribute bindings so that they can be ignored when matching directives, however as I was implementing it I realized that the attributes in that array were only used for directive matching (as far as I could tell). I decided to drop the attribute bindings completely, because it results in less generated code.

PR Close #31541
2019-07-16 23:59:13 -04:00
crisbeto 40d785f0a0 perf(ivy): avoid generating extra parameters for host property bindings (#31550)
Currently we reuse the same instruction both for regular property bindings and property bindings on the `host`. The only difference between the two is that when it's on the host we shouldn't support inputs. We have an optional parameter called `nativeOnly` which is used to differentiate the two, however since `nativeOnly` is preceeded by another optional parameter (`sanitizer`), we have to generate two extra parameters for each host property bindings every time (e.g. `property('someProp', 'someValue', null, true)`).

These changes add a new instruction called `hostProperty` which avoids the need for the two parameters by removing `nativeOnly` which is always set and it allows us to omit `sanitizer` when it isn't being used.

These changes also remove the `nativeOnly` parameter from the `updateSyntheticHostBinding` instruction, because it's only generated for host elements which means that we can assume that its value will always be `true`.

PR Close #31550
2019-07-16 13:01:42 -04:00
Jon Wallsten 3166cffd28 fix(compiler-cli): Return original sourceFile instead of redirected sourceFile from getSourceFile (#26036)
Closes #22524

PR Close #26036
2019-07-15 17:33:40 -04:00
Ayaz Hafiz 604d9063c5 feat(ivy): index template elements for selectors, attributes, directives (#31240)
Add support for indexing elements in the indexing module.
Opening and self-closing HTML tags have their selector indexed, as well
as the attributes on the element and the directives applied to an
element.

PR Close #31240
2019-07-12 17:54:08 -04:00
Pete Bacon Darwin fac20bd8d1 fix(ivy): ngcc - resolve `main` property paths correctly (#31509)
There are two places in the ngcc processing where it needs to load the
content of a file given by a general path:

* when determining the format of an entry-point.
 To do this ngcc uses the value of the relevant property in package.json.
 But in the case of `main` it must parse the contents of the entry-point
 file to decide whether the format is UMD or CommonJS.

* when parsing the source files for dependencies to determine the order in
which compilation must occur. The relative imports in each file are parsed
and followed recursively, looking for external imports.

Previously, we naively assumed that the path would match the file name exactly.
But actually we must consider the standard module resolution conventions.
E.g. the extension (.js) may be missing, or the path may refer to a directory
containing an index.js file.

This commit fixes both places.

This commit now requires the `DependencyHost` instances to check
the existence of more files than before (at worst all the different possible
post-fixes). This should not create a significant performance reduction for
ngcc. Since the results of the checks will be cached, and similar work is
done inside the TS compiler, so what we lose in doing it here, is saved later
in the processing. The main performance loss would be where there are lots
of files that need to be parsed for dependencies that do not end up being
processed by TS. But compared to the main ngcc processing this dependency
parsing is a small proportion of the work done and so should not impact
much on the overall performance of ngcc.

// FW-1444

PR Close #31509
2019-07-12 11:37:35 -04:00
Andrew Kushnir 63e458dd3a fix(ivy): handle ICUs with placeholders in case other nested ICUs are present (#31516)
Prior to this fix, the logic to set the right placeholder format for ICUs was a bit incorrect: if there was a nested ICU in one of the root ICU cases, that led to a problem where placeholders in subsequent branches used the wrong ({$placeholder}) format instead of {PLACEHOLDER} one. This commit updates the logic to make sure we properly transform all placeholders even if nested ICUs are present.

PR Close #31516
2019-07-12 11:37:16 -04:00
George Kalpakas 4bb283cbb2 build: remove redundant `@types/source-map` dependency (#31468)
In version 0.6.1 that we are using, `source-map` ships with
[its own typings][1], so there is no need to use `@types/source-map`.
The types were even removed from `DefinitelyTyped` in
DefinitelyTyped/DefinitelyTyped@1792bfaa2.

[1]: https://github.com/mozilla/source-map/blob/0.6.1/package.json#L72

PR Close #31468
2019-07-11 17:18:12 -04:00
George Kalpakas a08b4b3519 build(compiler-cli): remove unused dependency (`shelljs`) (#31468)
Since, 7186f9c01 `compiler-cli` is no longer depending on `shelljs` for
production code. (We still use it in tests and infrastructure/tooling.)

Incidentally, this should also help with #29460.

PR Close #31468
2019-07-11 17:18:12 -04:00
Matias Niemelä db557221bc revert: fix(ivy): ngcc - resolve `main` property paths correctly (#31509)
This reverts commit 103a5b42ec.
2019-07-11 11:51:13 -04:00
Alex Rickabaugh 1cba5d42d1 fix(ivy): handle rooted resource paths correctly (#31511)
Previously, resource paths beginning with '/' (aka "rooted" paths, which
are not actually absolute filesystem paths, but are relative to the
TypeScript project root directory) were not handled correctly. The leading
'/' was stripped and the path was resolved as if it was relative, but with
no containing file for context. This led to resources in different rootDirs
not being found.

Instead, such rooted paths are now resolved without TypeScript's help, by
checking each root directory. A test is added to this effect.

PR Close #31511
2019-07-11 11:42:33 -04:00
Pete Bacon Darwin 103a5b42ec fix(ivy): ngcc - resolve `main` property paths correctly (#31509)
When determining if a `main` path points to a UMD or CommonJS
format, the contents of the file need to be loaded and parsed.

Previously, it was assumed that the path referred to the exact filename,
but did not account for normal module resolution semantics, where the
path may be missing an extension or refer to a directory containing an
`index.js` file.

// FW-1444

PR Close #31509
2019-07-11 11:41:11 -04:00
Andrew Kushnir dee16a4355 fix(ivy): update ICU placeholders format to match Closure compiler (#31459)
Since `goog.getMsg` does not process ICUs (post-processing is required via goog.i18n.MessageFormat, https://google.github.io/closure-library/api/goog.i18n.MessageFormat.html) and placeholder format used for ICUs and regular messages inside `goog.getMsg` are different, the current implementation (that assumed the same placeholder format) needs to be updated. This commit updates placeholder format used inside ICUs from `{$placeholder}` to `{PLACEHOLDER}` to better align with Closure. ICU placeholders (that were left as is prior to this commit) are now replaced with actual values in post-processing step (inside `i18nPostprocess`).

PR Close #31459
2019-07-10 18:31:33 -04:00
Andrew Kushnir 76e3b57a12 test(ivy): verify no translations are generated for bound attributes (#31481)
This commit adds a test that verifies no translations are generated for bound attributes and also checks (as a part of the `verify` function) that VE and Ivy handle this case the same way.

PR Close #31481
2019-07-10 18:28:58 -04:00
crisbeto 23e0d65471 perf(ivy): add self-closing elementContainer instruction (#31444)
Adds a new `elementContainer` instruction that can be used to avoid two instruction (`elementContainerStart` and `elementContainerEnd`) for `ng-container` that has text-only content. This is particularly useful when we have `ng-container` inside i18n sections.

This PR resolves FW-1105.

PR Close #31444
2019-07-09 13:50:28 -07:00
Pete Bacon Darwin 207f9b6017 fix(ivy): ngcc - handle pathMappings to files rather then directories (#30525)
Paths can be mapped directly to files, which was not being taken
into account when computing `basePaths` for the `EntryPointFinder`s.

Now if a `pathMapping` pattern does not exist or is a file, then we try
the containing folder instead.

Fixes #31424

PR Close #30525
2019-07-09 09:40:46 -07:00
Pete Bacon Darwin a581773887 perf(ivy): ngcc - only find dependencies when targeting a single entry-point (#30525)
Previously, ngcc had to walk the entire `node_modules` tree looking for
entry-points, even if it only needed to process a single target entry-point
and its dependencies.

This added up to a few seconds to each execution of ngcc, which is noticeable
when being run via the CLI integration.

Now, if an entry-point target is provided, only that target and its entry-points
are considered rather than the whole folder tree.

PR Close #30525
2019-07-09 09:40:46 -07:00
Pete Bacon Darwin 7f2330a968 perf(ivy): ngcc - add a cache to the FileSystem (#30525)
When profiling ngcc it is notable that a large amount of time
is spent dealing with an exception that is thrown (and handled
internally by fs) when checking the existence of a file.

We check file existence a lot in both finding entry-points
and when TS is compiling code. This commit adds a simple
cached `FileSystem`, which wraps a real `FileSystem` delegate.
This will reduce the number of calls through to `fs.exists()` and
`fs.readFile()` on the delegate.

Initial benchmarks indicate that the cache is miss to hit ratio
for `exists()` is about 2:1, which means that we save about 1/3
of the calls to `fs.existsSync()`.

Note that this implements a "non-expiring" cache, so it is not suitable
for a long lived `FileSystem`, where files may be modified externally.
The cache will be updated if a file is changed or moved via
calls to `FileSystem` methods but it will not be aware of changes
to the files system from outside the `FileSystem` service.

For ngcc we must create a new `FileSystem` service
for each run of `mainNgcc` and ensure that all file operations
(including TS compilation) use the `FileSystem` service.
This ensures that it is very unlikely that a file will change
externally during `mainNgcc` processing.

PR Close #30525
2019-07-09 09:40:46 -07:00
Pete Bacon Darwin aaaeb924ac fix(ivy): ngcc - remove unwanted logging message (#30525)
This message gets called if a format has already been
compiled and we only want the first. So the message itself
is wrong but it is also not very useful anyway.

PR Close #30525
2019-07-09 09:40:46 -07:00
Pete Bacon Darwin 98a68ad3e7 fix(ivy): handle namespaced imports correctly (#31367)
The ngcc tool adds namespaced imports to files when compiling. The ngtsc
tooling was not processing types correctly when they were imported via
such namespaces. For example:

```
export declare class SomeModule {
    static withOptions(...): ModuleWithProviders<ɵngcc1.BaseModule>;
```

In this case the `BaseModule` was being incorrectly attributed to coming
from the current module rather than the imported module, represented by
`ɵngcc1`.

Fixes #31342

PR Close #31367
2019-07-09 09:40:30 -07:00
Pete Bacon Darwin 83b19bf1a2 fix(ivy): ngcc - compute potential d.ts files from .js files (#31411)
If a package delcares a class internally on an NgModule, ngcc
needs to be able to add a public export to this class's type.

Previously, if the typing file for the declared is not imported
from the typings entry-point file, then ngcc cannot find it.
Now we try to guess the .d.ts files from the equivalent .js
files.

PR Close #31411
2019-07-09 09:35:26 -07:00
Ayaz Hafiz 6aaca21c27 fix(compiler): give ASTWithSource its own visit method (#31347)
ASTWithSource contains more information that AST and should have its own
visit method, if desired. This implements that.

PR Close #31347
2019-07-08 10:29:07 -07:00
Pete Bacon Darwin 50c4ec6687 fix(ivy): ngcc - resolve path-mapped modules correctly (#31450)
Non-wild-card path-mappings were not being matched correctly.

Further path-mapped secondary entry-points that
were imported from the associated primary entry-point were not
being martched correctly.

Fixes #31274

PR Close #31450
2019-07-08 10:28:13 -07:00
crisbeto 02491a6ce8 refactor(ivy): move classMap interpolation logic internally (#31211)
Adds the new `classMapInterpolate1` through `classMapInterpolate8` instructions which handle interpolations inside the `class` attribute and moves the interpolation logic internally. This allows us to remove the `interpolationX` instructions in a follow-up PR.

These changes also add an error if an interpolation is encountered inside a `style` tag (e.g. `style="width: {{value}}"`). Up until now this would actually generate valid instructions, because `styleMap` goes through the same code path as `classMap` which does support interpolation. At runtime, however, `styleMap` would set invalid styles that look like `<div style="0:w;1:i;2:d;3:t;4:h;5::;7:1;">`. In `ViewEngine` interpolations inside `style` weren't supported either, however there we'd output invalid styles like `<div style="unsafe">`, even if the content was trusted.

PR Close #31211
2019-07-02 11:07:14 -07:00
JoostK eb6281f5b4 fix(ivy): include type parameter for `ngBaseDef` declaration (#31210)
When a class uses Angular decorators such as `@Input`, `@Output` and
friends without an Angular class decorator, they are compiled into a
static `ngBaseDef` field on the class, with the TypeScript declaration
of the class being altered to declare the `ngBaseDef` field to be of type
`ɵɵBaseDef`. This type however requires a generic type parameter that
corresponds with the type of the class, however the compiler did not
provide this type parameter. As a result, compiling a program where such
invalid `ngBaseDef` declarations are present will result in compilation
errors.

This commit fixes the problem by providing the generic type parameter.

Fixes #31160

PR Close #31210
2019-07-02 11:06:46 -07:00
Greg Magolan a4a423a083 build: fix build failures with worker mode cache and @types/events (#31325)
Errors observed only in tests on CircleCI — was not reproducible locally.

```
ERROR: /home/circleci/ng/packages/http/test/BUILD.bazel:3:1: Compiling TypeScript (devmode) //packages/http/test:test_lib failed (Exit 1): tsc_wrapped failed: error executing command
  (cd /home/circleci/.cache/bazel/_bazel_circleci/9ce5c2144ecf75d11717c0aa41e45a8d/execroot/angular && \
  exec env - \
    BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1 \
    PATH=/bin:/usr/bin:/usr/local/bin \
  bazel-out/host/bin/external/npm/@bazel/typescript/bin/tsc_wrapped @@bazel-out/k8-fastbuild/bin/packages/http/test/test_lib_es5_tsconfig.json)
Execution platform: //tools:rbe_ubuntu1604-angular
Compilation failed Error: missing input digest for /home/circleci/.cache/bazel/_bazel_circleci/9ce5c2144ecf75d11717c0aa41e45a8d/execroot/angular/external/npm/node_modules/@types/events/index.d.ts.

ERROR: /home/circleci/ng/packages/benchpress/test/BUILD.bazel:3:1: Compiling TypeScript (devmode) //packages/benchpress/test:test_lib failed (Exit 1): tsc_wrapped failed: error executing command
  (cd /home/circleci/.cache/bazel/_bazel_circleci/9ce5c2144ecf75d11717c0aa41e45a8d/execroot/angular && \
  exec env - \
    BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1 \
    PATH=/bin:/usr/bin:/usr/local/bin \
  bazel-out/host/bin/external/npm/@bazel/typescript/bin/tsc_wrapped @@bazel-out/k8-fastbuild/bin/packages/benchpress/test/test_lib_es5_tsconfig.json)
Execution platform: //tools:rbe_ubuntu1604-angular
Compilation failed Error: missing input digest for /home/circleci/.cache/bazel/_bazel_circleci/9ce5c2144ecf75d11717c0aa41e45a8d/execroot/angular/external/npm/node_modules/@types/events/index.d.ts

ERROR: C:/codefresh/volume/angular/packages/compiler/test/css_parser/BUILD.bazel:3:1: Compiling TypeScript (devmode) //packages/compiler/test/css_parser:css_parser_lib failed (Exit 1):
tsc_wrapped.exe failed: error executing command
  cd C:/users/containeradministrator/_bazel_containeradministrator/zquin2l6/execroot/angular
  SET PATH=C:\msys64\usr\bin;C:\msys64\bin;C:\Windows;C:\Windows\System32;C:\Windows\System32\WindowsPowerShell\v1.0
    SET RUNFILES_MANIFEST_ONLY=1
  bazel-out/host/bin/external/npm/@bazel/typescript/bin/tsc_wrapped.exe @@bazel-out/x64_windows-fastbuild/bin/packages/compiler/test/css_parser/css_parser_lib_es5_tsconfig.json
Execution platform: @bazel_tools//platforms:host_platform
Compilation failed Error: missing input digest for C:/users/containeradministrator/_bazel_containeradministrator/zquin2l6/execroot/angular/external/npm/node_modules/@types/events/index.
d.ts
```

PR Close #31325
2019-07-01 14:16:43 -07:00
Greg Magolan 63bdfca580 build(bazel): cleanup entry_point target (#31325)
PR Close #31325
2019-07-01 14:16:42 -07:00
Pete Bacon Darwin dd36f3ac99 feat(ivy): ngcc - handle top-level helper calls in CommonJS (#31335)
Some formats of CommonJS put the decorator helper calls
outside the class IIFE as statements on the top level of the
source file.

This commit adds support to the `CommonJSReflectionHost`
for this format.

PR Close #31335
2019-07-01 10:09:41 -07:00
crisbeto 81332150aa perf(ivy): chain host binding instructions (#31296)
Adds chaining to the `property`, `attribute` and `updateSyntheticHostBinding` instructions when they're used in a host binding.

This PR resolves FW-1404.

PR Close #31296
2019-06-28 09:26:20 -07:00
Pete Bacon Darwin d171006083 fix(ivy): ngtsc - NgtscCompilerHost should cope with directories that look like files (#31289)
The TS compiler is likely to test paths with extensions and try to
load them as files. Therefore `fileExists()` and methods that rely
on it need to be able to distinguish between real files and directories
that have paths that look like files.

This came up as a bug in ngcc when trying to process `ngx-virtual-scroller`,
which relies upon a library called `@tweenjs/tween.js`.

PR Close #31289
2019-06-27 12:34:51 -07:00
Pete Bacon Darwin 3788ebb714 fix(ivy): ngcc - don't crash if entry-points have multiple invalid dependencies (#31276)
If an entry-point has missing dependencies then it cannot be
processed and is marked as invalid. Similarly, if an entry-point
has dependencies that have been marked as invalid then that
entry-point too is invalid. In all these cases, ngcc should quietly
ignore these entry-points and continue processing what it can.

Previously, if an entry-point had more than one entry-point that
was transitively invalid then ngcc was crashing rather than
ignoring the entry-point.

PR Close #31276
2019-06-26 08:01:43 -07:00
Pete Bacon Darwin f690a4e0af fix(ivy): ngcc - do not analyze files outside the current package (#30591)
Our module resolution prefers `.js` files over `.d.ts` files because
occasionally libraries publish their typings in the same directory
structure as the compiled JS files, i.e. adjacent to each other.

The standard TS module resolution would pick up the typings
file and add that to the `ts.Program` and so they would be
ignored by our analyzers. But we need those JS files, if they
are part of the current package.

But this meant that we also bring in JS files from external
imports from outside the package, which is not desired.
This was happening for the `@fire/storage` enty-point
that was importing the `firebase/storage` path.

In this commit we solve this problem, for the case of imports
coming from a completely different package, by saying that any
file that is outside the package root directory must be an external
import and so we do not analyze those files.

This does not solve the potential problem of imports between
secondary entry-points within a package but so far that does
not appear to be a problem.

PR Close #30591
2019-06-26 08:00:03 -07:00
Pete Bacon Darwin 42036f4b79 refactor(ivy): ngcc - pass `bundle` to `DecorationAnalyzer` (#30591)
Rather than passing a number of individual arguments, we can
just pass an `EntryPointBundle`, which already contains them.

This is also a precursor to using more of the properties in the bundle.

PR Close #30591
2019-06-26 08:00:03 -07:00
Pete Bacon Darwin 74f637f98d refactor(ivy): ngcc - no need to pass `isCore` explicitly (#30591)
It is part of `EntryPointBundle` so we can just use that, which
is generally already passed around.

PR Close #30591
2019-06-26 08:00:03 -07:00
Pete Bacon Darwin e943859843 refactor(ivy): ngcc - expose the `entryPoint` from the `EntryPointBundle` interface (#30591)
This will allow users of the `EntryPointBundle` to use some of the `EntryPoint`
properties without us having to pass them around one by one.

PR Close #30591
2019-06-26 08:00:03 -07:00
Pete Bacon Darwin a94bdc6793 refactor(ivy): ngcc - pass whole entry-point object to `makeEntryPointBundle()` (#30591)
This simplifies the interface somewhat but also allows us to make use of
other properties of the EntryPoint object in the future.

PR Close #30591
2019-06-26 08:00:03 -07:00
Pete Bacon Darwin 2dfd97d8f0 fix(ivy): ngcc - support bare array constructor param decorators (#30591)
Previously we expected the constructor parameter `decorators`
property to be an array wrapped in a function. Now we also support
an array not wrapped in a function.

PR Close #30591
2019-06-26 08:00:03 -07:00
Pete Bacon Darwin 869e3e8edc fix(ivy): ngcc - infer entry-point typings from format paths (#30591)
Some packages do not actually provide a `typings` field in their
package.json. But TypeScript naturally infers the typings file from
the location of the JavaScript source file.

This commit modifies ngcc to do a similar inference when finding
entry-points to process.

Fixes #28603 (FW-1299)

PR Close #30591
2019-06-26 08:00:02 -07:00
Pete Bacon Darwin 7c4c676413 feat(ivy): customize ngcc via configuration files (#30591)
There are scenarios where it is not possible for ngcc to guess the format
or configuration of an entry-point just from the files on disk.

Such scenarios include:

1) Unwanted entry-points: A spurious package.json makes ngcc think
there is an entry-point when there should not be one.

2) Deep-import entry-points: some packages allow deep-imports but do not
provide package.json files to indicate to ngcc that the imported path is
actually an entry-point to be processed.

3) Invalid/missing package.json properties: For example, an entry-point
that does not provide a valid property to a required format.

The configuration is provided by one or more `ngcc.config.js` files:

* If placed at the root of the project, this file can provide configuration
for named packages (and their entry-points) that have been npm installed
into the project.

* If published as part of a package, the file can provide configuration
for entry-points of the package.

The configured of a package at the project level will override any
configuration provided by the package itself.

PR Close #30591
2019-06-26 08:00:02 -07:00
Pete Bacon Darwin 4004d15ba5 test(ivy): ngcc refactor mock file-systems to make each spec independent (#30591)
Previously each test relied on large shared mock file-systems, which
makes it difficult to reason about what is actually being tested.

This commit breaks up these big mock file-systems into smaller more
focused chunks.

PR Close #30591
2019-06-26 08:00:02 -07:00
Pete Bacon Darwin abbbc69e64 test(ivy): ngcc - remove use of mock-fs in tests (#30591)
Now that ngcc uses a `FileSystem` throughout we no longer need
to rely upon mocking out the real file-system with mock-fs.

PR Close #30591
2019-06-26 08:00:02 -07:00
Pete Bacon Darwin 7186f9c016 refactor(ivy): implement a virtual file-system layer in ngtsc + ngcc (#30921)
To improve cross platform support, all file access (and path manipulation)
is now done through a well known interface (`FileSystem`).

For testing a number of `MockFileSystem` implementations are provided.
These provide an in-memory file-system which emulates operating systems
like OS/X, Unix and Windows.

The current file system is always available via the static method,
`FileSystem.getFileSystem()`. This is also used by a number of static
methods on `AbsoluteFsPath` and `PathSegment`, to avoid having to pass
`FileSystem` objects around all the time. The result of this is that one
must be careful to ensure that the file-system has been initialized before
using any of these static methods. To prevent this happening accidentally
the current file system always starts out as an instance of `InvalidFileSystem`,
which will throw an error if any of its methods are called.

You can set the current file-system by calling `FileSystem.setFileSystem()`.
During testing you can call the helper function `initMockFileSystem(os)`
which takes a string name of the OS to emulate, and will also monkey-patch
aspects of the TypeScript library to ensure that TS is also using the
current file-system.

Finally there is the `NgtscCompilerHost` to be used for any TypeScript
compilation, which uses a given file-system.

All tests that interact with the file-system should be tested against each
of the mock file-systems. A series of helpers have been provided to support
such tests:

* `runInEachFileSystem()` - wrap your tests in this helper to run all the
wrapped tests in each of the mock file-systems.
* `addTestFilesToFileSystem()` - use this to add files and their contents
to the mock file system for testing.
* `loadTestFilesFromDisk()` - use this to load a mirror image of files on
disk into the in-memory mock file-system.
* `loadFakeCore()` - use this to load a fake version of `@angular/core`
into the mock file-system.

All ngcc and ngtsc source and tests now use this virtual file-system setup.

PR Close #30921
2019-06-25 16:25:24 -07:00
Alex Rickabaugh 2c07820636 Revert "build(bazel): cleanup entry_point target (#31019)" (#31267)
This reverts commit cd617b15e8.

Reason: this causes failures in g3 with i18n extraction. See #31267.

PR Close #31267
2019-06-25 14:36:00 -07:00
Alex Rickabaugh 26a85a82ff Revert "build: fix build failures with worker mode cache and @types/events (#31019)" (#31267)
This reverts commit 6ba42f1da4.

Reason: this causes failures in g3 with i18n extraction. See #31267.

PR Close #31267
2019-06-25 14:36:00 -07:00
Olivier Combe ef9cb6a034 perf(ivy): chain multiple `i18nExp` calls (#31258)
Implement function chaining for `i18nExp` to reduce the output size.

FW-1391 #resolve
PR Close #31258
2019-06-25 11:26:29 -07:00
Andrew Kushnir 2aba485118 refactor(ivy): use FatalDiagnosticError to throw more descriptive errors while extracting queries information (#31123)
Prior to this commit, the logic to extract query information from class fields used an instance of regular Error class to throw an error. As a result, some useful information (like reference to a specific field) was missing. Replacing Error class with FatalDiagnosticError one makes the error more verbose that should simplify debugging.

PR Close #31123
2019-06-25 10:23:24 -07:00
Greg Magolan 6ba42f1da4 build: fix build failures with worker mode cache and @types/events (#31019)
Errors observed only in tests on CircleCI — was not reproducible locally.

```
ERROR: /home/circleci/ng/packages/http/test/BUILD.bazel:3:1: Compiling TypeScript (devmode) //packages/http/test:test_lib failed (Exit 1): tsc_wrapped failed: error executing command
  (cd /home/circleci/.cache/bazel/_bazel_circleci/9ce5c2144ecf75d11717c0aa41e45a8d/execroot/angular && \
  exec env - \
    BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1 \
    PATH=/bin:/usr/bin:/usr/local/bin \
  bazel-out/host/bin/external/npm/@bazel/typescript/bin/tsc_wrapped @@bazel-out/k8-fastbuild/bin/packages/http/test/test_lib_es5_tsconfig.json)
Execution platform: //tools:rbe_ubuntu1604-angular
Compilation failed Error: missing input digest for /home/circleci/.cache/bazel/_bazel_circleci/9ce5c2144ecf75d11717c0aa41e45a8d/execroot/angular/external/npm/node_modules/@types/events/index.d.ts.

ERROR: /home/circleci/ng/packages/benchpress/test/BUILD.bazel:3:1: Compiling TypeScript (devmode) //packages/benchpress/test:test_lib failed (Exit 1): tsc_wrapped failed: error executing command
  (cd /home/circleci/.cache/bazel/_bazel_circleci/9ce5c2144ecf75d11717c0aa41e45a8d/execroot/angular && \
  exec env - \
    BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1 \
    PATH=/bin:/usr/bin:/usr/local/bin \
  bazel-out/host/bin/external/npm/@bazel/typescript/bin/tsc_wrapped @@bazel-out/k8-fastbuild/bin/packages/benchpress/test/test_lib_es5_tsconfig.json)
Execution platform: //tools:rbe_ubuntu1604-angular
Compilation failed Error: missing input digest for /home/circleci/.cache/bazel/_bazel_circleci/9ce5c2144ecf75d11717c0aa41e45a8d/execroot/angular/external/npm/node_modules/@types/events/index.d.ts

ERROR: C:/codefresh/volume/angular/packages/compiler/test/css_parser/BUILD.bazel:3:1: Compiling TypeScript (devmode) //packages/compiler/test/css_parser:css_parser_lib failed (Exit 1):
tsc_wrapped.exe failed: error executing command
  cd C:/users/containeradministrator/_bazel_containeradministrator/zquin2l6/execroot/angular
  SET PATH=C:\msys64\usr\bin;C:\msys64\bin;C:\Windows;C:\Windows\System32;C:\Windows\System32\WindowsPowerShell\v1.0
    SET RUNFILES_MANIFEST_ONLY=1
  bazel-out/host/bin/external/npm/@bazel/typescript/bin/tsc_wrapped.exe @@bazel-out/x64_windows-fastbuild/bin/packages/compiler/test/css_parser/css_parser_lib_es5_tsconfig.json
Execution platform: @bazel_tools//platforms:host_platform
Compilation failed Error: missing input digest for C:/users/containeradministrator/_bazel_containeradministrator/zquin2l6/execroot/angular/external/npm/node_modules/@types/events/index.
d.ts
```

PR Close #31019
2019-06-25 10:21:07 -07:00
Greg Magolan cd617b15e8 build(bazel): cleanup entry_point target (#31019)
PR Close #31019
2019-06-25 10:21:07 -07:00
Ayaz Hafiz 74f4f5dfab feat(ivy): integrate indexing pipeline with NgtscProgram (#31151)
Add an IndexingContext class to store indexing information and a
transformer module to generate indexing analysis. Integrate the indexing
module with the rest of NgtscProgram and add integration tests.

Closes #30959

PR Close #31151
2019-06-24 18:47:56 -07:00
JoostK 3fb73ac62b fix(ivy): support equality operators in static interpreter (#31145)
Previously, the usage of equality operators ==, ===, != and !== was not
supported in ngtsc's static interpreter. This commit adds support for
such operators and includes tests.

Fixes #31076

PR Close #31145
2019-06-24 18:47:02 -07:00
crisbeto 23c017121e perf(ivy): chain multiple attribute instructions (#31152)
Similarly to what we did in #31078, these changes implement chaining for the `attribute` instruction.

This PR resolves FW-1390.

PR Close #31152
2019-06-24 12:33:49 -07:00
Pete Bacon Darwin 48def92cad fix(ivy): ensure that changes to component resources trigger incremental builds (#30954)
Optimizations to skip compiling source files that had not changed
did not account for the case where only a resource file changes,
such as an external template or style file.

Now we track such dependencies and trigger a recompilation
if any of the previously tracked resources have changed.

This will require a change on the CLI side to provide the list of
resource files that changed to trigger the current compilation by
implementing `CompilerHost.getModifiedResourceFiles()`.

Closes #30947

PR Close #30954
2019-06-21 10:13:46 -07:00
Alex Rickabaugh fad03c3c14 refactor: early compatibility with TypeScript 3.5 (#31174)
This commit fixes a couple of issues with TS 3.5 compatibility in order to
unblock migration of g3. Mostly 'any's are added, and there are no behavior
changes.

PR Close #31174
2019-06-20 16:42:37 -07:00
JoostK 75ac724842 fix(ivy): quote dots in directive inputs and outputs (#31146)
A temporary check is in place to determine whether a key in an object
literal needs to be quoted during emit. Previously, only the presence of
a dash caused a key to become quoted, this however is not sufficient for
@angular/flex-layout to compile properly as it has dots in its inputs.

This commit extends the check to also use quotes when a dot is present.

Fixes #30114

PR Close #31146
2019-06-19 17:57:13 -07:00
Matt Lewis 91008bd979 fix(ivy): improve error message when NgModule properties are not arrays (#30796)
PR Close #30796
2019-06-19 15:47:54 -07:00
Matt Lewis f0395836b6 fix(ivy): evaluate non existing property access as undefined (#30738)
Closes #30726

PR Close #30738
2019-06-19 15:44:05 -07:00
crisbeto 4b16d98955 perf(ivy): chain multiple property instructions (#31078)
Currently each property binding generates an instruction like this:

```
property('prop1', ctx.value1);
property('prop2', ctx.value2);
```

The problem is that we're repeating the call to `property` for each of the properties. Since the `property` instruction returns itself, we can chain all of the calls which is more compact and it looks like this:

```
property('prop1', ctx.value1)('prop2', ctx.value2);
```

These changes implement the chaining behavior for regular property bindings and for synthetic ones, however interpolated ones are still handled like before, because they use a separate instruction.

This PR resolves FW-1389.

PR Close #31078
2019-06-19 15:42:37 -07:00
Alex Eagle db08fd2607 build: enable shard_count for some jasmine tests that have many specs (#31009)
This partitions the spects across multiple processes so they run in parallel.

PR Close #31009
2019-06-18 12:11:30 -07:00
Ayaz Hafiz beaab27a49 feat(ivy): index identifiers discovered in templates (#30963)
Add support for indexing of property reads, method calls in a template.
Visit AST of template syntax expressions to extract identifiers.

Child of #30959

PR Close #30963
2019-06-18 09:50:06 -07:00
Olivier Combe 87168acf39 refactor(ivy): move `bind` instruction into `i18nExp` (#31089)
i18nExp now uses `bind` internally rather than having the compiler generate it in order to bring it in line with other functions like `textBinding` & `property`.

FW-1384 #resolve
PR Close #31089
2019-06-18 09:49:27 -07:00
JoostK 6fbfb5a159 feat(ivy): ngcc - recognize static properties on the outer symbol in ES5 (#30795)
Packages that have been compiled using an older version of TypeScript
can have their decorators at the top-level of the ES5 bundles, instead
of inside the IIFE that is emitted for the class. Before this change,
ngcc only took static property assignments inside the IIFE into account,
therefore missing the decorators that were assigned at the top-level.

This commit extends the ES5 host to look for static properties in two
places. Testcases for all bundle formats that contain ES5 have been added
to ensure that this works in the various flavours.

A patch is included to support UMD bundles. The UMD factory affects how
TypeScripts binds the static properties to symbols, see the docblock of
the patch function for more details.

PR Close #30795
2019-06-14 13:09:56 -07:00
Ayaz Hafiz 4ad323a4d6 feat(ivy): setup boilerplate for component indexing API (#30961)
Set up the skeleton for a compiler API that indexes components and their
templates on an independent indexing step.

Part of #30959

PR Close #30961
2019-06-14 10:48:12 -07:00
Pete Bacon Darwin 0c3bb6a731 fix(ivy): ngcc - capture entry-points in top-level path-mapped folders (#31027)
The `EntryPointFinder` computes the base paths to consider
when searching for entry-points. When there are `pathMappings`
provided it works out the best top level base-paths that cover all
the potential mappings.

If this computed basePath happens to coincide with an entry-point
path itself then we were missing it.

Now we check for an entry-point even at the base-path itself.

Related to https://github.com/angular/angular-cli/pull/14755

PR Close #31027
2019-06-14 10:43:59 -07:00
Paul Gschwendtner 052ef654d2 test(compiler-cli): fix failing ivy template compliance test (#30983)
Commit 58be2ff884 has been created
before c0386757b1 landed, and therefore
the newly created compliance test was using an outdated expectation.

This commit updates the compliance test to no longer contain
the outdated expectation.

PR Close #30983
2019-06-11 15:17:01 -07:00
Paul Gschwendtner 58be2ff884 fix(ivy): unable to bind to implicit receiver in embedded views (#30897)
To provide some context: The implicit receiver is part of the
parsed Angular template AST. Any property reads in bindings,
interpolations etc. read from a given object (usually the component
instance). In that case there is an _implicit_ receiver which can also
be specified explicitly by just using `this`.

e.g.

```html
<ng-template>{{this.myProperty}}</ng-template>
```

This works as expected in Ivy and View Engine, but breaks in case the
implicit receiver is not used for property reads. For example:

```html
<my-dir [myFn]="greetFn.bind(this)"></my-dir>
```

In that case the `this` will not be properly translated into the generated
template function code because the Ivy compiler currently always treats
the `ctx` variable as the implicit receiver. This is **not correct** and breaks
compatibility with View Engine. Rather we need to ensure that we retrieve
the root context for the standalone implicit receiver similar to how it works
for property reads (as seen in the example above with `this.myProperty`)

Note that this requires some small changes to the `expression_converter`
because we only want to generate the `eenextContent()` instruction if the
implicit receiver is _actually_ used/needed. View Engine determines if that is the case by recursively walking through the converted output AST and
checking for usages of the `o.variable('_co')` variable ([see here][ve_check]). This would work too for Ivy, but involves most likely more code duplication
since templates are isolated in different functions and it another pass
through the output AST for every template expression.

[ve_check]: 0d6c9d36a1/packages/compiler/src/view_compiler/view_compiler.ts (L206-L208)

Resolves FW-1366.

PR Close #30897
2019-06-11 14:29:42 -07:00
Paul Gschwendtner 230e9766f6 test(ivy): fix strict null checks failures in ngcc tests (#30967)
9d9c9e43e5 has been created a few days ago
and wasn't rebased on top of recent changes that introduces a commonjs host.

This means that tests for the commonjs host haven't been updated to work with
the changes from from #30492 and now fail in `master`.

PR Close #30967
2019-06-11 09:37:19 -07:00
Paul Gschwendtner 2b4d5c7548 fix(ivy): ngcc should process undecorated base classes (#30821)
Currently undecorated classes are intentionally not processed
with ngcc. This is causing unexpected behavior because decorator
handlers such as `base_def.ts` are specifically interested in class
definitions without top-level decorators, so that the base definition
can be generated if there are Angular-specific class members.

In order to ensure that undecorated base-classes work as expected
with Ivy, we need to run the decorator handlers for all top-level
class declarations (not only for those with decorators). This is similar
to when `ngtsc` runs decorator handlers when analyzing source-files.

Resolves FW-1355. Fixes https://github.com/angular/components/issues/16178

PR Close #30821
2019-06-11 00:19:34 +00:00
JoostK 271d2b51a9 fix(ivy): ngcc - prevent crash for packages without "main" property (#30950)
When determining the module type of a bundle pointed to by the "main"
property, ngcc needs to read the bundle to figure out if it is CommonJS
or UMD format. However, when the "main" property does not exist ngcc
would crash while determining the path to the main bundle file.

This commit fixes the crash by checking if the "main" property is present
at all, before attempting to derive a full path to the bundle file.

Fixes #30916
Fixes FW-1369

PR Close #30950
2019-06-11 00:12:03 +00:00
Alex Eagle ef0b2cc74d build: convert entry_point to label (#30627)
PR Close #30627
2019-06-11 00:03:11 +00:00
JoostK 9d9c9e43e5 feat(ivy): static evaluation of TypeScript's `__spread` helper (#30492)
The usage of array spread syntax in source code may be downleveled to a
call to TypeScript's `__spread` helper function from `tslib`, depending
on the options `downlevelIteration` and `emitHelpers`. This proves
problematic for ngcc when it is processing ES5 formats, as the static
evaluator won't be able to interpret those calls.

A custom foreign function resolver is not sufficient in this case, as
`tslib` may be emitted into the library code itself. In that case, a
helper function can be resolved to an actual function with body, such
that it won't be considered as foreign function. Instead, a reflection
host can now indicate that the definition of a function corresponds with
a certain TypeScript helper, such that it becomes statically evaluable
in ngtsc.

Resolves #30299

PR Close #30492
2019-06-10 23:53:04 +00:00
Ben Lesh c0386757b1 refactor(ivy): inherently call ɵɵselect(0) (#30830)
- Refactors compiler to stop generating `ɵɵselect(0)` instructions
- Alters template execution to always call the equivalent of `ɵɵselect(0)` before running a template in update mode
- Updates tests to not check for or call `ɵɵselect(0)`.

The goal here is to reduce the size of generated templates

PR Close #30830
2019-06-07 08:48:31 -07:00
crisbeto b51d8dd438 fix(ivy): error for empty bindings on ng-template (#30829)
Fixes Ivy throwing an error if it runs into an empty property binding on an `ng-template` (e.g. `<ng-template [something]=""></ng-template>`) by not generating an update instruction for it.

Fixes #30801.
This PR resoves FW-1356.

PR Close #30829
2019-06-05 21:26:13 -07:00
George Kalpakas ea2d453118 fix(ivy): ngcc - use spaces in overwritten `package.json` content for readability (#30831)
When ngcc processes an entrypoint, it updates `package.json` with
metadata about the processed format. Previously, it overwrote the
`package.json` with the stringified JSON object without spaces. This
made the file difficult to read (for example when looking at the file
while debugging an ngcc failure).

This commit fixes it by using spaces in the new `package.json` content.

PR Close #30831
2019-06-05 21:22:49 -07:00
Ben Lesh d1df0a94d4 refactor(ivy): remove ɵɵelementProperty instruction (#30645)
- Removes ɵɵelementProperty instruction
- Updates tests that were using it
- NOTE: There is one test under `render3/integration_spec.ts` that is commented out, and needs to be reviewed. Basically, I could not find a good why to test what it was doing, because it was doing things that I am not sure we could generate in an acceptance test.

PR Close #30645
2019-06-05 09:04:43 -07:00
JoostK 456f2e70af fix(ivy): type checking - handle $implicit ng-template variables (#30675)
When an `ng-template` element has a variable declaration without a value,
it is assigned the value of the `$implicit` property in the embedded view's
context. The template compiler inserts a property access to `$implicit` for
template variables without a value, however the type-check code generation
logic did not. This resulted in incorrect type-checking code being generated.

Fixes FW-1326

PR Close #30675
2019-06-04 12:01:18 -07:00
JoostK 4da5e9a156 fix(ivy): type checking - apply attribute to property name mapping (#30675)
Some HTML attributes don't correspond to their DOM property name, in which
case the runtime will apply the appropriate transformation when assigning
a property using its attribute name. One example of this is the `for`
attribute, for which the DOM property is named `htmlFor`.

The type-checking machinery in ngtsc must also take this mapping into
account, as it generates type-check code in which unclaimed property bindings
are assigned to properties of (subtypes of) `HTMLElement`.

Fixes #30607
Fixes FW-1327

PR Close #30675
2019-06-04 12:01:18 -07:00
Ben Lesh b4e68025f8 refactor(ivy): add ɵɵupdateSyntheticHostBinding command (#30670)
- Refactors `ɵɵcomponentHostSyntheticProperty` into `ɵɵupdateSyntheticHostBinding`, to better align it with other new instructions.

PR Close #30670
2019-06-03 09:00:13 -07:00
Paul Gschwendtner aca339e864 fix(ivy): unable to project into multiple slots with default selector (#30561)
With View engine it was possible to declare multiple projection
definitions and to programmatically project nodes into the slots.

e.g.

```html
<ng-content></ng-content>
<ng-content></ng-content>
```

Using `ViewContainerRef#createComponent` allowed projecting
nodes into one of the projection defs (through index)

This no longer works with Ivy as the `projectionDef` instruction only
retrieves a list of selectors instead of also retrieving entries for
reserved projection slots which appear when using the default
selector multiple times (as seen above).

In order to fix this issue, the Ivy compiler now passes all
projection slots to the `projectionDef` instruction. Meaning that
there can be multiple projection slots with the same wildcard
selector. This allows multi-slot projection as seen in the
example above, and it also allows us to match the multi-slot node
projection order from View Engine (to avoid breaking changes).

It basically ensures that Ivy fully matches the View Engine behavior
except of a very small edge case that has already been discussed
in FW-886 (with the conclusion of working as intended).

Read more here: https://hackmd.io/s/Sy2kQlgTE

PR Close #30561
2019-05-31 09:52:32 -07:00
Olivier Combe 53c6b78c51 feat(ivy): add `AttributeMarker.I18n` for i18n attributes (#30402)
`i18nAttributes` instructions always occur after the element instruction. This means that we need to treat `i18n-` attributes differently.
By defining a specific `AttributeMarker` we can ensure that we won't trigger directive inputs with untranslated attribute values.

FW-1332 #resolve
PR Close #30402
2019-05-30 16:39:24 -04:00
Olivier Combe 91699259b2 fix(ivy): trigger directive inputs with i18n translations (#30402)
Changed runtime i18n to define attributes with bindings, or matching directive inputs/outputs as element properties as we are supposed to do in Angular.
This PR fixes the issue where directive inputs wouldn't be trigged.

FW-1315 #resolve
PR Close #30402
2019-05-30 16:39:24 -04:00
Alex Rickabaugh b61784948a fix(ivy): template inputs/outputs should not be bound in template scope (#30669)
The R3TargetBinder "binds" an Angular template AST, computing semantic
information regarding the template and making it accessible.

One of the binding passes previously had a bug, where for the following
template:

<div *ngIf="foo as foo"></div>

which desugars to:

<ng-template ngIf [ngIf]="foo" let-foo="ngIf">
  <div></div>
</ng-template>

would have the `[ngIf]` binding processed twice - in both the scope which
contains the `<ng-template>` and the scope inside the template. The bug
arises because during the latter, `foo` is a variable defined by `let-foo`,
and so the R3TargetBinder would incorrectly learn that `foo` inside `[ngIf]`
maps to that variable.

This commit fixes the bug by only processing inputs, outputs, and
templateAttrs from `Template`s in the outer scope.

PR Close #30669
2019-05-30 15:17:07 -04:00
Andrew Kushnir 7a0f8ac36c fix(ivy): generate explicit type annotation for NgModuleFactory calls in ngfactories (#30708)
Prior to this commit there were no explicit types setup for NgModuleFactory calls in ngfactories, so TypeScript inferred the type based on a given call. In some cases (when generic types were used for Components/Directives) that turned out to be problematic, so we add explicit typing for NgModuleFactory calls.

PR Close #30708
2019-05-30 15:09:56 -04:00
Olivier Combe 5e0f982961 feat(ivy): use i18n locale data to determine the plural form of ICU expressions (#29249)
Plural ICU expressions depend on the locale (different languages have different plural forms). Until now the locale was hard coded as `en-US`.
For compatibility reasons, if you use ivy with AOT and bootstrap your app with `bootstrapModule` then the `LOCALE_ID` token will be set automatically for ivy, which is then used to get the correct plural form.
If you use JIT, you need to define the `LOCALE_ID` provider on the module that you bootstrap.
For `TestBed` you can use either `configureTestingModule` or `overrideProvider` to define that provider.
If you don't use the compat mode and start your app with `renderComponent` you need to call `ɵsetLocaleId` manually to define the `LOCALE_ID` before bootstrap. We expect this to change once we start adding the new i18n APIs, so don't rely on this function (there's a reason why it's a private export).
PR Close #29249
2019-05-30 15:09:02 -04:00
Matias Niemelä 82682bb93f refactor(ivy): enable sanitization support for the new styling algorithm (#30667)
This patch is one of the final patches to refactor the styling algorithm
to be more efficient, performant and less complex.

This patch enables sanitization support for map-based and prop-based
style bindings.

PR Close #30667
2019-05-30 01:03:39 -04:00
Ben Lesh dd0815095f feat(ivy): add ɵɵtextInterpolateX instructions (#30011)
- `ɵɵtextBinding(..., ɵɵinterpolationX())` instructions will now just be `ɵɵtextInterpolate(...)` instructions

PR Close #30011
2019-05-29 12:38:58 -04:00
Alex Rickabaugh 84dd2679a9 fix(core): require 'static' flag on queries in typings (#30639)
This commit makes the static flag on @ViewChild and @ContentChild required.

BREAKING CHANGE:

In Angular version 8, it's required that all @ViewChild and @ContentChild
queries have a 'static' flag specifying whether the query is 'static' or
'dynamic'. The compiler previously sorted queries automatically, but in
8.0 developers are required to explicitly specify which behavior is wanted.
This is a temporary requirement as part of a migration; see
https://angular.io/guide/static-query-migration for more details.

@ViewChildren and @ContentChildren queries are always dynamic, and so are
unaffected.

PR Close #30639
2019-05-24 16:55:00 -04:00
Kara Erickson 214ae0ea4c test(compiler): update examples and compiler tests (#30626)
PR Close #30626
2019-05-23 10:31:32 -07:00
Ben Lesh 2cdbe9b2ef refactor(ivy): ensure new attribute instructons are available in JIT (#30503)
PR Close #30503
2019-05-22 16:30:29 -07:00
Ben Lesh 988afad2af refactor(ivy): generate new ɵɵattribute instruction in host bindings (#30503)
PR Close #30503
2019-05-22 16:30:29 -07:00
Ben Lesh 7555a46e23 refactor(ivy): add new attribute interpolation instructions (#30503)
PR Close #30503
2019-05-22 16:30:28 -07:00
Ben Lesh 38d7acee4d refactor(ivy): add new ɵɵattribute instruction (#30503)
- adds the ɵɵattribute instruction
- adds compilation handling for Δattribute instruction
- updates tests

PR Close #30503
2019-05-22 16:30:28 -07:00
Pete Bacon Darwin e20b92ba37 feat(ivy): ngcc - turn on CommonJS support (#30200)
PR Close #30200
2019-05-22 16:24:15 -07:00
Pete Bacon Darwin c7a9987067 feat(ivy): ngcc - implement CommonJsRenderingFormatter (#30200)
PR Close #30200
2019-05-22 16:24:15 -07:00
Pete Bacon Darwin 1bdec3ed6a feat(ivy): ngcc - implement CommonJsDependencyHost (#30200)
PR Close #30200
2019-05-22 16:24:15 -07:00
Pete Bacon Darwin 620cd5c148 feat(ivy): ngcc - implement `CommonJsReflectionHost` (#30200)
PR Close #30200
2019-05-22 16:24:15 -07:00
Pete Bacon Darwin 76391f8999 fix(ivy): use `ReflectionHost` in `AbsoluteModuleStrategy` (#30200)
The AbsoluteModuleStrategy in ngtsc assumed that the source code is
formatted as TypeScript with regards to module exports.

In ngcc this is not always the case, so this commit changes
`AbsoluteModuleStrategy` so that it relies upon a `ReflectionHost`  to
compute the exports of a module.

PR Close #30200
2019-05-22 16:24:14 -07:00
Andrew Kushnir 02523debe5 fix(ivy): handle pipes in i18n attributes properly (#30573)
Prior to this change we processed binding expression (including bindings with pipes) in i18n attributes before we generate update instruction. As a result, slot offsets for pipeBind instructions were calculated incorrectly. Now we perform binding expression processing when we generate "update block" instructions, so offsets are calculated correctly.

PR Close #30573
2019-05-22 16:23:18 -07:00
Paul Gschwendtner 70fd4300f4 test(compiler-cli): compliance tests not always reporting test failure (#30597)
Currently the `@angular/compiler-cli` compliance tests sometimes do
not throw an exception if the expected output does not match the
generated JavaScript output. This can happen for the following cases:

1. Expected code includes character that is not part of known alphabet
    (e.g. `Δ` is still used in a new compliance test after rebasing a PR)
2. Expected code asserts that a string literal matches a string with
    escaped quotes. e.g. expects `const $var$ = "\"quoted\"";`)

PR Close #30597
2019-05-22 16:22:52 -07:00
janith c79bffaacb docs: remove gender prefixes from examples (#29972)
PR Close #29972
2019-05-20 16:42:59 -07:00
Ben Lesh d7eaae6f22 refactor(ivy): Move instructions back to ɵɵ (#30546)
There is an encoding issue with using delta `Δ`, where the browser will attempt to detect the file encoding if the character set is not explicitly declared on a `<script/>` tag, and Chrome will find the `Δ` character and decide it is window-1252 encoding, which misinterprets the `Δ` character to be some other character that is not a valid JS identifier character

So back to the frog eyes we go.

```
    __
   /ɵɵ\
  ( -- ) - I am ineffable. I am forever.
 _/    \_
/  \  /  \
==  ==  ==
```

PR Close #30546
2019-05-20 16:37:47 -07:00
Alan a39f4e2301 test: fix paths tests to work cross platform (#30472)
In Windows when `/test.txt` is resolved it will be resolved to `[DRIVE]:/test.txt`

PR Close #30472
2019-05-17 13:34:11 -07:00
Pete Bacon Darwin eda09e69ea fix(ivy): ngtsc - do not wrap arguments unnecessarily (#30349)
Previously we defensively wrapped expressions in case they ran afoul of
precedence rules. For example, it would be easy to create the TS AST structure
Call(Ternary(a, b, c)), but might result in printed code of:

```
a ? b : c()
```

Whereas the actual structure we meant to generate is:

```
(a ? b : c)()
```

However the TypeScript renderer appears to be clever enough to provide
parenthesis as necessary.

This commit removes these defensive paraenthesis in the cases of binary
and ternary operations.

FW-1273

PR Close #30349
2019-05-17 09:55:46 -07:00
JoostK 0937062a64 fix(ivy): type-checking should infer string type for interpolations (#30177)
Previously, interpolations were generated into TCBs as a comma-separated
list of expressions, letting TypeScript infer the type of the expression
as the type of the last expression in the chain. This is undesirable, as
interpolations always result in a string type at runtime. Therefore,
type-checking of bindings such as `<img src="{{ link }}"/>` where `link`
is an object would incorrectly report a type-error.

This commit adjusts the emitted TCB code for interpolations, where a
chain of string concatenations is emitted, starting with the empty string.
This ensures that the inferred type of the interpolation is of type string.

PR Close #30177
2019-05-17 09:55:11 -07:00
JoostK 6f073885b0 refactor(ivy): translate template nodes to typescript using a visitor (#30177)
PR Close #30177
2019-05-17 09:55:11 -07:00
Pete Bacon Darwin 73e3f565e0 test(ivy): ngcc - fix tests to work on Windows (#30520)
PR Close #30520
2019-05-16 13:32:02 -07:00
Pete Bacon Darwin 757d4c33df refactor(ivy): ngcc - use `.has()` to check Map membership (#25445)
Previously we were relying upon the `.get()` method to return `undefined`
but it is clearer and safer to always check with `.has()` first.

PR Close #25445
2019-05-16 12:11:05 -07:00
Pete Bacon Darwin edd775eabc feat(ivy): ngcc - implement UmdDependencyHost (#25445)
The dependency resolution that works out the order in which
to process entry-points must also understand UMD formats.

PR Close #25445
2019-05-16 12:11:04 -07:00
Pete Bacon Darwin c613596658 fix(ivy): ngcc - separate typings rendering from src rendering (#25445)
Previously the same `Renderer` was used to render typings (.d.ts)
files. But the new `UmdRenderer` is not able to render typings files
correctly.

This commit splits out the typings rendering from the src rendering.
To achieve this the previous renderers have been refactored from
sub-classes of the abstract `Renderer` class to  classes that implement
the `RenderingFormatter` interface, which are then passed to the
`Renderer` and `DtsRenderer` to modify its rendering behaviour.

Along the way a few utility interfaces and classes have been moved
around and renamed for clarity.

PR Close #25445
2019-05-16 12:11:04 -07:00
Pete Bacon Darwin f4655ea98a feat(ivy): ngcc - turn on UMD processing (#25445)
PR Close #25445
2019-05-16 12:11:04 -07:00
Pete Bacon Darwin f6aa60c03c feat(ivy): ngcc - implement `UmdRenderer` (#25445)
PR Close #25445
2019-05-16 12:11:04 -07:00
Pete Bacon Darwin 7fec1771fc feat(ivy): ngcc - implement `UmdReflectionHost` (#25445)
PR Close #25445
2019-05-16 12:11:04 -07:00
Pete Bacon Darwin c9b588b349 feat(ivy): ngtsc - support namespaced `forwardRef` calls (#25445)
In some cases the `forwardRef` helper has been imported via a namespace,
e.g. `core.forwardRef(...)`.

This commit adds support for unwrapping such namespaced imports when
ngtsc is statically evaluating code.

PR Close #25445
2019-05-16 12:11:04 -07:00
Pete Bacon Darwin 37f69eddc7 test(ivy): ngcc - remove unnecessary code (#25445)
PR Close #25445
2019-05-16 12:11:04 -07:00
Pete Bacon Darwin 0fa72a8bc8 refactor(ivy): ngcc - fake core and tslib should be typings files (#25445)
Previously these fake files were full TypeScript source
files (`.ts`) but this is not necessary as we only need the
typings not the implementation.

PR Close #25445
2019-05-16 12:11:04 -07:00
Pete Bacon Darwin 48b77459ef refactor(ivy): ngcc - abstract how module statements are found (#25445)
This will be important for UMD support.

PR Close #25445
2019-05-16 12:11:04 -07:00
Pete Bacon Darwin 989bfd2e97 fix(ivy): ngcc - support namespaced identifiers (#25445)
In UMD formats, imports are always namespaced. This commit makes
ngcc more tolerant of such structures.

PR Close #25445
2019-05-16 12:11:04 -07:00
Pete Bacon Darwin aeec66b657 test(ivy): enhance the in-memory-typescript helper (#25445)
The `getDeclaration()` function now searches down into the AST for
matching nodes, which is needed for UMD testing.

PR Close #25445
2019-05-16 12:11:04 -07:00
Pete Bacon Darwin e68490c5e4 test(ivy): fix ESM5 test code to use `var` rather than `const` (#25445)
PR Close #25445
2019-05-16 12:11:04 -07:00
Pete Bacon Darwin 95c5b1a7f6 refactor(ivy): use a named type for ImportManager import structures (#25445)
Previously we were using an anonymous type `{specifier: string; qualifier: string;}`
throughout the code base. This commit gives this type a name and ensures it
is only defined in one place.

PR Close #25445
2019-05-16 12:11:03 -07:00
Pete Bacon Darwin 8e201f713a test(ivy): ngcc - check the actual file that is passed to `renderImports` (#25445)
Previously we were just checking that the object was "any" object but now
we check that it is the file object that we expected.

PR Close #25445
2019-05-16 12:11:03 -07:00
JoostK 1b613c3ebf fix(ivy): evaluate external declaration usages as dynamic (#30247)
Previously, ngtsc would fail to evaluate expressions that access properties
from e.g. the `window` object. This resulted in hard to debug error messages
as no indication on where the problem originated was present in the output.

This commit cleans up the handling of unknown property accesses, such that
evaluating such expressions no longer fail but instead result in a `DynamicValue`.

Fixes #30226

PR Close #30247
2019-05-16 11:46:00 -07:00
JoostK e9ead2bc09 feat(ivy): more accurate type narrowing for `ngIf` directive (#30248)
A structural directive can specify a template guard for an input, such that
the type of that input's binding can be narrowed based on the guard's return
type. Previously, such template guards could only be methods, of which an
invocation would be inserted into the type-check block (TCB). For `NgIf`,
the template guard narrowed the type of its expression to be `NonNullable`
using the following declaration:

```typescript
export declare class NgIf {
  static ngTemplateGuard_ngIf<E>(dir: NgIf, expr: E): expr is NonNullable<E>
}
```

This works fine for usages such as `*ngIf="person"` but starts to introduce
false-positives when e.g. an explicit non-null check like
`*ngIf="person !== null"` is used, as the method invocation in the TCB
would not have the desired effect of narrowing `person` to become
non-nullable:

```typescript
if (NgIf.ngTemplateGuard_ngIf(directive, ctx.person !== null)) {
  // Usages of `ctx.person` within this block would
  // not have been narrowed to be non-nullable.
}
```

This commit introduces a new strategy for template guards to allow for the
binding expression itself to be used as template guard in the TCB. Now,
the TCB generated for `*ngIf="person !== null"` would look as follows:

```typescript
if (ctx.person !== null) {
  // This time `ctx.person` will successfully have
  // been narrowed to be non-nullable.
}
```

This strategy can be activated by declaring the template guard as a
property declaration with `'binding'` as literal return type.

See #30235 for an example where this led to a false positive.

PR Close #30248
2019-05-16 09:48:40 -07:00
Ben Lesh cf86ed7b29 refactor(ivy): migrate ɵɵ prefix back to Δ (#30362)
Now that issues are resolved with Closure compiler, we can move back to our desired prefix of `Δ`.

PR Close #30362
2019-05-14 16:52:15 -07:00
Alan c7f9a95a3f test: fix tests in windows ci (#30451)
PR Close #30451
2019-05-14 10:35:55 -07:00
Alex Eagle 06efc340b6 build: update rules_nodejs and clean up bazel warnings (#30370)
Preserve compatibility with rollup_bundle rule.
Add missing npm dependencies, which are now enforced by the strict_deps plugin in tsc_wrapped

PR Close #30370
2019-05-14 10:08:45 -07:00
Alan Agius 18c0ba5272 test: fix ngcc integration tests in windows (#30297)
```
//packages/compiler-cli/ngcc/test:integration
```

Partially addresses #29785

PR Close #30297
2019-05-13 11:26:56 -07:00
Alan 1bd4891c9a test: fix ngcc unit tests in windows (#30297)
```
//packages/compiler-cli/ngcc/test:test
```

Partially addresses #29785

PR Close #30297
2019-05-13 11:26:56 -07:00
Alan 3a7bfc721e fix(ivy): handle windows drives correctly (#30297)
At the moment the module resolver will end up in an infinite loop in Windows because we are assuming that the root directory is always `/` however in windows this can be any drive letter example `c:/` or `d:/` etc...

With this change we also resolve the drive letter in windows, when using `AbsoluteFsPath.from` for consistence so under `/foo` will be converted to `c:/foo` this is also needed because of relative paths with different drive letters.

PR Close #30297
2019-05-13 11:26:55 -07:00
Kristiyan Kostadinov f74373f2dd fix(ivy): align NgModule registration timing with ViewEngine (#30244)
Currently in Ivy `NgModule` registration happens when the class is declared, however this is inconsistent with ViewEngine and requires extra generated code. These changes remove the generated code for `registerModuleFactory`, pass the id through to the `ngModuleDef` and do the module registration inside `NgModuleFactory.create`.

This PR resolves FW-1285.

PR Close #30244
2019-05-13 11:13:25 -07:00
Alan Agius 2f35dbfd3b test: fix ngtsc tests in windows (#30146)
This commit fixes the following test target in windows

```
//packages/compiler-cli/test/ngtsc:ngtsc
```

PR Close #30146
2019-05-13 11:06:12 -07:00
Alan Agius 31df5139c5 test: fix several Bazel compiler tests in windows (#30146)
```
//packages/compiler-cli/test:ngc
//packages/compiler/test:test
```

This also address `node_modules` to the ignored paths for ngc compiler as otherwise the `ready` is never fired

Partially addresses #29785

PR Close #30146
2019-05-13 11:06:12 -07:00
Pete Bacon Darwin fbff03b476 feat(ivy): skip analysis of unchanged components (#30238)
Now that the dependent files and compilation scopes are being tracked in
the incremental state, we can skip analysing and emitting source files if
none of their dependent files have changed since the last compile.

The computation of what files (and their dependencies) are unchanged is
computed during reconciliation.

This commit also removes the previous emission skipping logic, since this
approach covers those cases already.

PR Close #30238
2019-05-10 12:10:40 -07:00
Pete Bacon Darwin 411524d341 feat(ivy): track compilation scope dependencies for components (#30238)
To support skipping analysis of a file containing a component
we need to know that none of the declarations that might affect
its ngtsc compilation have not changed. The files that we need to
check are those that contain classes from the `CompilationScope`
of the component. These classes are already tracked in the
`LocalModuleScopeRegistry`.

This commit modifies the `IvyCompilation` class to record the
files that are in each declared class's `CompilationScope` via
a new method, `recordNgModuleScopeDependencies()`, that is called
after all the handlers have been "resolved".

Further, if analysis is skipped for a declared class, then we need
to recover the analysis from the previous compilation run. To
support this, the `IncrementalState` class has been updated to
expose the `MetadataReader` and `MetadataRegistry` interfaces.
This is included in the `metaRegistry` object to capture these analyses,
and also in the `localMetaReader` as a fallback to use if the
current compilation analysis was skipped.

PR Close #30238
2019-05-10 12:10:40 -07:00
Pete Bacon Darwin 0a0b4c1d8f feat(ivy): track file dependencies due to partial evaluation (#30238)
As part of incremental compilation performance improvements, we need
to track the dependencies of files due to expressions being evaluated by
the `PartialEvaluator`.

The `PartialEvaluator` now accepts a `DependencyTracker` object, which is
used to track which files are visited when evaluating an expression.
The interpreter computes this `originatingFile` and stores it in the evaluation
`Context` so it can pass this to the `DependencyTracker.

The `IncrementalState` object implements this interface, which allows it to be
passed to the `PartialEvaluator` and so capture the file dependencies.

PR Close #30238
2019-05-10 12:10:40 -07:00
Pete Bacon Darwin 5887ddfa3c refactor(ivy): clean up ngtsc code (#30238)
No behavioural changes.

PR Close #30238
2019-05-10 12:10:40 -07:00
Matias Niemelä d8665e639b refactor(ivy): drop `element` prefixes for all styling-related instructions (#30318)
This is the final patch to migrate the Angular styling code to have a
smaller instruction set in preparation for the runtime refactor. All
styling-related instructions now work both in template and hostBindings
functions and do not use `element` as a prefix for their names:

BEFORE:
  elementStyling()
  elementStyleProp()
  elementClassProp()
  elementStyleMap()
  elementClassMap()
  elementStylingApply()

AFTER:
  styling()
  styleProp()
  classProp()
  styleMap()
  classMap()
  stylingApply()

PR Close #30318
2019-05-08 15:33:39 -07:00
Matias Niemelä c016e2c4ec refactor(ivy): migrate all host-specific styling instructions to element-level styling instructions (#30336)
This patch removes all host-specific styling instructions in favor of
using element-level instructions instead. Because of the previous
patches that made sure `select(n)` worked between styling calls, all
host level instructions are not needed anymore. This patch changes each
of those instruction calls to use any of the `elementStyling*`,
`elementStyle*` and `elementClass*` styling instructions instead.

PR Close #30336
2019-05-08 14:54:44 -07:00
Matias Niemelä 7c8a62d64d refactor(ivy): remove elementIndex param from all element-level styling instructions (#30313)
This patch is one commit of many patches that will unify all styling instructions
across both template-level bindings and host-level bindings. This patch in particular
removes the `elementIndex` param because it is already set prior to each styling
instruction via the `select(n)` instruction.

PR Close #30313
2019-05-08 09:18:19 -07:00
Matias Niemelä 345a3cd9aa fix(ivy): ensure `select(n)` instructions are always generated around style/class bindings (#30311)
Prior to this patch, the `select(n)` instruction would only be generated
when property bindings are encountered which meant that styling-related
bindings were skipped. This patch ensures that all styling-related bindings
(i.e. class and style bindings) are always prepended with a `select()`
instruction prior to being generated in AOT.

PR Close #30311
2019-05-07 14:56:17 -07:00
Matias Niemelä be8fbac942 refactor(ivy): break apart stylingMap into styleMap and classMap instructions (#30293)
This patch breaks up the existing `elementStylingMap` into
`elementClassMap` and `elementStyleMap` instructions. It also breaks
apart `hostStlyingMap` into `hostClassMap` and `hostStyleMap`
instructions. This change allows for better tree-shaking and reduces
the complexity of the styling algorithm code for `[style]` and `[class]`
bindings.

PR Close #30293
2019-05-07 11:06:04 -07:00
Pete Bacon Darwin c59717571e fix(ivy): ngcc - handle missing entry-point dependencies better (#30270)
If an entry-point has a missing dependency then all the entry-points
that would have pointed to that dependency are also removed from
the dependency graph.

Previously we were still processing the dependencies of an entry-point
even if it had already been removed from the graph because it depended
upon a missing dependency that had previously been removed due to another
entry-point depending upon it.

This caused the dependency processing to crash rather than gracefully
logging and handling the missing invalid entry-point.

Fixes #29624

PR Close #30270
2019-05-07 10:24:48 -07:00
Pete Bacon Darwin f5b2ae616f feat(ivy): ngcc - add debug message for invalid entry-points (#30270)
PR Close #30270
2019-05-07 10:24:48 -07:00
Alan 1660b34e2d test: fix several bazel compiler-cli tests in windows (#30189)
```
//packages/compiler-cli/integrationtest:integrationtest
//packages/compiler-cli/test/compliance:compliance
```

Partially addresses #29785

PR Close #30189
2019-05-07 10:21:36 -07:00
Filipe Silva 60a8888b4f fix(compiler-cli): log ngcc skipping messages as debug instead of info (#30232)
Related to https://github.com/angular/angular-cli/issues/14194, https://github.com/angular/angular-cli/pull/14320

PR Close #30232
2019-05-06 09:24:15 -07:00
Alan Agius 4537816c1d docs: fix `targetEntryPointPath` description (#30237)
PR Close #30237
2019-05-06 09:21:23 -07:00
Pete Bacon Darwin 5b80ab372d fix(ivy): use `CompilerHost.resolveModuleNames()` if available (#30017)
Sometimes we need to override module resolution behaviour.
We do this by implementing the optional method `resolveModuleNames()`
on `CompilerHost`.

This commit ensures that we always try this method first before falling
back to the standard `ts.resolveModuleName`

PR Close #30017
2019-05-01 15:41:53 -07:00
JoostK 638ba4a2cf fix(ivy): ngcc - prefer JavaScript source files when resolving module imports (#30017)
Packages that do not follow APF may have the declaration files in the same
directory as one source format, typically ES5. This is problematic for ngcc,
as it needs to create a TypeScript program with all JavaScript sources of
an entry-point, whereas TypeScript's module resolution mechanism would have
resolved an internal module import to the external facing .d.ts declaration
file, instead of the JavaScript source file. This behavior results in the
program to be analysed being incomplete.

This commit introduces a custom compiler host that recognizes the above
scenario and rewires the resolution of a .d.ts declaration file to its
JavaScript counterpart, if applicable.

Fixes #29939

PR Close #30017
2019-05-01 15:41:53 -07:00
Kristiyan Kostadinov 68ff2cc323 fix(ivy): host bindings and listeners not being inherited from undecorated classes (#30158)
Fixes `HostBinding` and `HostListener` declarations not being inherited from base classes that don't have an Angular decorator.

This PR resolves FW-1275.

PR Close #30158
2019-04-29 13:35:14 -07:00
Pete Bacon Darwin 029a93963a refactor(ivy): ngcc - remove the last remnants of `path` and `canonical-path` (#29643)
The ngcc code now uses `AbsoluteFsPath` and `PathSegment` to do all its
path manipulation.

PR Close #29643
2019-04-29 12:37:21 -07:00
Pete Bacon Darwin 20898f9f4f test(ivy): ngcc - tighten up typings in Esm5ReflectionHost specs (#29643)
PR Close #29643
2019-04-29 12:37:21 -07:00
Pete Bacon Darwin ef861958a9 refactor(ivy): ngcc - add MockFileSystem (#29643)
PR Close #29643
2019-04-29 12:37:21 -07:00
Pete Bacon Darwin 16d7dde2ad refactor(ivy): ngcc - implement abstract FileSystem (#29643)
This commit introduces a new interface, which abstracts access
to the underlying `FileSystem`. There is initially one concrete
implementation, `NodeJsFileSystem`, which is simply wrapping the
`fs` library of NodeJs.

Going forward, we can provide a `MockFileSystem` for test, which
should allow us to stop using `mock-fs` for most of the unit tests.
We could also implement a `CachedFileSystem` that may improve the
performance of ngcc.

PR Close #29643
2019-04-29 12:37:21 -07:00
Pete Bacon Darwin 1fd2cc6340 refactor(ivy): ngcc - move the dependency resolving stuff around (#29643)
For UMD/RequireJS support we will need to have multiple
`DependencyHost` implementations. This commit  prepares the
ground for that.

PR Close #29643
2019-04-29 12:37:21 -07:00
Pete Bacon Darwin 5ced8fbbd5 feat(ivy): ngcc - support additional paths to process (#29643)
By passing a `pathMappings` configuration (a subset of the
`ts.CompilerOptions` interface), we can instuct ngcc to process
additional paths outside the `node_modules` folder.

PR Close #29643
2019-04-29 12:37:21 -07:00
Pete Bacon Darwin 23152c37c8 feat(ivy): add helper methods to AbsoluteFsPath (#29643)
PR Close #29643
2019-04-29 12:37:21 -07:00
Pete Bacon Darwin 4a2405929c refactor(ivy): ngcc - implement new module resolver (#29643)
When working out the dependencies between entry-points
ngcc must parse the import statements and then resolve the
import path to the actual file.  This is complicated because module
resolution is not trivial.

Previously ngcc used the node.js `require.resolve`, with some
hacking to resolve modules. This change refactors the `DependencyHost`
to use a new custom `ModuleResolver`, which is optimized for this use
case.

Moreover, because we are in full control of the resolution,
we can support TS `paths` aliases, where not all imports come from
`node_modules`. This is the case in some CLI projects where there are
compiled libraries that are stored locally in a `dist` folder.
See //FW-1210.

PR Close #29643
2019-04-29 12:37:21 -07:00
Pete Bacon Darwin eef4ca5dd3 refactor(ivy): ngcc - tidy up `mainNgcc` (#29643)
PR Close #29643
2019-04-29 12:37:20 -07:00
Pete Bacon Darwin 321da5cc83 refactor(compiler-cli): ngcc - track non-Angular entry-points (#29643)
Previously we completely ignored entry-points that had not been
compiled with Angular, since we do not need to compile them
with ngcc. But this makes it difficult to reason about dependencies
between entry-points that were compiled with Angular and those that
were not.

Now we do track these non-Angular compiled entry-points but they
are marked as `compiledByAngular: false`.

PR Close #29643
2019-04-29 12:37:20 -07:00
Pete Bacon Darwin c2cf500da9 test(ivy): ngcc - check private dependency in integration test (#29643)
The test now attempts to compile an entry-point (@angular/common/http/testing)
that has a transient "private" dependency. A private dependency is one that is
only visible by looking at the compiled JS code, rather than the generated TS
typings files.

This proves that we can't rely on typings files alone for computing the
dependencies between entry-points.

PR Close #29643
2019-04-29 12:37:20 -07:00
Pete Bacon Darwin 4c03208537 refactor(ivy): ngcc - tidy up `DependencyResolver` helper method (#29643)
This method was poorly named for what it does, and did not have a
return type.

PR Close #29643
2019-04-29 12:37:20 -07:00
Pete Bacon Darwin 78b5bd5174 refactor(compiler-cli): ngcc - remove unnecessary `sourcePath` parameters (#29643)
The `Transformer` and `Renderer` classes do not
actually need a `sourcePath` value as by the time
they are doing their work we are only working directly
with full absolute paths.

PR Close #29643
2019-04-29 12:37:20 -07:00
Alan Agius e4b81a6957 test: fix language service tests in windows (#30113)
This PR parially addresses #29785 and fixes ` //packages/language-service/test:test`

PR Close #30113
2019-04-26 16:34:22 -07:00
MaksPob 2ae26ce20b build: upgrade yargs package to 13.1.0 (#29722)
Update yargs, because the old version was transitively (via os-local) depending on a vulnerable version of the mem package: https://app.snyk.io/vuln/npm:mem:20180117

PR Close #29722
2019-04-26 16:29:29 -07:00
Ben Lesh f3ce8eeb83 fix(ivy): property bindings use correct indices (#30129)
- Extracts and documents code that will be common to interpolation instructions
- Ensures that binding indices are updated at the proper time during compilation
- Adds additional tests

Related #30011

PR Close #30129
2019-04-26 11:09:51 -07:00
Alex Rickabaugh d316a18dc6 fix(ivy): don't include query fields in type constructors (#30094)
Previously, ngtsc included query fields in the list of fields which can
affect the type of a directive via its type constructor. This feature
however has yet to be built, and View Engine in default mode does not
do this inference.

This caused an unexpected bug where private query fields (which should be
an error but are allowed by View Engine) cause the type constructor
signature to be invalid. This commit fixes that issue by disabling the
logic to include query fields.

PR Close #30094
2019-04-24 17:10:21 -07:00
Alex Rickabaugh 79141f4424 fix(ivy): generate default 'any' types for type ctor generic params (#30094)
ngtsc generates type constructors which infer the type of a directive based
on its inputs. Previously, a bug existed where this inference would fail in
the case of 'any' input values. For example, the inference of NgForOf fails
when an 'any' is provided, as it causes TypeScript to attempt to solve:

T[] = any

In this case, T gets inferred as {}, the empty object type, which is not
desirable.

The fix is to assign generic types in type constructors a default type of
'any', which TypeScript uses instead of {} when inference fails.

PR Close #30094
2019-04-24 17:10:21 -07:00
Alex Rickabaugh 3938563565 fix(ivy): don't reuse a ts.Program more than once in ngtsc (#30090)
ngtsc previously could attempt to reuse the main ts.Program twice. This
occurred when template type-checking was enabled and then an incremental
build was performed. This breaks a TypeScript invariant - ts.Programs can
only be reused once.

The creation of the template type-checking program reuses the main program,
rendering it moot. Then, on the next incremental build the main program
would be subject to reuse again, which would crash inside TypeScript.

This commit fixes the issue by reusing the template type-checking program
from the previous run on the next incremental build. Since under normal
circumstances the files in the type-checking program aren't changed, this
should be just as fast.

Testing strategy: a test is added in the incremental_spec which validates
that program reuse with type-checking turned on does not crash the compiler.

Fixes #30079

PR Close #30090
2019-04-24 11:41:21 -07:00
Kristiyan Kostadinov ae93ba1140 fix(ivy): don't throw error when evaluating function with more than one statement (#30061)
Resolves functions with more than one statement to unknown dynamic values, rather than throwing an error.

PR Close #30061
2019-04-24 11:32:56 -07:00
Pete Bacon Darwin 0fa76219ac refactor(ivy): ngcc - simplify `NewEntryPointFileWriter` code (#30085)
The lines that compute the paths for this writer were confusing.
This commit simplifies and clarifies what is being computed.

PR Close #30085
2019-04-24 10:49:31 -07:00
Pete Bacon Darwin 6af9b8fb92 fix(ivy): ngcc - do not copy external files when writing bundles (#30085)
Only the JS files that are actually part of the entry-point
should be copied to the new entry-point folder in the
`NewEntryPointFileWriter`.

Previously some typings and external JS files were
being copied which was messing up the node_modules
structure.

Fixes https://github.com/angular/angular-cli/issues/14193

PR Close #30085
2019-04-24 10:49:31 -07:00
Kristiyan Kostadinov c7f1b0a97f fix(ivy): queries not being inherited from undecorated classes (#30015)
Fixes view and content queries not being inherited in Ivy, if the base class hasn't been annotated with an Angular decorator (e.g. `Component` or `Directive`).

Also reworks the way the `ngBaseDef` is created so that it is added at the same point as the queries, rather than inside of the `Input` and `Output` decorators.

This PR partially resolves FW-1275. Support for host bindings will be added in a follow-up, because this PR is somewhat large as it is.

PR Close #30015
2019-04-24 10:38:44 -07:00
Andrew Kushnir aaf8145c48 fix(ivy): support module.id as @NgModule's "id" field value (#30040)
Prior to this commit, the check that verifies correct "id" field type was too strict and didn't allow `module.id` as @NgModule's "id" field value. This change adds a special handling for `module.id` and uses it as id of @NgModule if specified.

PR Close #30040
2019-04-23 14:50:58 -07:00
JoostK c4dd2d115b fix(ivy): let ngtsc's shim host delegate `resolveModuleNames` method (#30068)
Now that ngtsc performs type checking using a dedicated `__ng_typecheck__.ts`
file, `NgtscProgram` always wraps its `ts.CompilerHost` in a shim host. This
shim fails to delegate `resolveModuleNames` so no custom module resolution
logic is considered. This introduces a problem for the CLI, as the compiler
host it passes kicks of ngcc for any imported module such that Ivy's
compatibility compiler runs automatically behind the scenes.

This commit adds delegation of the `resolveModuleNames` to fix the issue.

Fixes #30064

PR Close #30068
2019-04-23 13:05:25 -07:00
Alex Rickabaugh 8e73f9b0aa feat(compiler-cli): lower some exported expressions (#30038)
The compiler uses metadata to represent what it statically knows about
various expressions in a program. Occasionally, expressions in the program
for which metadata is extracted may contain sub-expressions which are not
representable in metadata. One such construct is an arrow function.

The compiler does not always need to understand such expressions completely.
For example, for a provider defined with `useValue`, the compiler does not
need to understand the value at all, only the outer provider definition. In
this case, the compiler employs a technique known as "expression lowering",
where it rewrites the provider expression into one that can be represented
in metadata. Chiefly, this involves extracting out the dynamic part (the
`useValue` expression) into an exported constant.

Lowering is applied through a heuristic, which considers the containing
statement as well as the field name of the expression.

Previously, this heuristic was not completely accurate in the case of
route definitions and the `loadChildren` field, which is lowered. If the
route definition using `loadChildren` existed inside a decorator invocation,
lowering was performed correctly. However, if it existed inside a standalone
variable declaration with an export keyword, the heuristic would conclude
that lowering was unnecessary. For ordinary providers this is true; however
the compiler attempts to fully understand the ROUTES token and thus even if
an array of routes is declared in an exported variable, any `loadChildren`
expressions within still need to be lowered.

This commit enables lowering of already exported variables under a limited
set of conditions (where the initializer expression is of a specific form).
This should enable the use of `loadChildren` in route definitions.

PR Close #30038
2019-04-23 08:30:58 -07:00
Ben Lesh 0f9230d018 feat(ivy): generate ɵɵproperty in host bindings (#30009)
PR Close #30009
2019-04-22 17:30:17 -07:00
JoostK 19dfadb717 fix(ivy): include context name for template functions for `ng-content` (#30025)
Previously, a template's context name would only be included in an embedded
template function if the element that the template was declared on has a
tag name. This is generally true for elements, except for `ng-content`
that does not have a tag name. By omitting the context name the compiler
could introduce duplicate template function names, which would fail at runtime.

This commit fixes the behavior by always including the context name in the
template function's name, regardless of tag name.

Resolves FW-1272

PR Close #30025
2019-04-22 17:28:36 -07:00
Ben Lesh 0bcb2320ba feat(ivy): generate ɵɵpropertyInterpolateX instructions (#30008)
- Compiler now generates `ɵɵpropertyInterpolateX` instructions.

PR Close #30008
2019-04-22 17:10:36 -07:00
JoostK 8c80b851c8 fix(ivy): ngcc - insert new imports after existing ones (#30029)
Previously, ngcc would insert new imports at the beginning of the file, for
convenience. This is problematic for imports that have side-effects, as the
side-effects imposed by such imports may affect the behavior of subsequent
imports.

This commit teaches ngcc to insert imports after any existing imports. Special
care has been taken to ensure inserted constants will still follow after the
inserted imports.

Resolves FW-1271

PR Close #30029
2019-04-22 16:29:30 -07:00
Kristiyan Kostadinov 63523f7964 fix(ivy): avoid generating instructions for empty style and class bindings (#30024)
Fixes Ivy throwing an error because it tries to generate styling instructions for empty `style` and `class` bindings.

This PR resolves FW-1274.

PR Close #30024
2019-04-22 11:16:58 -07:00
JoostK 8cba4e1f6b fix(ivy): ngcc - do not copy declaration files into bundle clone (#30020)
Previously, all of a program's files would be copied into the __ivy_ngcc__
folder where ngcc then writes its modifications into. The set of source files
in a program however is much larger than the source files contained within
the entry-point of interest, so many more files were copied than necessary.
Even worse, it may occur that an unrelated file in the program would collide
with an already existing source file, resulting in incorrectly overwriting
a file with unrelated content. This behavior has actually been observed
with @angular/animations and @angular/platform-browser/animations, where
the former package would overwrite declaration files of the latter package.

This commit fixes the issue by only copying relevant source files when cloning
a bundle's content into __ivy_ngcc__.

Fixes #29960

PR Close #30020
2019-04-22 08:46:19 -07:00
JoostK c3c0df9d56 fix(ivy): let ngtsc evaluate default parameters in the callee context (#29888)
Previously, during the evaluation of a function call where no argument
was provided for a parameter that has a default value, the default value
would be taken from the context of the caller, instead of the callee.

This commit fixes the behavior by resolving the default value of a
parameter in the context of the callee.

PR Close #29888
2019-04-19 19:30:40 -07:00
JoostK cb34514d05 feat(ivy): let ngtsc evaluate the spread operator in function calls (#29888)
Previously, ngtsc's static evaluator did not take spread operators into
account when evaluating function calls, nor did it handle rest arguments
correctly. This commit adds support for static evaluation of these
language features.

PR Close #29888
2019-04-19 19:30:40 -07:00
Ben Lesh 10217bb3bc feat(ivy): generate ɵɵproperty instructions (#29946)
PR Close #29946
2019-04-19 16:07:52 -07:00
Alex Rickabaugh d9ce8a4ab5 feat(ivy): introduce a flag to control template type-checking for Ivy (#29698)
Template type-checking is enabled by default in the View Engine compiler.
The feature in Ivy is not quite ready for this yet, so this flag will
temporarily control whether templates are type-checked in ngtsc.

The goal is to remove this flag after rolling out template type-checking in
google3 in Ivy mode, and making sure the feature is as compatible with the
View Engine implementation as possible.

Initially, the default value of the flag will leave checking disabled.

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh 42262e4e8c feat(ivy): support $any when type-checking templates (#29698)
This commit adds support in the template type-checking engine for the $any
cast operation.

Testing strategy: TCB tests included.

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh bea85ffe9c fix(ivy): match microsyntax template directives correctly (#29698)
Previously, Template.templateAttrs was introduced to capture attribute
bindings which originated from microsyntax (e.g. bindings in *ngFor="...").
This means that a Template node can have two different structures, depending
on whether it originated from microsyntax or from a literal <ng-template>.

In the literal case, the node behaves much like an Element node, it has
attributes, inputs, and outputs which determine which directives apply.
In the microsyntax case, though, only the templateAttrs should be used
to determine which directives apply.

Previously, both the t2_binder and the TemplateDefinitionBuilder were using
the wrong set of attributes to match directives - combining the attributes,
inputs, outputs, and templateAttrs of the Template node regardless of its
origin. In the TDB's case this wasn't a problem, since the TDB collects a
global Set of directives used in the template, so it didn't matter whether
the directive was also recognized on the <ng-template>. t2_binder's API
distinguishes between directives on specific nodes, though, so it's more
sensitive to mismatching.

In particular, this showed up as an assertion failure in template type-
checking in certain cases, when a directive was accidentally matched on
a microsyntax template element and also had a binding which referenced a
variable declared in the microsyntax. This resulted in the type-checker
attempting to generate a reference to a variable that didn't exist in that
scope.

The fix is to distinguish between the two cases and select the appropriate
set of attributes to match on accordingly.

Testing strategy: tested in the t2_binder tests.

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh 5268ae61a0 feat(ivy): support for template type-checking pipe bindings (#29698)
This commit adds support for template type-checking a pipe binding which
previously was not handled by the type-checking engine. In compatibility
mode, the arguments to transform() are not checked and the type returned
by a pipe is 'any'. In full type-checking mode, the transform() method's
type signature is used to check the pipe usage and infer the return type
of the pipe.

Testing strategy: TCB tests included.

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh 98f86de8da perf(ivy): template type-check the entire program in 1 file if possible (#29698)
The template type-checking engine previously would assemble a type-checking
program by inserting Type Check Blocks (TCBs) into existing user files. This
approach proved expensive, as TypeScript has to re-parse and re-type-check
those files when processing the type-checking program.

Instead, a far more performant approach is to augment the program with a
single type-checking file, into which all TCBs are generated. Additionally,
type constructors are also inlined into this file.

This is not always possible - both TCBs and type constructors can sometimes
require inlining into user code, particularly if bound generic type
parameters are present, so the approach taken is actually a hybrid. These
operations are inlined if necessary, but are otherwise generated in a single
file.

It is critically important that the original program also include an empty
version of the type-checking file, otherwise the shape of the two programs
will be different and TypeScript will throw away all the old program
information. This leads to a painfully slow type checking pass, on the same
order as the original program creation. A shim to generate this file in the
original program is therefore added.

Testing strategy: this commit is largely a refactor with no externally
observable behavioral differences, and thus no tests are needed.

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh f4c536ae36 feat(ivy): logical not and safe navigation operation handling in TCBs (#29698)
This commit adds support in the template type-checking engine for handling
the logical not operation and the safe navigation operation.

Safe navigation in particular is tricky, as the View Engine implementation
has a rather inconvenient flaw. View Engine checks a safe navigation
operation `a?.b` as:

```typescript
(a != null ? a!.b : null as any)
```

The type of this expression is always 'any', as the false branch of the
ternary has type 'any'. Thus, using null-safe navigation throws away the
type of the result, and breaks type-checking for the rest of the expression.

A flag is introduced in the type-checking configuration to allow Ivy to
mimic this behavior when needed.

Testing strategy: TCB tests included.

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh 182e2c7449 feat(ivy): add backwards compatibility config to template type-checking (#29698)
View Engine's implementation of naive template type-checking is less
advanced than the current Ivy implementation. As a result, Ivy catches lots
of typing bugs which VE does not. As a result, it's necessary to tone down
the Ivy template type-checker in the default case.

This commit introduces a mechanism for doing that, by passing a config to
the template type-checking engine. Through this configuration, particular
checks can be loosened or disabled entirely.

Testing strategy: TCB tests included.

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh cd1277cfb7 fix(ivy): include directive base class metadata when generating TCBs (#29698)
Previously the template type-checking code only considered the metadata of
directive classes actually referenced in the template. If those directives
had base classes, any inputs/outputs/etc of the base classes were not
tracked when generating the TCB. This resulted in bindings to those inputs
being incorrectly attributed to the host component or element.

This commit uses the new metadata package to follow directive inheritance
chains and use the full metadata for a directive for TCB generation.

Testing strategy: Template type-checking tests included.

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh 9277afce61 refactor(ivy): move metadata registration to its own package (#29698)
Previously, metadata registration (the recording of collected metadata
during analysis of directives, pipes, and NgModules) was only used to
produce the `LocalModuleScope`, and thus was handled by the
`LocalModuleScopeRegistry`.

However, the template type-checker also needs information about registered
directives, outside of the NgModule scope determinations. Rather than
reuse the scope registry for an unintended purpose, this commit introduces
new abstractions for metadata registration and lookups in a separate
'metadata' package, which the scope registry implements.

This paves the way for a future commit to make use of this metadata for the
template type-checking system.

Testing strategy: this commit is a refactoring which introduces no new
functionality, so existing tests are sufficient.

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh 410151b07f fix(ivy): check [class] and [style] bindings properly (#29698)
Previously, bindings to [class] and [style] were treated like any other
property binding. That is, they would result in type-checking code that
attempted to write directly to .class or .style on the element node.

This is incorrect, however - the mapping from Angular's [class] and [style]
onto the DOM properties is non-trivial.

For now, this commit avoids the issue by only checking the expressions
themselves and not the assignment to the element properties.

Testing strategy: TCB tests included.

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh 073d258deb feat(ivy): template type-checking for '#' references in templates (#29698)
Previously the template type-checking engine processed templates in a linear
manner, and could not handle '#' references within a template. One reason
for this is that '#' references are non-linear - a reference can be used
before its declaration. Consider the template:

```html
{{ref.value}}
<input #ref>
```

Accommodating this required refactoring the type-checking code generator to
be able to produce Type Check Block (TCB) code non-linearly. Now, each
template is processed and a list of TCB operations (`TcbOp`s) are created.
Non-linearity is modeled via dependencies between operations, with the
appropriate protection in place for circular dependencies.

Testing strategy: TCB tests included.

PR Close #29698
2019-04-19 11:15:25 -07:00