Commit Graph

5589 Commits

Author SHA1 Message Date
Paul Gschwendtner 8de3c20e50 fix(ivy): do not reset view dirty state in check no changes mode (#34495)
Unlike in View Engine, we currently reset the dirty state of
components in the check no changes change detection cycle.

This means that components cannot be marked as dirty from
view lifecycle hooks because the dirty state is reset and
the lifecycle hooks do not run in the check no changes CD cycle.

PR Close #34495
2020-01-13 09:43:16 -08:00
Adam 55037d1107 build: bump year (#34651)
PR Close #34651
2020-01-13 07:21:43 -08:00
Ayaz Hafiz a44479d0a0 style(common): remove unnecessary private annotation (#34734)
The `@private` annotation on a function upsets tsc, and appears
unnecessary for non-exported functions.

PR Close #34734
2020-01-13 07:17:42 -08:00
Keen Yee Liau bfe9bc912a fix(language-service): CRLF offset in inline template (#34737)
This commit fixes incorrect CRLF offsets in inline template.

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

PR Close #34737
2020-01-13 07:16:50 -08:00
crisbeto 6d534f10e6 fix(ivy): don't run decorator handlers against declaration files (#34557)
Currently the decorator handlers are run against all `SourceFile`s in the compilation, but we shouldn't be doing it against declaration files. This initially came up as a CI issue in #33264 where it was worked around only for the `DirectiveDecoratorHandler`. These changes move the logic into the `TraitCompiler` and `DecorationAnalyzer` so that it applies to all of the handlers.

PR Close #34557
2020-01-10 15:54:51 -08:00
Keen Yee Liau 6d28a209e4 test(language-service): Remove test cases from parsing-cases.ts (#34716)
This commit removes some test scenarios from `parsing-cases.ts` and
colocate them with the test code instead. This makes the tests easier to
read and understand.

PR Close #34716
2020-01-10 14:44:24 -08:00
atscott e88d652f2a Revert "build: upgrade to rules_nodejs 1.0.0 (first stable release) (#34589)" (#34730)
This reverts commit cb6ffa1211.

PR Close #34730
2020-01-10 14:12:15 -08:00
atscott aa0244765a Revert "build: upgrade to io_bazel_rules_sass 1.24.0 (#34589)" (#34730)
This reverts commit 96643e7ce2.

PR Close #34730
2020-01-10 14:12:15 -08:00
atscott 538d0446b5 Revert "refactor: handle breaking changes in rules_nodejs 1.0.0 (#34589)" (#34730)
This reverts commit 9bb349e1c8.

PR Close #34730
2020-01-10 14:12:15 -08:00
atscott 7eddbe5d7f Revert "build: update integration/bazel & @angular/bazel schematics to rules_nodejs 1.0.0 (#34589)" (#34730)
This reverts commit 7203169c3d.

PR Close #34730
2020-01-10 14:12:15 -08:00
atscott 6e5774b9a0 Revert "build: update to rules nodejs 1.0.1 (#34589)" (#34730)
This reverts commit 8042433cb0.

PR Close #34730
2020-01-10 14:12:15 -08:00
atscott 5e60215470 Revert "test: handle bootstrap templated_args in jasmine_node_test defaults.bzl (#34589)" (#34730)
This reverts commit da4782e67f.

PR Close #34730
2020-01-10 14:12:15 -08:00
atscott eabe961197 Revert "build: renamed "injected_scripts" target to "asset_injected_index_html" (#34589)" (#34730)
This reverts commit 4754e495dc.

PR Close #34730
2020-01-10 14:12:14 -08:00
atscott b788c36909 Revert "build: add a before-all-other bootstrap script that patches require (#34589)" (#34730)
This reverts commit c3e8439954.

PR Close #34730
2020-01-10 14:12:14 -08:00
atscott 66fbc2a1b8 Revert "build: should use $(execpath) in npm_package_bin args (#34589)" (#34730)
This reverts commit 67044ef55d.

PR Close #34730
2020-01-10 14:12:14 -08:00
atscott 24679d8676 Revert "build: derive ts_library dep from jasmine_node_test boostrap label if it ends in `_es5` (#34589)" (#34730)
This reverts commit 79a0d007b4.

PR Close #34730
2020-01-10 14:12:14 -08:00
Greg Magolan 79a0d007b4 build: derive ts_library dep from jasmine_node_test boostrap label if it ends in `_es5` (#34589)
PR Close #34589
2020-01-10 08:32:00 -08:00
Greg Magolan 67044ef55d build: should use $(execpath) in npm_package_bin args (#34589)
This is recommended in the Bazel docs as $(location) is ambiguous and can mean either $(execpath) or $(rootpath) depending on the context.

PR Close #34589
2020-01-10 08:32:00 -08:00
Greg Magolan c3e8439954 build: add a before-all-other bootstrap script that patches require (#34589)
This removes the churn in the existing bootstrap scripts.

PR Close #34589
2020-01-10 08:32:00 -08:00
Greg Magolan 4754e495dc build: renamed "injected_scripts" target to "asset_injected_index_html" (#34589)
PR Close #34589
2020-01-10 08:32:00 -08:00
Greg Magolan da4782e67f test: handle bootstrap templated_args in jasmine_node_test defaults.bzl (#34589)
PR Close #34589
2020-01-10 08:31:59 -08:00
Greg Magolan 8042433cb0 build: update to rules nodejs 1.0.1 (#34589)
This brings in a few minor fixes including a better way to patch require for bootstrap scripts.

PR Close #34589
2020-01-10 08:31:59 -08:00
Greg Magolan 7203169c3d build: update integration/bazel & @angular/bazel schematics to rules_nodejs 1.0.0 (#34589)
For the purposes of the integration test the zone.js script & bundle script tags can just go into the source index.html itself. The purpose of the integration test is is to test @angular/bazel & ng_module & ng_package so there is no need to exercise html_insert_assets in integration/bazel.

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

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

PR Close #34589
2020-01-10 08:31:58 -08:00
ayazhafiz 4d95c3d39a refactor(language-service): rename expression completions method (#34518)
This commit renames `addAttributeValuesToCompletions`, which generates
expression completions and is not exclusive to processing attributes, to
`processExpressionCompletions`. Also removes the expression completion
logic in `visitBoundText` for a call to `processExpressionCompletions`.

The conditional branch in `visitBoundText` is also removed. This branch
was added in one of the first commits to the language service
(519a324454) and appears to be
unnecessary, as the expression AST is constructed from the template
position anyway.

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

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

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

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

PR Close #34527
2020-01-10 08:28:50 -08:00
crisbeto b1eb84c57e refactor(ivy): remove calls into other instructions from pipe instructions (#33714)
A while ago we made a pass through all instructions to make sure that none of them call directly into other instructions, however it seems like missed the `pipeBind*` since they still call into the pure functions. The result is that we have some unnecessary duplicated accesses of global state like `getLView` which are called twice in a row with nothing changing.

These changes move the common functionality into a shared file and make the pipe instructions call into them with the global state instead.

PR Close #33714
2020-01-10 08:27:26 -08:00
ayazhafiz 794dcb58d3 fix(language-service): do not use an i18n parser for templates (#34531)
The compiler's `I18NHtmlParser` may expand template nodes that have
internationalization metadata attached to them; for instance,

```html
<div i18n="@@i18n-el">{{}}</div>
```

gets expanded to an AST with the i18n metadata extracted and text filled
in as necessary; to the language service, the template above, as read in
the AST, now looks something like

```html
<div>{{$implicit}}</div>
```

This is undesirable for the language service because we want to preserve
the original form of the source template source code, and have
information about the original values of the template. The language
service also does not need to use an i18n parser -- we don't generate
any template output.

To fix this turns out to be as easy as moving to using a raw
`HtmlParser`.

---

A note on the testing strategy: as mentioned above, we don't need to use
an i18n parser, but we don't **not** need to use one if the parser
does not heavily modify the template AST. For this reason, the tests
target the functionality of not modifying a template with i18n metadata
rather than testing that the language service does not use an i18n parser.

---

Closes https://github.com/angular/vscode-ng-language-service/issues/272

PR Close #34531
2020-01-10 08:23:08 -08:00
Igor Minar 25eaff447a refactor(core): remove duplicate InjectableType declaration (#34679)
This duplication causes a compilation error with TypeScript 3.7

PR Close #34679
2020-01-09 16:05:20 -08:00
Paul Gschwendtner 6315acae94 fix(forms): disabled input acceptance member not properly applied (#34502)
With 5cecd97493 we intended to expand
the input type of the `disabled` input of the `NgModel` directive.
Read more about the reason for this in the actual commit message.

Currently though, the acceptance coercion member does not have any
effect. This is because the acceptance member needs to refer to the
actual input property name, and not to the public input name.
`disabled` corresponds to the `isDisabled` property.

PR Close #34502
2020-01-09 15:12:09 -08:00
Andrew Kushnir c3f14bb7a5 feat(ivy): improve `ExpressionChangedAfterChecked` error message for attributes (#34505)
This commit improves `ExpressionChangedAfterChecked` error message for attributes by including attribute name and the content of the entire expression that contains interpolation(s). In order to achieve that, metadata is now stored in `TData` array when `attribute` and `attributeInterpolate` instructions are being called (similar to `property` and `propertyInterpolate` instructions).

PR Close #34505
2020-01-09 13:47:58 -08:00
ivanwonder 181d766941 feat(language-service): completions support for template reference variables (#34363)
PR Close #34363
2020-01-09 13:45:42 -08:00
ayazhafiz 443e423b58 test(language-service): make app.component a constant (#34587)
Cleans up usages of `app.component.ts` to be a constant file variable.

PR Close #34587
2020-01-09 13:31:39 -08:00
crisbeto e48e36bde3 test(ivy): add test for class setters being invoked when not used (#34706)
Adds a test that we should make pass once the latest styling refactor has landed.

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

Now the insertion point will be after the
full statement.

Fixes #34648

PR Close #34677
2020-01-08 15:09:24 -08:00
Alex Eagle 660546d0ec refactor(bazel): remove explicit deps param to ts_compile_actions (#34665)
This was already the default. I'm working on a change in the underlying TS rules where this parameter will be replaced, so ng_module needs to change first

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

For example:

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

may result in a UMD bundle including:

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

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

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

Fixes #34653

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

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

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

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

Fixes #34560

PR Close #34658
2020-01-08 15:07:10 -08:00
crisbeto d909fb0b1f fix(ivy): ngClass not applying classes with trailing/leading spaces (#34539)
Fixes classes with trailing or leading space that are passed to `ngClass` (e.g. `{'foo ': bar}`) not being applied in Ivy. The issue comes from the fact that when the styling differ builds up the style map it uses the trimmed key to look up the value in the map that uses non-trimmed keys.

Fixes #34476.

PR Close #34539
2020-01-08 15:02:09 -08:00
crisbeto 6fda7f3da4 fix(ivy): warn instead of throwing for unknown elements (#34524)
Follow-up from [this discussion](https://github.com/angular/angular/pull/33419#discussion_r339296216). In Ivy we don't use the schema to validate tag names, but instead we use feature detection to figure out whether an element is supported. While this should generally be more accurate, it'll also end up throwing for some more innocent cases. E.g. now Ivy throws an error for `main` elements in IE which is accurate since IE doesn't support the element, but is annoying since there is no functionality attached.

These changes switch to logging a warning instead, similarly to what we're doing for unknown properties.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

PR Close #34617
2020-01-07 10:51:46 -08:00
Troels Lenda 1b6ad15bc5 fix(common): remove trailing whitespace for CurrencyPipe (#34642)
Trimming any surrounding whitespace characters informatNumberToLocaleString
if currency symbol issupressed.

Closes #34641

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

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

Fixes #34525

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

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

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

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

Fixes #34411

// FW-1781

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

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

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

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

PR Close #34436
2020-01-07 10:31:45 -08:00
skrikl 0254cba4b3 docs: Fix double 'as an' in description at line 2069 (#34373)
PR Close #34373
2020-01-07 10:29:41 -08:00
Andrew Kushnir effb92dfae fix(ivy): skip field inheritance if InheritDefinitionFeature is present on parent def (#34244)
The main logic of the `InheritDefinitionFeature` is to go through the prototype chain of a given Component and merge all Angular-specific information onto that Component def. The problem happens in case there is a Component in a hierarchy that also contains the `InheritDefinitionFeature` (i.e. it extends some other Component), so it inherits all Angular-specific information from its super class. As a result, the root Component may end up having duplicate information inherited from different Components in hierarchy.

Let's consider the following structure: `GrandChild` extends `Child` that extends `Base` and the `Base` class has a `HostListener`. In this scenario `GrandChild` and `Child` will have `InheritDefinitionFeature` included into the `features` list. The processing will happend in the following order:

- `Child` inherits `HostListener` from the `Base` class
- `GrandChild` inherits `HostListener` from the `Child` class
- since `Child` has a parent, `GrandChild` also inherits from the `Base` class

The result is that the `GrandChild` def has duplicated host listener, which is not correct.

This commit introduces additional logic that checks whether we came across a def that has `InheritDefinitionFeature` feature (which means that this def already inherited information from its super classes). If that's the case, we skip further fields-related inheritance logic, but keep going though the prototype chain to look for super classes that contain other features (like NgOnChanges), that we need to invoke for a given Component def.

PR Close #34244
2020-01-07 10:28:06 -08:00
crisbeto 5b864ede13 fix(ivy): TestBed not unwrapping imports array function when overriding provider (#34629)
Fixes an error that is thrown when a provider is overridden in `TestBed`, if the module definition of one of the imported modules uses a function for the `imports` that is set via `setNgModuleScope`. The problem was that we have a `for...of` loop that assumes that the imports are an array, but they can also be a function. This was handled correctly in other places, but this one was missed.

Note that the above-mentioned error is only thrown at runtime when the code is transpiled to es6. In es5 TS generates a call to a helper that handles the error silently so the attached unit test only fails in es6.

Fixes #34623.

PR Close #34629
2020-01-06 11:38:02 -08:00
ayazhafiz ee46b9b44f fix(language-service): correctly parse expressions in an attribute (#34517)
Currently, the language service provides completions in a template node
attribute by first checking if the attribute contains template bindings
to provide completions for, and then providing completions for the
expression in the attribute.

In the latter case, the expression AST was being constructed
"synthetically" inside the language service, in particular declaring the
expression to be a `PropertyRead` with an implicit receiver.
Unfortunately, this AST can be incorrect if the expression is actually a
property read on a component property receiver (e.g. when reading
`key` in the expression `obj.key`, `obj` is the receiver).

The fix is pretty simple - rather than a synthetic construction of the
AST, ask the expression parser to parse the expression in the attribute.

Fixes https://github.com/angular/vscode-ng-language-service/issues/523

PR Close #34517
2020-01-06 11:37:21 -08:00
Keen Yee Liau c079f38cbb feat(language-service): Show documentation on hover (#34506)
This commit adds dpcumentation to the hover tooltip.

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

PR Close #34506
2020-01-06 11:36:57 -08:00
ivanwonder ba2fd31e62 fix(language-service): The pipe method should not include parentheses (#34485)
PR Close #34485
2020-01-06 11:31:14 -08:00
JoostK e116816131 refactor(ivy): let `strictTemplates` imply `fullTemplateTypeCheck` (#34195)
Previously, it was required that both `fullTemplateTypeCheck` and
`strictTemplates` had to be enabled for strict mode to be enabled. This
is strange, as `strictTemplates` implies `fullTemplateTypeCheck`. This
commit makes setting the `fullTemplateTypeCheck` flag optional so that
strict mode can be enabled by just setting `strictTemplates`.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Resolves FW-1739

PR Close #34021
2020-01-06 11:06:07 -08:00
ayazhafiz 19944c2424 feat(compiler): record end of expression Token (#33549)
In the past, only the starting index of an expression Token has been
recorded, so a parser could demarkate the span of a token only by the
start locations of two tokens. This may lead to trailing whitespace
being included in the token span:

```html
{{ token1   + token2 }}
   ^^^^^^^^^             recorded span of `token1`
```

It's also not enough for a parser to determine the end of a token by
adding the length of the token value to the token's start location,
because lexed expression values may not exactly reflect the source code.
For example, `"d\\"e"` is lexed as a string token whose value is `d"e`.

Instead, this commit adds a `end` field to expression tokens. `end`
is one past the last index of the token source code. This will enable a
parser to determine the span of a token just by looking at that token.

This is a breaking change because the contructor interface of `Token`
has changed.

Part of #33477.

PR Close #33549
2020-01-06 11:00:15 -08:00
Keen Yee Liau 9b9116c79d feat(language-service): Append symbol type to hover tooltip (#34515)
Now that https://github.com/angular/angular/pull/34177 fixed the `TypeWrapper`
to have a proper name, we have the information needed to show the type
name in a hover tooltip.

PR Close #34515
2019-12-20 14:40:04 -08:00
Keen Yee Liau 2dffe65cfd fix(language-service): completions after "let x of |" in ngFor (#34473)
This commit fixes a bug in which we do testing for completions.
Subsequently, this exposes another bug in our implementation whereby
suggestions are not provided in "ngFor" where there should have been.

Currently, multiple test cases are grouped together in a single
template. This requires the template to be somewhat complete so that
test cases that depend on variables declared earlier would pass.

Consider the following example:

```
  template: `
    <div *ngFor="let ~{for-person}person of ~{for-people}people">
      <span>Name: {{~{for-interp-person}person.~{for-interp-name}name}}</span>
      <span>Age: {{person.~{for-interp-age}age}}</span>
    </div>`,
```

In order to test `~{for-interp-person}`, `people` has to be included after
`~{for-people}`. This means the test case for `~{for-people}` is not
reflective of the actual use case because the variable is already there!
In real case, the expression would be incomplete, and our implementation
failed to take that into account.

This commit breaks such test into individual tests, and fix the bugs in
the underlying implementation.

PR Close #34473
2019-12-19 11:34:03 -08:00
crisbeto cf37c003ff feat(ivy): error in ivy when inheriting a ctor from an undecorated base (#34460)
Angular View Engine uses global knowledge to compile the following code:

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

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

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

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

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

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

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

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

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

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

Fixes #33849

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #33593

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

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

This is downleveled in UMD to:

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

This commit adds support for this.

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

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

This can be downleveled in CommonJS to either:

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

or

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

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

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

PR Close #34254
2019-12-18 11:25:01 -08:00
Martin Probst dfecca29da refactor: TypeScript 3.7 fixes. (#34372)
This PR fixes more TypeScript 3.7 compilation issues.

PR Close #34372
2019-12-18 10:14:10 -08:00
Keen Yee Liau 1eae7c81e9 refactor(language-service): Append missing AttrAst to AstPath (#34459)
When a HTML Ast containing an Attribute node is converted to a Template Ast,
the attribute node might get dropped from the Template Ast path.
This is because the AttrNode is not even in the Template Ast to begin with.
In this case, we manually fix the path by converting the Attribute node
to a AttrAst node and appending it to the path.

This allows the `ExpressionVisitor` to properly visit the leaf node in the
TemplateAst path. We no longer need to visit the `Element` and look for
attributes.

PR Close #34459
2019-12-18 09:14:16 -08:00
Keen Yee Liau a04f7c0d5f fix(language-service): Proper completions for properties and events (#34445)
This commit fixes autocompletions for properties and events bindings.

The language service will no longer provide bindings like (click) or [id].
Instead, it'll infer the context based on the brackets and provide suggestions
without any brackets.

This fix also adds support for alternative binding syntax such as
`bind-`, `on-`, and `bindon`.

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

PR Close #34445
2019-12-18 09:13:31 -08:00
Andrew Kushnir 9d1175e2b2 fix(ivy): improve ExpressionChangedAfterChecked error (#34381)
Prior to this change, the ExpressionChangedAfterChecked error thrown in Ivy was missing useful information that was available in View Engine, specifically: missing property name for proprty bindings and also the content of the entire property interpolation (only a changed value was displayed) if one of expressions was changed unexpectedly. This commit improves the error message by including the mentioned information into the error text.

PR Close #34381
2019-12-18 09:12:57 -08:00
Ayaz Hafiz 3e201181bb fix(ivy): correctly associate output bound events with directives (#31938)
Previously, bound events were incorrectly bound to directives with
inputs matching the bound event attribute. This fixes that so bound
events can only be bound to directives with matching outputs.

Adds tests for all kinds of directive matching on bound attributes.

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

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

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

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

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

PR Close #34404
2019-12-17 11:39:48 -08:00
George Kalpakas 9cabd6638e refactor(ngcc): un-nest accidentally nested `describe()` blocks (#34437)
PR Close #34437
2019-12-17 11:39:18 -08:00
George Kalpakas cd8a837956 refactor(ngcc): add debug messages to help with debugging in parallel mode (#34437)
PR Close #34437
2019-12-17 11:39:18 -08:00
Paul Gschwendtner 5cecd97493 feat(forms): expand NgModel disabled type to work with strict template type checking (#34438)
NgModel internally coerces any arbitrary value that will assigned
to the `disabled` `@Input` to a boolean. This has been done to
support the common case where developers set the disabled attribute
without a value. For example:

```html
<input type="checkbox" [(ngModel)]="value" disabled>
```

This worked in View Engine without any errors because inputs were
not strictly checked. In Ivy though, developers can opt-in into
strict template type checking where the attribute would be flagged.

This is because the `NgModel#isDisabled` property type-wise only
accepts a `boolean`. To ensure that the common pattern described
above can still be used, and to reflect the actual runtime behavior,
we should add an acceptance member that makes it work without type
checking errors.

Using a coercion member means that this is not a breaking change.

PR Close #34438
2019-12-16 15:34:03 -08:00
Keen Yee Liau 5df8a3ba95 fix(language-service): HTML path should include last node before cursor (#34440)
Given the following HTML and cursor position:
```
<div c|></div>
      ^ cursor is here
```

Note that the cursor is **after** the attribute `c`.

Under the current implementation, only `Element` is included in the
path. Instead, it should be `Element -> Attribute`.

This bug occurs only for cases where the cursor is right after the Node,
and it is because the `end` position of the span is excluded from the search.
Instead, the `end` position should be included.

PR Close #34440
2019-12-16 14:12:36 -08:00
Keen Yee Liau 5eaab85fc0 fix(language-service): Remove completions for let and of in ngFor (#34434)
`let` and `of` should be considered reserved keywords in template syntax
and thus should not be part of the autocomplete suggestions.

For reference, TypeScript does not provide such completions.

This commit removes these results and cleans up the code.

PR Close #34434
2019-12-16 12:45:38 -08:00
Andrew Scott 357a0733c7 fix(ivy): reorder provider type checks to align with VE (#34433)
The ordering matters because we don't currently throw if multiple
configurations are provided (i.e. provider has *both* useExisting and
useFactory). We should actually throw an error in this case, but to
avoid another breaking change in v9, this PR simply aligns the Ivy
behavior with ViewEngine.

PR Close #34433
2019-12-16 12:44:27 -08:00
crisbeto 835ed0f35f fix(animations): leaking detached nodes when parent has a leave transition (#34409)
In the TransitionAnimationEngine we keep track of the existing elements with animations and we clear the cached data when they're removed. We also have some logic where we transition away the child elements when a parent is removed, however in that case we never cleared the cached element data which resulted in a memory leak. The leak is particularly visible in Material where whenever there's an animated overlay with a component inside of it that has an animation, the child component would always be retained in memory.

Fixes #25744.

PR Close #34409
2019-12-16 12:39:25 -08:00
Michael Nahkies 1144ce97f9 fix(common): ngStyle should ignore undefined values (#34422)
Prior to ivy, undefined values passed in an object to the
ngStyle directive were ignored. Restore this behavior by
ignoring keys that point to undefined values.

closes #34310

PR Close #34422
2019-12-16 12:38:49 -08:00
Ayaz Hafiz ddc229b69b fix(ivy): record correct absolute source span for ngForOf expressions (#31813)
Expressions in an inline template binding are improperly recorded as
spaning an offset calculated from the start of the template binding
attribute key, whereas they should be calculated from the start of the
attribute value, which contains the actual binding AST.

PR Close #31813
2019-12-16 08:11:48 -08:00
JoostK 12444a8afc test(ngcc): cleanup entry-point bundle testcases (#34415)
There was an issue with the program under test and two tests with the
same description, this has been fixed.

PR Close #34415
2019-12-16 07:45:36 -08:00
ajitsinghkaler a186dbc1d4 docs(upgrade): add example links to `downgradeComponent()` function docs (#34406)
There were some extra examples for `downgradeComponent()` in the upgrade
guide. Added a link to the relevant section of the guide in the
`downgradeComponent()` docs.

Fixes #31584

PR Close #34406
2019-12-16 07:45:00 -08:00
Paul Gschwendtner 6d3a25d897 ci: run acceptance tests on saucelabs with ivy (#34277)
Currently we only run Saucelabs on PRs using the legacy View Engine
build. Switching that build to Ivy is not trivial and there are various
options:

  1. Updating the R3 switches to use POST_R3 by default. At first glance,
  this doesn't look easy because the current ngtsc switch logic seems to
  be unidirectional (only PRE_R3 to POST_R3).

  2. Updating the legacy setup to run with Ivy. This sounds like the easiest
  solution at first.. but it turns out to be way more complicated. Packages
  would need to be built with ngtsc using legacy tools (i.e. first building
  the compiler-cli; and then building packages) and View Engine only tests
  would need to be determined and filtered out. Basically it will result in
  re-auditing all test targets. This is contradictory to the fact that we have
  this information in Bazel already.

  3. Creating a new job that runs tests on Saucelabs with Bazel. We specify
  fine-grained test targets that should run. This would be a good start
  (e.g. acceptance tests) and also would mean that we do not continue maintaining
  the legacy setup..

This commit implements the third option as it allows us to move forward
with the general Bazel migration. We don't want to spend too much time
on our legacy setup since it will be removed anyway in the future.

PR Close #34277
2019-12-16 07:43:41 -08:00
crisbeto f79110c637 fix(ivy): incorrect injectable name logged in warning message on IE (#34305)
When we log DI errors we get the name of the provider via `SomeClass.name`. In IE functions that inherit from other functions don't have their own `name`, but they take the `name` from the lowest parent in the chain, before `Function`. I've added some changes to fall back to parsing out the function name from the function's string form.

PR Close #34305
2019-12-13 14:19:57 -08:00
crisbeto c2a904da09 fix(ivy): inheriting injectable definition from undecorated class not working on IE10 in JIT mode (#34305)
The way definitions are added in JIT mode is through `Object.defineProperty`, but the problem is that in IE10 properties defined through `defineProperty` won't be inherited which means that inheriting injectable definitions no longer works. These changes add a workaround only for JIT mode where we define a fallback method for retrieving the definition. This isn't ideal, but it should only be required until v10 where we'll no longer support inheriting injectable definitions from undecorated classes.

PR Close #34305
2019-12-13 14:19:56 -08:00
crisbeto ded78e5688 fix(ivy): inheritance in JIT mode not working correctly on IE10 (#34305)
Fixes the metadata and lifecycle hook inheritance not working properly in IE10, because we weren't accessing things correctly.

PR Close #34305
2019-12-13 14:19:56 -08:00
crisbeto 1efa0ca4d0 fix(ivy): avoid using __proto__ when reading metadata in JIT mode (#34305)
In JIT mode we use `__proto__` when reading constructor parameter metadata, however it's not supported on IE10. These changes switch to using `Object.getPrototypeOf` instead.

PR Close #34305
2019-12-13 14:19:56 -08:00
crisbeto 758f7a7d8e test(ivy): account for inconsistent attribute order (#34305)
We've got some tests that assert that the generate DOM looks correct. The problem is that IE changes the attribute order in `innerHTML` which caused the tests to fail. I've reworked the relevant tests not to assert directly against `innerHTML`.

PR Close #34305
2019-12-13 14:19:56 -08:00
crisbeto 8eb0596463 fix(ivy): unknown property and element checks not working correctly in IE (#34305)
We have a couple of cases where we use something like `typeof Node === 'function'` to figure out whether we're in a worker context. This works in most browsers, but IE returns `object` instead of `function`. I've updated all the usages to account for it.

PR Close #34305
2019-12-13 14:19:56 -08:00
crisbeto c45a70c3b8 fix(ivy): inconsistent attribute casing in DebugNode.attributes on IE (#34305)
In `DebugElement.attributes` we return all of the attributes from the underlying DOM node. Most browsers change the attribute names to lower case, but IE preserves the case and since we use camel-cased attributes, the return value was inconsitent. I've changed it to always lower case the attribute names.

PR Close #34305
2019-12-13 14:19:56 -08:00
crisbeto 0100a39e21 fix(ivy): i18n instructions thrown off by sanitizer in IE11 (#34305)
While sanitizing on browsers that don't support the `template` element (pretty much only IE), we create an inert document and we insert content into it via `document.body.innerHTML = unsafeHTML`. The problem is that IE appears to parse the HTML passed to `innerHTML` differently, depending on whether the element has been inserted into a document or not. In particular, it seems to split some strings into multiple text nodes, which would've otherwise been a single node. This ended up throwing off some of the i18n code down the line and causing a handful of failures. I've worked around it by creating a new inert `body` element into which the HTML would be inserted.

PR Close #34305
2019-12-13 14:19:56 -08:00
Pawel Kozlowski a781800276 refactor(ivy): remove usage of Proxy for IE10/11 compatibility (#34328)
PR Close #34328
2019-12-13 10:53:41 -08:00
Pawel Kozlowski 0fba79cda2 refactor(ivy): don't include removed classes in the styling debug (#34375)
This is mostly done to allign behaviour with DebugElement.classes and remove
Proxy usage (not supported in IE10/11).

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

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

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

PR Close #34334
2019-12-12 14:13:16 -08:00
JoostK ff0a91422a perf(compiler): speed up i18n digest computations (#34332)
Avoids the usage of array destructuring, as it introduces calls to
a `__values` helper function in ES5 that has a relatively high
performance impact. This shaves off roughly 130ms of CPU time for a
large compilation with big templates that uses i18n.

PR Close #34332
2019-12-12 14:06:37 -08:00
JoostK 014a7137f4 perf(compiler): use a shared interpolation regex (#34332)
The template parser has a certain interpolation config associated with
it and builds a regular expression each time it needs to extract the
interpolations from an input string. Since the interpolation config is
typically the default of `{{` and `}}`, the regular expression doesn't
have to be recreated each time. Therefore, this commit creates only a
single regular expression instance that is used for the default
configuration.

In a large compilation unit with big templates, computing the regular
expression took circa 275ms. This change reduces this to effectively
zero.

PR Close #34332
2019-12-12 14:06:37 -08:00
JoostK 4945274080 perf(compiler): optimize cloning cursors state (#34332)
On a large compilation unit with big templates, the total time spent in
the `PlainCharacterCursor` constructor was 470ms. This commit applies
two optimizations to reduce this time:

1. Avoid the object spread operator within the constructor, as the
generated `__assign` helper in the emitted UMD bundle (ES5) does not
optimize well compared to a hardcoded object literal. This results in a
significant performance improvement. Because of the straight-forward
object literal, the VM is now much better able to optimize the memory
allocations which makes a significant difference as the
`PlainCharacterCursor` constructor is called in tight loops.

2. Reduce the number of `CharacterCursor` clones. Although cloning
itself is now much faster because of the optimization above, several
clone operations were not necessary.

Combined, these changes reduce the total time spent in the
`PlainCharacterCursor` constructor to just 10ms.

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

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

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

PR Close #34332
2019-12-12 14:06:36 -08:00
JoostK 6e5f076330 perf(ivy): share instances of `DomElementSchemaRegistry` (#34332)
To create a binding parser, an instance of `ElementSchemaRegistry` is
required. Prior to this change, each time a new binding parser was
created a new instance of `DomElementSchemaRegistry` would be
instantiated. This is an expensive operation that takes roughly 1ms per
instantiation, so it is key that multiple allocations are avoided.

By sharing a single `DomElementSchemaRegistry`, we avoid two such
allocations, i.e. save ~2ms, per component template.

PR Close #34332
2019-12-12 14:06:36 -08:00
Adam Plumer 3255d2b197 test(core): fix schematics calls to run synchronously (#34364)
Previously the calls to run the schematics were not being properly
or consistently awaited in the tests. While this currently does not
affect the tests' performance, this fix corrects the syntax and
adds stability for future changes.

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

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

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

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

Closes #33674

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

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

The new algorithm implemented by this commit is such:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

PR Close #34288
2019-12-12 13:11:45 -08:00
Pete Bacon Darwin c13a4b8c03 style(common): remove unnecessary jsdoc type (#34369)
These types cause the compiler to give warnings,
which add noise to compilation logs.

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

This commit adds support for this corner case.

Fixes #34138

PR Close #34353
2019-12-12 09:09:41 -08:00
Kara Erickson 9a800e8fa2 Revert "build: update @angular/bazel schematics to rules_nodejs 0.42.1" (#34360)
This reverts commit 73fd10ddd5548ce899b897ba2779ff041914c2dc because it's part
of a PR that was red on CircleCI once it was merged into master (Windows tests
are only run on master, not on PRs).

PR Close #34360
2019-12-11 15:58:46 -08:00
Kara Erickson 0bf9263297 Revert "build: update @angular/bazel schematics to use html_insert_assets & pkg_web" (#34360)
This reverts commit 6b905347bd2294bba703f6d38c983356af58946b because it's part
of a PR that was red on CircleCI once it was merged into master (Windows tests
are only run on master, not on PRs).

PR Close #34360
2019-12-11 15:58:46 -08:00
Kara Erickson caaeb21e59 Revert "build: update integration/bazel & @angular/bazel schematics to rules_nodejs 0.42.1" (#34360)
This reverts commit 4e38a973b158ba397903199abe1e008b0627d81c because it's part of a PR
that was red on CircleCI once it was merged into master (Windows tests are only run
on master, not on PRs).

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

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

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

PR Close #34356
2019-12-11 13:20:49 -08:00
Pete Bacon Darwin 6ce940315b fix(ivy): i18n - remove `translate` function when clearing translations (#34346)
The `loadTranslations()` function will attach the `translate()` function
to `$localize.translate` to cause runtime translation to occur.

We should cleanup after ourselves by unattaching this function when
we call `clearTranslations()`.

Fixes #32781

PR Close #34346
2019-12-11 13:19:22 -08:00
Greg Magolan 656607b640 build: update integration/bazel & @angular/bazel schematics to rules_nodejs 0.42.1 (#34112)
This release brings a bug fix that https://github.com/angular/angular/pull/34243 is waiting on in order to remove rules_nodejs patches: fix(builtin): additional_root_paths in pkg_web should also include paths in genfiles and bin dirs (bazelbuild/rules_nodejs#1402)

PR Close #34112
2019-12-11 13:18:51 -08:00
Greg Magolan 7df2b4aeff build: update @angular/bazel schematics to use html_insert_assets & pkg_web (#34112)
PR Close #34112
2019-12-11 13:18:51 -08:00
Greg Magolan bfeaa7d564 build: update @angular/bazel schematics to rules_nodejs 0.42.1 (#34112)
PR Close #34112
2019-12-11 13:18:51 -08:00
Keen Yee Liau 08ea38f197 fix(bazel): improve performance of tsHost.writeFile() (#34331)
Removing from an array incurs O(n^2) cost, and could be mitigated with the use of a Set instead.

PR Close #34331
2019-12-11 09:51:14 -08:00
Andrew Kushnir 8572911e94 test(ivy): `class_binding` benchmark fixes (#34242)
This commit fixes a couple issues that prevent `class_binding` benchmark from running: moving constants requires by the `benchmark` function before function declaration and referencing correct consts in template instructions.

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

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

Resolves FW-389

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

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

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

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

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

  static ngAcceptInputType_disabled: boolean | string;
}
```

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

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

Fixes #33830
Resolves FW-1759

PR Close #34296
2019-12-10 16:31:23 -08:00
Andrew Kushnir c8b5b81516 refactor(ivy): avoid type coercion in `saveNameToExportMap` function (#34335)
TypeScript 3.7 flags `if` conditions that implicitly coerce a function/method definition. While checking for the `template` presence on a def (actually checking whether we work with Component) in `saveNameToExportMap`, the `if` condition had implicit type coercion. This commit updates the condition to use the `isComponentDef` function (that checks `def.template` against `null` internally) to avoid compilation errors with TypeScript 3.7.

PR Close #34335
2019-12-10 14:06:25 -08:00
Misko Hevery c8447d21bd refactor(ivy): pull property read into a constant (#34290)
PR Close #34290
2019-12-10 10:33:19 -08:00
Misko Hevery 4ef6f1ab2e refactor(ivy): prevent `-0` from being generated (#34290)
PR Close #34290
2019-12-10 10:33:19 -08:00
Andrew Kushnir bb52fb798c fix(ivy): handle SafeStyles in [style.prop] correctly (#34286)
Prior to this commit, values wrapped into SafeStyle were not handled correctly in [style.prop] bindings in case style sanitizer is present (when template contains some style props that require sanitization). Style sanitizer was not unwrapping values in case a given prop doesn't require sanitization.As a result, wrapped values were used as final styling values (see https://github.com/angular/angular/blob/master/packages/core/src/render3/styling/bindings.ts#L620). This commit updates the logic to unwrap safe values in sanitizer in case no sanitization is required.

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

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

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

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

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

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

PR Close #34234
2019-12-09 11:37:49 -08:00
Alex Rickabaugh 13c2fad240 fix(ivy): throw a better error when DI can't inject a ctor param (#33739)
Occasionally a factory function needs to be generated for an "invalid"
constructor (one with parameters types which aren't injectable). Typically
this happens in JIT mode where understanding of parameters cannot be done in
the same "up-front" way that the AOT compiler can.

This commit changes the JIT compiler to generate a new `invalidFactoryDep`
call for each invalid parameter. This instruction will error at runtime if
called, indicating both the index of the invalid parameter as well as (via
the stack trace) the factory function which was generated for the type being
constructed.

Fixes #33637

PR Close #33739
2019-12-09 11:37:10 -08:00
Jithil P Ponnan 2f3d41f081 docs(core): add new example for HostListener (#34228)
PR Close #34228
2019-12-09 10:38:01 -08:00
Pawel Kozlowski d3069dbec6 refactor(ivy): minor cleanup in the listener instruction (#34255)
PR Close #34255
2019-12-09 10:36:16 -08:00
Andrew Scott a1d0f1e5d2 fix(ivy): align TestBed.overrideProvider with what happens with providers in TestBed providers array (#33769)
In Ivy, if you do:
`TestBed.configureTestingModule({providers: [{provide: Service}]});`
the injector will attempt to inject Service as if it was simply listed
in the providers array like `{providers: [Service]}`
This fixes an inconsistency when similarly providing an override with no
`useValue` or `useFactory`.

PR Close #33769
2019-12-06 13:06:22 -08:00
Pete Bacon Darwin a12b5f930a fix(compiler): ensure localized strings are ES5 compatible for JIT mode (#34265)
Previously the JIT evaluated code for ivy localized strings included
backtick tagged template strings, which are not compatible with ES5
in legacy browsers such as IE 11.

Now the generated code is ES5 compatible.

Fixes #34246

PR Close #34265
2019-12-06 13:03:46 -08:00
Andrew Kushnir b342a69bbc fix(ivy): do not invoke change detection for destroyed views (#34241)
Prior to this commit, calling change detection for destroyed views resulted in errors being thrown in some cases. This commit adds a check to make sure change detection is invoked for non-destroyed views only.

PR Close #34241
2019-12-06 13:03:08 -08:00
Alex Rickabaugh 718d7fe5fe fix(ivy): properly parenthesize ternary expressions when emitted (#34221)
Previously, ternary expressions were emitted as:

condExpr ? trueCase : falseCase

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

a?.b ? c : d

would have compiled to:

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

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

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

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

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

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

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

Fixes #34087

PR Close #34221
2019-12-06 13:01:48 -08:00
Joey Perrott f72de51a6f build: remove compile build variable (#34280)
Remove the remaining check for compile build variable in the ng_module
rule.  Now that components is no longer relying on this build variable
we can safely remove it from our repository.

We will leave the remaining check for if the compile build variable is
used within our own repo, with plans to remove it in a couple months.
It is being kept in place to ensure that uncommitted local scripts for
our own development that we have locally, kill error as expected if
they still reference the compile build variable.

PR Close #34280
2019-12-06 11:04:20 -08:00
Kristiyan Kostadinov e7cf1e0580 feat(docs-infra): add the ability to expose globals (#34237)
Adds the ability to expose global symbols in the API docs via the `@globalApi` tag. Also supports optionally setting a namespace which will be added to the name automatically (e.g. `foo` will be renamed to `ng.foo`). Relevant APIs should also be exported through the `global.ts` file which will show up under `core/global`.

PR Close #34237
2019-12-06 10:58:09 -08:00
Keen Yee Liau 613dc1122a fix(language-service): Simplify resolution logic in banner (#34262)
Due to a bug in the existing banner, `typescript` module was require-d
instead of reusing the module passed in from tsserver.
This bug is caused by some source files in language-service that imports
`typescript` instead of `typescript/lib/tsserverlibrary`.
This is not an unsupported use case, it's just that when typescript is
resolved in the banner we have to be very careful about which modules to
"require".
The convoluted logic in the banner makes it very hard to detect
anomalies. This commit cleans it up and removes a lot of unneeded code.

This commit also removes `ts` import in typescript_host.ts and use `tss`
instead to make it less confusing.

PR Close #34262
2019-12-06 10:27:30 -08:00
Keen Yee Liau f05e1719cc fix(language-service): Remove getExternalFiles() (#34260)
This commit removes the `getExternalFiles()` from the tsserver plugin.
This API is no longer needed now that we do not intend to support
external templates under the plugin mode.
Instead, the external files are added to the project only when they are
opened by the user.
For complete discussion, see https://github.com/angular/vscode-ng-language-service/issues/473

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

PR Close #34260
2019-12-05 13:13:20 -08:00
ivanwonder a91ca99b1f refactor(language-service): refactor the method TypeWrapper.name and PipeSymbol.selectSignature (#34177)
PR Close #34177
2019-12-05 13:12:44 -08:00
ivanwonder 7a86a32040 fix(language-service): apply suggestion (#34177)
PR Close #34177
2019-12-05 13:12:44 -08:00
ivanwonder 148a060daa fix(language-service): return the js primitive type name (#34177)
PR Close #34177
2019-12-05 13:12:44 -08:00
ivanwonder 2ebaa51514 fix(language-service): bug of accessing a string index signature using dot notation (#34177)
PR Close #34177
2019-12-05 13:12:44 -08:00
Keen Yee Liau d6f278867f build: Enable ivy in google3 if ng_module attr is True (#34238)
This commit creates a way for `ng_module` rule to compile with Ivy based
on the `ivy` attribute. This enables google3 targets to pick the
compiler without using `define` flags.

PR Close #34238
2019-12-05 13:09:43 -08:00
Martin Probst 1084d4ab49 refactor(upgrade): avoid mutable exports. (#34232)
Previously, create_angular_testing_module would export a mutable `let`
binding. The binding is already exporting using an accessor function
though, so the export on the let variable seems like an accidental
oversight.

This is functionally equivalent, but makes it easier for module
optimizers such as Closure Compiler to track down side effects and prune
modules.

PR Close #34232
2019-12-05 10:19:48 -08:00
Martin Probst 37bb90140c refactor(platform-browser): avoid mutable exports. (#34207)
Previously, browser_util would export a mutable `let` binding that was
initialized as a side-effect of `BrowserDetection.setup()`. This change
refactors the mutable binding into a `const` binding that is immediately
initialized in its initialized.

This is functionally equivalent, but makes it easier for module
optimizers such as Closure Compiler to track down side effects and prune
modules. It is also arguably cleaner to read (no worries about later
changes to the apparently mutable but effectively const binding).

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

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

---

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

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

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

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

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

The second strategy failure is fixed by this PR.

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

PR Close #34212
2019-12-05 10:13:02 -08:00
Joey Perrott f9e959e098 fix(common): update closure locales to include directionality data (#34240)
When directionality data was added to @angular/common locales, only
the externally used locales were updated.  We need to additionally
update the closure locales which are synced into google3.

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

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

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

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

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

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

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

PR Close #34206
2019-12-03 16:16:30 -08:00
Andrew Kushnir 9b6a1b85b1 refactor(ivy): check metadata presence before compiling Type in R3TestBed (#34204)
Prior to this commit, there was no check in R3TestBed to verify that metadata is resolved using a given Type. That leads to some cryptic error messages (when TestBed tries to compile a Type without having metadata) in case TestBed override functions receive unexpected Types (for example a Directive is used in `TestBed.overrideComponent` call). This commit adds the necessary checks to verify metadata presence before TestBed tries to (re)compile a Type.

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

PR Close #34200
2019-12-03 16:12:55 -08:00
Andrew Kushnir 60b13d9948 fix(ivy): support ICUs with pipes (#34198)
Prior to this commit, i18n runtime code failed with the exception saying that no provider was found for ChangeDetectorRef for a pipe used in ICU. The problem happened because the underlying `createViewRef` function was not taking into account IcuContainer as a valid TNodeType. This commit updates the `createViewRef` function to return corresponding ViewRef for TNodeType.IcuContainer.

PR Close #34198
2019-12-03 16:12:19 -08:00
Kristiyan Kostadinov a295255e58 perf(ivy): avoid duplicate state lookup and default function parameters (#34183)
Includes a few minor performance improvements:
* In the `nextContext` instruction we assign a new LView to the `LFrame.contextLView` and then we immediately look it up to get its context. We don't need to do that since we know the view that was assigned already.
* Removes the default value for the `level` parameter of `nextContextImpl` because it generates more code in es5 and is internal-only.
* Removes the default parameter from `setActiveHostElement` since it generates extra code and it's an internal function.
* Makes a check in `setElementExitFn` more strict since we're guaranteed for the value to match the type.

PR Close #34183
2019-12-03 16:10:43 -08:00
Pawel Kozlowski fcbc38cb22 test(ivy): ViewContainerRef.move where the old and new indexes are the same (#34156)
PR Close #34156
2019-12-03 16:08:48 -08:00
Pawel Kozlowski 5a52990b91 fix(ivy): allow insertion of views attached to a different container (#34156)
Fixes #34152

PR Close #34156
2019-12-03 16:08:47 -08:00
Pawel Kozlowski 2cf25facd9 fix(ivy): consistenly return -1 from ViewContainerRef.indexOf for non-inserted view (#34156)
PR Close #34156
2019-12-03 16:08:47 -08:00
zuckjet bd820fdf84 docs(core): update render factory description (#34137)
PR Close #34137
2019-12-03 16:07:59 -08:00
arturovt 627814cc4a docs(compiler): fix typos and spelling (#34008)
PR Close #34008
2019-12-03 16:05:32 -08:00
Feliks Khantsis 15d3e741e9 feat: update the locale files (#33556)
PR Close #33556
2019-12-03 15:58:09 -08:00
Feliks Khantsis 3c2438425b feat: add direction property to locale files (#33556)
PR Close #33556
2019-12-03 15:58:09 -08:00
crisbeto e6909bda89 fix(ivy): incorrectly validating html foreign objects inside svg (#34178)
Fixes ngtsc incorrectly logging an unknown element diagnostic for HTML elements that are inside an SVG `foreignObject` with the `xhtml` namespace.

Fixes #34171.

PR Close #34178
2019-12-03 10:29:45 -08:00
JiaLiPassion 539d8f09e0 fix: implement Symbol.specics of Promise (#34162)
Close #34105, #33989

PR Close #34162
2019-12-03 10:29:04 -08:00
Pete Bacon Darwin 6b1a47183d fix(ivy): i18n - trim whitespace when parsing metadata (#34154)
It is possible for HTML formatters to add whitespace
around the content of `i18n` attribute values. This can
make the meaning and custom ids brittle to simple
whitespace formatting.

This commit ensures that the metadata string extracted
from HTML `i18n` attributes is trimmed before being parsed
into meaning, description and custom id.

PR Close #34154
2019-12-03 10:20:53 -08:00
Pete Bacon Darwin 41485599f3 refactor(compiler): remove redundant `metaFromI18nMessage()` function (#34154)
PR Close #34154
2019-12-03 10:20:49 -08:00
Pete Bacon Darwin f6a6f26e0f fix(compiler): i18n - trim whitespace from i18n custom ids (#34154)
Fixes #34147

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

Fixes #34056

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

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

PR Close #34135
2019-12-03 10:15:53 -08:00
Pete Bacon Darwin 8e96b450e2 refactor(ivy): i18n - store legacy message ids separately to custom ids (#34135)
This change will enable the Angular compiler to provide these legacy
message ids by default, which will solve problems with ngcc not knowing
whether to generate legacy ids or not.

PR Close #34135
2019-12-03 10:15:53 -08:00
Pete Bacon Darwin 80d326bd49 refactor(ivy): i18n - remove hack around TS tagged literals (#34135)
When first written there was no way to specify the raw text when
programmatically creating a template tagged literal AST node.

This is now fixed in TS and so the hack is no longer needed.

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

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

This should give us some modest code size savings.

PR Close #34116
2019-12-03 10:14:52 -08:00
Keen Yee Liau dd944ef73f fix(language-service): Insert parentheses for method completion (#33860)
This commit leverages the `insertText` field in `ts.CompletionEntry` to
return a completion text for class methods that includes parentheses.

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

PR Close #33860
2019-12-03 10:13:36 -08:00
Danny Skoog c60d7563a8 style: enforce disallowance of object constructor (#33211)
Applying the `prefer-literal` tslint rule to object enforces the style guide rule https://google.github.io/styleguide/jsguide.html#features-objects-ctor

PR Close #33211
2019-12-03 10:08:25 -08:00
Andrew Scott d4b83681f1 build: disable buildifier print warning for compile=aot deprecation (#34199)
PR Close #34199
2019-12-03 10:07:21 -08:00
Alan Agius 0cd8431698 fix(bazel): don't rely on @angular/core being as a depedency to install @angular/bazel (#34181)
With this change we fix the logic to detect if a package is installed, removing a package and add a package by using the CLI schematic helpers.

Also we save `@angular/bazel` package directly as a `devDependency` when doing `ng-add`.

Closes #34164

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

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

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

```
factory: Svc.fac
```

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

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

Fixes #31556.

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

PR Close #33997
2019-12-02 11:34:26 -08:00
Pete Bacon Darwin d529b55651 fix(ivy): i18n - correctly parse XLIFF placeholders (#34155)
The ViewEngine translation extractor does not convert `-` to `_` for
placeholders that represent custom elements. For example `<app-component>`
gets converted to placeholders like `START_TAG_APP-COMPONENT`.

In `$localize` placeholders are expected to be snake-case, not kebab-case.
So we must normalize them when parsing a translation file that might have
been created via the View Engine translation extractor.

The `$localize` extraction code will normalize these placeholders when
creating translation files in the first place.

Fixes #34151

PR Close #34155
2019-12-02 11:24:48 -08:00
Igor Minar 180a41af68 ci: replace fixme-ivy-aot with no-ivy-aot tag for //packages/language-service/test (#34144)
This target will need to be completely updated once the language service supports Ivy.

PR Close #34144
2019-12-02 11:24:18 -08:00
Igor Minar 1421eff382 build: re-enable template type-checking for various targets across the repo (#34144)
Various targets have their template type-checking disabled in the past.

There is no reason for this any more.

The only target that was tricky was packages/examples/core:core_examples
which was quite broken and I had to fix it up.

Template typechecking is still disabled under blaze, see FW-1753 for more
info.

PR Close #34144
2019-12-02 11:24:18 -08:00
Igor Minar d8792b3c36 fix(bazel): reenable template type checking in ng_module (#34144)
due to an unfortunate condition in 168abc6d6f/packages/compiler-cli/src/ngtsc/program.ts (L430-L434) the typechecking has been disabled when running under bazel + ivy.

As far as I can tell the ivyTemplateTypeCheck flag is now obsolete, so removing this
code from ng_module.bzl is desirable. I'll send a separate PR to remove the flag completely.

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

PR Close #34142
2019-12-02 11:22:45 -08:00
Paul Gschwendtner e7cc1d606a refactor(core): update missing-injectable migration description to match guide (#34125)
Updates the description of the `missing-injectable` migration to mention the second pattern
that will be automatically handled.

PR Close #34125
2019-12-02 11:21:50 -08:00
Keen Yee Liau 7eccbcd30d fix(language-service): Make missing module suggestion instead of error (#34115)
If a Component or Directive is not part of any NgModule, the language
service currently produces an error message. This should not be an
error. Instead, it should be a suggestion.

This PR removes `ng.DiagnosticKind`, and instead reuses
`ts.DiagnosticCategory`.

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

PR Close #34115
2019-12-02 11:19:40 -08:00
Keen Yee Liau 99320e1ffc fix(language-service): use host.error() instead of console.error() (#34114)
`host.error()` would log to file, and makes error messages much easier
to inspect because entries are time-stamped.

PR Close #34114
2019-12-02 11:14:08 -08:00
Keen Yee Liau 39722df41e fix(language-service): Do not produce diagnostics if metadata for NgModule not found (#34113)
The language service incorrectly reports an error if it fails to find
NgModule metadata for a particular Component / Directive. In many cases,
the use case is legit, particularly in test.

This commit removes such diagnostic message and cleans up the interface
for `TypeScriptHost.getTemplateAst()`.

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

PR Close #34113
2019-12-02 11:13:41 -08:00
Joey Perrott c16a79df5c build: add failure message if compile build variable for angular/angular usage (#34109)
To quicken migration for our own developers away from using compile=aot
for setting ivy, we actually fail the build process if the compile
build variable is used with a message to use our config flags instead.

PR Close #34109
2019-12-02 11:13:13 -08:00
Joey Perrott 72d366fe21 build: Add deprecation warning when compile=aot is used for building with Ivy (#34109)
To inform downstream users to switch to using angular_ivy_enabled as the build
variable for setting Ivy, a deprecation message is printed instructing the user
to migrate away from building with compile=*

PR Close #34109
2019-12-02 11:13:13 -08:00
ayazhafiz 1425e63029 fix(language-service): determine correct type for ngFor exported values (#34089)
Currently, variables of an unknown type in an `*ngFor` expression are
refined to have the type of the iterable binding of the `*ngFor`
expression. Unfortunately, this is a bug for variables aliasing
[values exported by
`*ngFor`](https://angular.io/api/common/NgForOf#local-variables),
including `index` and `first`, because they are also given the type of
the binding expression, but they are not of the binding type. For
example, in

```typescript
@Component({
  selector: 'test',
  template: `
    <div *ngFor="let hero of heroes; let i = index; let isFirst = first">
      {{ hero }}
    </div>
  `
})
export class TestComponent {
  heroes: Hero[];
}
```

The local variables `i` and `isFirst` are determined to have a type of
`Hero`, when actually their types are `number` and `boolean`,
respectively.

This commit fixes this bug by checking if the value of a variable in an
`*ngFor` expression is known to be an export and assigning the variable
the type of that export value. Only if the variable does not alias an
export is it typed with the binding value of the `*ngFor` expression.

Closes https://github.com/angular/vscode-ng-language-service/issues/460

PR Close #34089
2019-12-02 11:03:34 -08:00
Igor Minar ea37e82e69 build: consolidate @angular-devkit/build-angular to the root package.json (#34002)
This allows us to update the version of the package in a single place for all tests.

Notable exemption of this is aio which currently doesn't depend on anything installed in the root.

PR Close #34002
2019-12-02 10:49:12 -08:00
Miško Hevery 85b551a388 Revert "refactor: use isObservable provided by rxjs 6.1+ (#27668)"
This reverts commit 92c547830a.
2019-11-27 13:00:59 -08:00
ivanwonder c5006e025f fix(language-service): fix error of array-index out of bounds exception (#33928)
PR Close #33928
2019-11-27 12:48:41 -08:00
ivanwonder 5a227d8d7c feat(language-service): completions support for tuple array (#33928)
PR Close #33928
2019-11-27 12:48:41 -08:00
Pete Bacon Darwin 2fb9b7ff1b fix(ngcc): do not output duplicate ɵprov properties (#34085)
Previously, the Angular AOT compiler would always add a
`ɵprov` to injectables. But in ngcc this resulted in duplicate `ɵprov`
properties since published libraries already have this property.

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

// FW-1750

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

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

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

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

// FW-1747

PR Close #34065
2019-11-27 10:36:36 -08:00
Alan Agius d5aedbe892 refactor(core): update undecorated-classes-with-di migration rerun command (#33958)
With Angular CLI version 9 RC 3 we can run a single migration for a package using the name of the migration schematic.

We need to pass the schematic name as a value to the `migrate-only` option.
Ex:
```
ng update @angular/core --migrate-only migration-v9-undecorated-classes-with-di
```

See: https://github.com/angular/angular-cli/pull/16174

PR Close #33958
2019-11-27 10:36:02 -08:00
Christopher Dahm 92c547830a refactor: use isObservable provided by rxjs 6.1+ (#27668)
Refactor common, core, forms, router to use the isObservable method from rxjs 6.1+. Remove the isObservable method from core.

PR Close #27668
2019-11-27 10:33:45 -08:00
Greg Magolan 005c4a1cc5 build: set default ts_devserver serving_path to /app_bundle.js to match g3 (#33996)
PR Close #33996
2019-11-26 16:09:32 -08:00
Greg Magolan c4335e2817 build: update to nodejs rules 0.41.0 (#33996)
This bring is changes to the @nodejs repository required for https://github.com/angular/angular/pull/33927. See release notes for more details: https://github.com/bazelbuild/rules_nodejs/releases/tag/0.41.0.

rules_nodejs is approaching 1.0 and breaking changes for that release are being made more frequently. In this release, the ts_devserver API changed and it no longer injects html script tags into a provided index.html file. The diff on this commit is large as this breaking change affects quite a few tests.

Also note that we don’t update @angular/bazel schematics and integration/bazel as 0.41.0 is not a recommended update for angular users yet due to the breaking changes in ts_devserver & web_package (now named pkg_web). When a suitable plain npm package that is in progress is finished then it will be possible to easily replace the html injection functionality removed from ts_devserver & pkg_web.

PR Close #33996
2019-11-26 16:09:32 -08:00
ayazhafiz 49804fe017 fix(language-service): determine index types accessed using dot notation (#33884)
Commit 53fc2ed8bf added support for
determining index types accessed using index signatures, but did not
include support for index types accessed using dot notation:

```typescript
const obj<T>: { [key: string]: T };
obj['stringKey']. // gets `T.` completions
obj.stringKey.    // did not peviously get `T.` completions
```

This adds support for determining an index type accessed via dot
notation by rigging an object's symbol table to return the string index
signature type a property access refers to, if that property does not
explicitly exist on the object. This is very similar to @ivanwonder's
work in #29811.

`SymbolWrapper` now takes an additional parameter to explicitly set the
type of the symbol wrapped. This is done because
`SymbolTableWrapper#get` only has access to the symbol of the index
type, _not_ the index signature symbol itself. An attempt to get the
type of the index type will give an error.

Closes #29811
Closes https://github.com/angular/vscode-ng-language-service/issues/126

PR Close #33884
2019-11-26 15:57:07 -08:00
Joey Perrott 6d7d2e439c build: remove remaining internal references to define=compile flag (#33983)
Now that all compile decisions are determined by the define=angular_ivy_enabled
flag, we can remove the setting of the define=compile flag throughout the repo.

PR Close #33983
2019-11-26 16:38:40 -05:00
Joey Perrott 807c89441a build: migrate determining if Ivy is enabled in typescript genrule files to use angular_ivy_enabled (#33983)
Use angular_ivy_enabled to determine if Ivy is being used for the ivy_test_selector.ts symbols.
Additionally, remove the reflect_metadata genrules as we not longer have a "jit" compile option
so all possible invocations result in the same generated file.  Instead we can just commit this
file.

PR Close #33983
2019-11-26 16:38:40 -05:00
Joey Perrott 4022376b3f build: update scripting and tooling to rely on define=angular_ivy_enabled instream of define=compile (#33983)
We need to migrate to using angular_ivy_enabled value to determine whether to use
Ivy or ViewEngine for package building scripts and for size-tracking and
symbol-extract tooling.

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

PR Close #33983
2019-11-26 16:38:40 -05:00
Joey Perrott f9def8cd30 build: create --config=ivy flag to set the angular_ivy_enabled define flag value (#33983)
Beginning of migration away from --define=compile=* to --define=angular_ivy_enabled=*.
Additionally, to make it clearer to developers, we will encourage use of --config=ivy
instead of directy setting the --define flag, this abstraction will allow us more
flexibility as we move foward with relation to our compile decisions at build time.

PR Close #33983
2019-11-26 16:38:40 -05:00
Andrew Kushnir af2d22c43d fix(ivy): support ICUs without "other" cases (#34042)
Prior to this commit, there was a runtime check in i18n logic to make sure "other" case is always present in an ICU. That was not a requirement in View Engine, so ICUs that previously worked may produce errors. This commit removes that restriction and adds support for ICUs without "other" cases.

PR Close #34042
2019-11-26 16:35:55 -05:00
Pete Bacon Darwin fadb2d9004 perf(ivy): do no work if moving a `viewRef` to the same position (#34052)
Move a view only if it would end up at a different place.
Otherwise we would do unnecessary processing like DOM manipulation, query notifications etc.

Thanks to @pkozlowski-opensource for the change.

PR Close #34052
2019-11-26 16:27:27 -05:00
Pete Bacon Darwin f0f426b2d0 fix(ivy): support inserting a `viewRef` that is already present (#34052)
When inserting a `viewRef` it is possible to not provide
an `index`, which is regarded as appending to the end of
the container.

If the `viewRef` already exists in the container, then
this results in a move. But there was a fault in the logic
that computed where to insert the `viewRef` that did not
account for the fact that the `viewRef` was already in
the container, so the insertion `index` was outside the
bounds of the array.

Fixes #33924

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

PR Close #34017
2019-11-25 22:38:42 -05:00
crisbeto 953365d090 refactor(ivy): remove tsickle workaround in chainable instruction (#34019)
Previously if a type was returning itself it would cause an infinite loop in tsickle. We worked around it with a type that alises to `any`. Now that the issue has been resolved in tsickle, we can clean up the workaround.

PR Close #34019
2019-11-25 22:36:00 -05:00
Keen Yee Liau 7cd16b9e2c fix(language-service): function.bind() should not be an error (#34041)
When performing diagnostic checks or completions, we should take into
account members and properties in the base class, if any. Otherwise, the
language service will produce a false error.

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

PR Close #34041
2019-11-25 21:20:56 -05:00
Kara Erickson 1a0ee18d62 fix(ivy): run pre-order hooks in injection order (#34026)
This commit fixes a compatibility bug where pre-order lifecycle
hooks (onInit, doCheck, OnChanges) for directives on the same
host node were executed based on the order the directives were
matched, rather than the order the directives were instantiated
(i.e. injection order).

This discrepancy can cause issues with forms, where it is common
to inject NgControl and try to extract its control property in
ngOnInit. As the NgControl directive is injected, it should be
instantiated before the control value accessor directive (and
thus its hooks should run first). This ensures that the NgControl
ngOnInit can set up the form control before the ngOnInit
for the control value accessor tries to access it.

Closes #32522

PR Close #34026
2019-11-25 18:41:22 -05:00
Igor Minar ed55355363 fix(core): remove deprecated and defunct wtf* apis (#33949)
These apis have been deprecated in v8, so they should stick around till v10,
but since they are defunct we are removing them early so that they don't take up payload size.

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

Fixes #33724.

PR Close #33921
2019-11-25 16:36:44 -05:00
Pawel Kozlowski 31e2bdffa8 perf(ivy): fix creation time micro-benchmarks (#34031)
Micro-benchmarks were broken after we've introduced concept of
DECLARATION_COMPONENT_VIEW on LView (after this change embedded
views must have a pointer to a parent LView).

PR Close #34031
2019-11-25 12:47:58 -05:00
Joey Perrott d80eeb6959 build: remove compile_strategy from ng_module.bzl (#33999)
With the migration of internal i18n rule to use is_ivy_enabled complete, we
can remove compile_strategy as it is now unused.

PR Close #33999
2019-11-25 11:48:25 -05:00
Pawel Kozlowski 478f8821a0 refactor(ivy): extract elementStart first create pass (#33963)
PR Close #33963
2019-11-25 11:41:17 -05:00
Pawel Kozlowski 04b12fc0d6 refactor(ivy): remove isRootView check from getRenderParent (#33988)
The root view case is already covered by the existing code in the
getRenderParent function so no need to have an explicit checks
(and associated memory reads) again.

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

PR Close #34012
2019-11-25 11:38:36 -05:00
Joey Perrott fe91700dc6 build: make ng_module.bzl is_ivy_enabled function public (#33992)
We need to make is_ivy_enabled public to allow the internal i18n
build rule to rely on it rather than relying on compile_strategy.
After we move the internal i18n rule to rely on is_ivy_enabled,
compile_strategy can then be removed.

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

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

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

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

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

Fixes #32214

PR Close #33971
2019-11-22 17:39:35 -05:00
Joey Perrott a4c3ceeddb build: change visible compiler name during ng_module builds to be Ivy/ViewEngine (#33995)
Previously the visible compiler name during the ng_module build action was
ngc/ngtsc.  These names however are only really known to the compiler team.
Instead we should use more general terms for which compiler is used to match
how we speak about compiler choices.

PR Close #33995
2019-11-22 17:37:40 -05:00
Alan Agius 588823b437 refactor(elements): ng-add schematics (#33723)
This PR brings a couple of changes;
- Removes undeed dependencies in bazel targets such as `//packages/common` & `//packages/core`
- Removes RxJs usage
- Adds `document-register-element` to architect test targets
- Use @schematics/angular helpers
- Uses the standard `$source": "projectName"` to get the projectName, which is defined in the `schema.json`
- Use workspace writer to update the workspace config

PR Close #33723
2019-11-22 17:36:47 -05:00
Igor Minar de043a4bcb refactor(bazel): use getattr instead of hasattr in ng_module.bzl (#33765)
getattr improves code readability and makes the code also shorter.

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

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

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

PR Close #33765
2019-11-22 16:52:08 -05:00
Denis Omelkov 621b659aa9 fix(service-worker): allow creating post api requests after cache failure (#33930)
Before creating a mutating http request, service-worker
invalidates lru cache entry and writes to cache storage.
Therefore, cache storage failure can prevent making post requests.
Fix this by catching and logging cache error, add a test case.

Fixes #33793

PR Close #33930
2019-11-22 13:15:56 -05:00
Denis Omelkov 82be6215af refactor(service-worker): set http method in MockRequest constructor (#33930)
Enable to create mocks for mutating http requests in tests
to check more scenarios.

PR Close #33930
2019-11-22 13:15:56 -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
Zaid Al-Omari 828e5c1f79 fix(router): make routerLinkActive work with query params which contain arrays (#22666)
The url_tree equalQueryParams and containsQueryParam methods did not handle query params that has arrays, which resulted in the routerLinkActive to not behave as expected, change was made to ensure query params with arrays are handled correctly

fixes #22223

PR Close #22666
2019-11-21 20:02:33 -05:00
Joey Perrott 7d579b913c build: create bazel define flag, `angular_ivy_enabled`, to build using ivy (#33975)
This introduces a second possible define flag for informing bazel to build with ivy, but
does not remove the old `compile=aot` flag for configuration.

This is the first step in migrating away from using the `compile=aot` define flag.

PR Close #33975
2019-11-21 19:46:57 -05:00
Andrew Kushnir 3d69693692 fix(ivy): remove TNodeType assertion from `directiveInject` instruction (#33948)
The assertion that we have in the `directiveInject` instruction is too restrictive and we came across some pattern where it throws unnecessarily. This commit removes that assertion for now and more detailed investigation is needed to decide is we need to restrict the set of TNodeType again.

This commit also adds a test which triggered the TNodeType.View to come up in the `directiveInject` instruction, so it might be useful to avoid regressions during further refactoring.

PR Close #33948
2019-11-21 17:09:42 -05:00
George Kalpakas acd8734937 fix(service-worker): throw when using the unsupported `versionedFiles` option in config (#33903)
In 5d5c94d83, the deprecated `versionedFiles` option from the SW
asset-group configuration in `ngsw-config.json`. As a result, the
option would be silently ignored and the runtime behavior of the SW
would change (i.e. some files might not be cached and available offline
any more). This change could be easily go unnoticed by the developer.

This commit ensures this does not happen by throwing a build-time error,
when detecting the unsupported `versionedFiles` option with an error
message prompting the user to use the `files` option instead.

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

PR Close #33903
2019-11-21 11:43:58 -08:00
George Kalpakas 4d03ec0e85 refactor(service-worker): use `async/await` in SW config tests (#33903)
PR Close #33903
2019-11-21 11:43:58 -08: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
Andrew Kushnir fd83d9479a fix(ivy): avoid using stale cache in TestBed if module overrides are defined (#33787)
NgModule compilation in JIT mode (that is also used in TestBed) caches module scopes on NgModule defs (using `transitiveCompileScopes` field). Module overrides (defined via TestBed.overrideModule) may invalidate this data by adding/removing items in `declarations` list. This commit forces TestBed to recalculate transitive scopes in case module overrides are present, so TestBed always gets the most up-to-date information.

PR Close #33787
2019-11-20 14:50:27 -08:00
Judy Bogart 87994d2c03 docs: add api doc to sub-packages (#33801)
PR Close #33801
2019-11-20 14:48:50 -08:00
Igor Minar 55748dbc55 fix(core): allow css custom variables/properties in the style sanitizer (#33841)
This change enables "var(--my-var)" to pass through the style sanitizer.

After consulation with our security team, allowing these doesn't create
new attack vectors, so the sanitizer doesn't need to strip them.

Fixes parts of #23485 related to the sanitizer, other use cases discussed
there related to binding have been addressed via other changes to the
class and style handling in the runtime.

Closes #23485

PR Close #33841
2019-11-20 14:47:59 -08:00
Igor Minar 6a5475f65b style(core): improve readability of style_sanizer(_spec).ts (#33841)
PR Close #33841
2019-11-20 14:47:59 -08:00
Andrew Scott 5af3bd4728 perf(ivy): R3TestBed - Do not process NgModuleDefs that have already been processed (#33863)
PR Close #33863
2019-11-20 14:47:42 -08:00
Judy Bogart e13aa65f49 docs: add doc reference to npm package readme (#33911)
PR Close #33911
2019-11-20 14:46:23 -08:00
horn 7b4853bae4 fix(ivy): reset style property using ngStyle fix (#33920)
PR Close #33920
2019-11-20 14:46:00 -08:00
Pawel Kozlowski 51cee50ee3 test(ivy): non-regression test for ViewContainerRef queried on ng-container (#33939)
Closes #31971

PR Close #33939
2019-11-20 14:45:43 -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
Pawel Kozlowski 6bf2531b19 fix(ivy): properly insert views before ng-container with injected ViewContainerRef (#33853)
PR Close #33853
2019-11-19 11:56:43 -08:00
Pawel Kozlowski e698d355c1 refactor(ivy): stricter TNode.inputs typing (#33798)
TNode.inputs are initialised during directives resolution now so we know early
if a node has directives with inputs or no. We don't need to use undefined value
as an indicator that inputs were not resolved yet.

PR Close #33798
2019-11-19 11:56:00 -08:00
Pawel Kozlowski da0c372fdf perf(ivy): don't store public input names in two places (#33798)
Before this change a public name of a directive's input
was stored in 2 places:
- as a key of an object on TNode.index;
- as a value of PropertyAliasValue at the index 1

This PR changes the data structure so the public name is stored
only once as a key on TNode.index. This saves one array entry
for each and every directive input.

PR Close #33798
2019-11-19 11:55:59 -08:00
Pawel Kozlowski 5aec1798eb perf(ivy): add micro-benchmark focused on directive input update (#33798)
PR Close #33798
2019-11-19 11:55:59 -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
Pawel Kozlowski 8555d51bc7 perf(ivy): extract template's instruction first create pass processing (#33856)
This refactorings clearly separates the first and subsequent creation execution
of the `template` instruction. This approach has the following benefits:
- it is clear what happens during the first vs. subsequent executions;
- we can avoid several memory reads and checks after the first creation pass
(there is measurable performance improvement on various benchmarks);
- the template instructions becomes smaller and should become a candidate
for optimisations / inlining faster;

PR Close #33856
2019-11-19 11:41:49 -08:00
Pawel Kozlowski ad4300f52b refactor(ivy): limit reads from TView.consts (#33856)
PR Close #33856
2019-11-19 11:41:49 -08:00
Lars Gyrup Brink Nielsen 3557849371 docs: correct lifecycle hooks feature example (#33886)
PR Close #33886
2019-11-19 11:40:59 -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
Pawel Kozlowski c44415494a refactor(ivy): separate first creation pass in the elementContainerStart instruction (#33894)
PR Close #33894
2019-11-18 16:01:54 -08:00
Pawel Kozlowski 96499c898f refactor(ivy): separate first creation pass in the text instruction (#33894)
PR Close #33894
2019-11-18 16:01:54 -08:00
Alan Agius ffa3936b4c fix(bazel): add terser as an optional peer dependency (#33891)
`ng_package` rule has an implicitly optional depedency on terser a48573efe8/packages/bazel/src/ng_package/ng_package.bzl (L36)

When using this rule without terser being available we get the below error;
```
ERROR: /home/circleci/ng/modules/express-engine/BUILD.bazel:22:1: every rule of type ng_package implicitly depends upon the target '@npm//terser/bin:terser', but this target could not be found because of: no such package '@npm//terser/bin': BUILD file not found in directory 'terser/bin' of external repository @npm. Add a BUILD file to a directory to mark it as a package.
ERROR: Analysis of target '//modules/express-engine:npm_package' failed; build aborted: no such package '@npm//terser/bin': BUILD file not found in directory 'terser/bin' of external repository @npm. Add a BUILD file to a directory to mark it as a package.
```

PR Close #33891
2019-11-18 16:01: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
Pawel Kozlowski 49c9f782ab fix(ivy): properly insert views into ViewContainerRef injected by querying <ng-container> (#33816)
When asking for a ViewContainerRef on <ng-container> we do reuse <ng-container> comment
node as a LContainer's anachor. Before this fix the act of re-using a <ng-container>'s
comment node would result in this comment node being re-appended to the DOM in the wrong
place. With the fix in this PR we make sure that re-using <ng-container>'s comment node
doesn't result in unwanted DOM manipulation (ng-gontainer's comment node is already part
of the DOM and doesn't have to be re-created / re-appended).

PR Close #33816
2019-11-18 16:00:00 -08:00