Commit Graph

43 Commits

Author SHA1 Message Date
JoostK eb74a96935 refactor(compiler-cli): separate used components from used directives in partial declaration (#41104)
The partial declaration of a component includes the list of directives
that are used in its template, including some metadata of the directive
which can be used during actual compilation of the component. Used
components are currently part of this list, as components are also
directives. This commit splits the used components into a dedicate
property in the partial declaration, which allows for template
compilation to optimize the generated code for components.

PR Close #41104
2021-03-17 09:09:29 -07:00
Pete Bacon Darwin 5565810bd6 refactor(compiler-cli): implement `ɵɵngDeclareNgModule` and `ɵɵngDeclareInjector` (#41080)
This commit changes the partial compilation so that it outputs declaration
calls rather than definition calls for NgModules and Injectors.

The JIT compiler and the linker are updated to be able to handle these
new declarations.

PR Close #41080
2021-03-15 13:26:51 -07:00
Misko Hevery 70962465b5 fix(core): Switch `emitDistinctChangesOnlyDefaultValue` to true (#41121)
BREAKING CHANGE:

Switching default of `emitDistinctChangesOnlyDefaultValue`
which changes the default behavior and may cause some applications which
rely on the incorrect behavior to fail.

`emitDistinctChangesOnly` flag has also been deprecated and will be
removed in a future major release.

The previous implementation would fire changes `QueryList.changes.subscribe`
whenever the `QueryList` was recomputed. This resulted in an artificially
high number of change notifications, as it is possible that recomputing
`QueryList` results in the same list. When the `QueryList` gets recomputed
is an implementation detail, and it should not be the thing that determines
how often change event should fire.

Unfortunately, fixing the behavior outright caused too many existing
applications to fail. For this reason, Angular considers this fix a
breaking fix and has introduced a flag in `@ContentChildren` and
`@ViewChildren`, that controls the behavior.

```
export class QueryCompWithStrictChangeEmitParent {
  @ContentChildren('foo', {
    // This option is the new default with this change.
    emitDistinctChangesOnly: true,
  })
  foos!: QueryList<any>;
}
```
For backward compatibility before v12
`emitDistinctChangesOnlyDefaultValue` was set to `false. This change
changes the default to `true`.

PR Close #41121
2021-03-12 10:47:56 -08:00
Pete Bacon Darwin 2ebe2bcb2f refactor(compiler): move factory out of injector definition (#41022)
Previously, injector definitions contained a `factory` property that
was used to create a new instance of the associated NgModule class.

Now this factory has been moved to its own `ɵfac` static property on the
NgModule class itself. This is inline with how directives, components and
pipes are created.

There is a small size increase to bundle sizes for each NgModule class,
because the `ɵfac` takes up a bit more space:

Before:

```js
let a = (() => {
  class n {}
  return n.\u0275mod = c.Cb({type: n}),
  n.\u0275inj = c.Bb({factory: function(t) { return new (t || n) }, imports: [[e.a.forChild(s)], e.a]}),
  n
})(),
```

After:

```js
let a = (() => {
  class n {}
  return n.\u0275fac = function(t) { return new (t || n) },
  n.\u0275mod = c.Cb({type: n}),
  n.\u0275inj = c.Bb({imports: [[r.a.forChild(s)], r.a]}),
  n
})(),
```

In other words `n.\u0275fac = ` is longer than `factory: ` (by 5 characters)
and only because the tooling insists on encoding `ɵ` as `\u0275`.

This can be mitigated in a future PR by only generating the `ɵfac` property
if it is actually needed.

PR Close #41022
2021-03-08 15:31:30 -08:00
Igor Minar 9c210281d4 feat(compiler): emit @__PURE__ or @pureOrBreakMyCode annotations in the generated code (#41096)
This change marks all relevant define* callsites as pure, causing the compiler to
emmit either @__PURE__ or @pureOrBreakMyCode annotation based on whether we are
compiling code annotated for closure or terser.

This change is needed in g3 where we don't run build optimizer but we
need the code to be annotated for the closure compiler.

Additionally this change allows for simplification of CLI and build optimizer as they
will no longer need to rewrite the generated code (there are still other places where
a build optimizer rewrite will be necessary so we can't remove it, we can only simplify it).

PR Close #41096
2021-03-08 10:30:08 -08:00
Kristiyan Kostadinov cdf1ea1951 refactor(compiler): retrieve variables from context inside nested template listener (#40833)
This is a pre-requisite for #40360. Given the following template which has a listener
that references a variable from a parent template (`name`):

```
<ng-template let-name="name">
  <button (click)="hello(name)"></button>
</ng-template>
```

We generate code that looks that looks like. Note how we access `name` through `ctx`:

```js
function template(rf, ctx) {
  if (rf & 1) {
    const r0 = ɵɵgetCurrentView();
    ɵɵelementStart(0, "button", 2);
    ɵɵlistener("click", function() {
      ɵɵrestoreView(r0);
      const name_r0 = ctx.name; // Note the `ctx.name` access here.
      const ctx_r1 = ɵɵnextContext();
      return ctx_r1.log(name_r0);
    });
    ɵɵelementEnd();
  }
}
```

This works fine at the moment, because the template context object can't be changed after creation.
The changes in #40360 allow for the object to be changed, which means that the `ctx` reference
inside the listener will be out of date, because it was bound during creation mode.

This PR aims to address the issue by accessing the context inside listeners through the saved
view reference. With the new code, the generated code from above will look as follows:

```js
function template(rf, ctx) {
  if (rf & 1) {
    const r0 = ɵɵgetCurrentView();
    ɵɵelementStart(0, "button", 2);
    ɵɵlistener("click", function() {
      const restoredCtx = ɵɵrestoreView(r0);
      const name_r0 = restoredCtx.name;
      const ctx_r1 = ɵɵnextContext();
      return ctx_r1.log(name_r0);
    });
    ɵɵelementEnd();
  }
}
```

PR Close #40833
2021-02-17 11:45:46 -08:00
Pete Bacon Darwin 9cb43fb507 refactor(compiler-cli): implement `ɵɵngDeclarePipe()` (#40803)
This commit implements creating of `ɵɵngDeclarePipe()` calls in partial
compilation, and processing of those calls in the linker and JIT compiler.

See #40677

PR Close #40803
2021-02-12 09:00:16 -08:00
JoostK c18c7e23ec fix(compiler): exclude trailing whitespace from element source spans (#40513)
If the template parse option `leadingTriviaChars` is configured to
consider whitespace as trivia, any trailing whitespace of an element
would be considered as leading trivia of the subsequent element, such
that its `start` span would start _after_ the whitespace. This means
that the start span cannot be used to mark the end of the current
element, as its trailing whitespace would then be included in its span.
Instead, the full start of the subsequent element should be used.

To harden the tests that for the Ivy parser, the test utility `parseR3`
has been adjusted to use the same configuration for `leadingTriviaChars`
as would be the case in its production counterpart `parseTemplate`. This
uncovered another bug in offset handling of the interpolation parser,
where the absolute offset was computed from the start source span
(which excludes leading trivia) whereas the interpolation expression
would include the leading trivia. As such, the absolute offset now also
uses the full start span.

Fixes #39148

PR Close #40513
2021-01-28 08:53:02 -08:00
JoostK 6db342a87a test(compiler-cli): reset i18n message index in compliance test macro (#40529)
The compliance test runner has various macros that process the
expectation files before actually checking their contents. Among those
macros are i18n helpers, which uses a global message counter to be able
to uniquely identify ICU variables.

Because of the global nature of this message index, it was susceptible
to ordering issues which could result in flaky tests, although it failed
very infrequently.

This commit resets the global message counter before applying the macros.
As a result of this change an expectation file had to be updated; this
is actually a bug fix as said test used to fail if run in isolation (if
`focusTest: true` was set for that particular testcase).

PR Close #40529
2021-01-25 10:55:42 -08:00
Misko Hevery d516113803 refactor(core): Remove the need for explicit static query instruction (#40091)
Because the query now has `flags` which specify the mode, the static query
instruction can now be remove. It is simply normal query with `static` flag.

PR Close #40091
2021-01-14 13:55:02 -08:00
Misko Hevery e32b6256ce fix(core): `QueryList` should not fire changes if the underlying list did not change. (#40091)
Previous implementation would fire changes `QueryList.changes.subscribe`
whenever the `QueryList` was recomputed. This resulted in artificially
high number of change notifications, as it is possible that recomputing
`QueryList` results in the same list. When the `QueryList` gets recomputed
is an implementation detail and it should not be the thing which determines
how often change event should fire.

This change introduces a new `emitDistinctChangesOnly` option for
`ContentChildren` and `ViewChildren`.

```
export class QueryCompWithStrictChangeEmitParent {
  @ContentChildren('foo', {
    // This option will become the default in the future
    emitDistinctChangesOnly: true,
  })
  foos!: QueryList<any>;
}
```

PR Close #40091
2021-01-14 13:55:02 -08:00
JoostK b48eabddb8 refactor(compiler-cli): include `template` source directly inside declaration object (#40383)
The `template` and `isInline` fields were previously stored in a nested
object, which was initially done to accommodate for additional template
information to support accurate source maps for external templates. In
the meantime the source mapping has been accomplished in a different
way, and I feel this flattened structure is simpler and smaller so is
preferable over the nested object. This change also makes the `isInline`
property optional with a default value of `false`.

PR Close #40383
2021-01-11 15:37:12 -08:00
Kristiyan Kostadinov 104546569e fix(compiler): incorrectly interpreting some HostBinding names (#40233)
Currently when analyzing the metadata of a directive, we bundle together the bindings from `host`
and the `HostBinding` and `HostListener` together. This can become a problem later on in the
compilation pipeline, because we try to evaluate the value of the binding, causing something like
`@HostBinding('class.foo') public true = 1;` to be treated the same as
`host: {'[class.foo]': 'true'}`.

While looking into the issue, I noticed another one that is closely related: we weren't treating
quoted property names correctly. E.g. `@HostBinding('class.foo') public "foo-bar" = 1;` was being
interpreted as `classProp('foo', ctx.foo - ctx.bar)` due to the same issue where property names
were being evaluated.

These changes resolve both of the issues by treating all `HostBinding` instance as if they're
reading the property from `this`. E.g. the `@HostBinding('class.foo') public true = 1;` from above
is now being treated as `host: {'[class.foo]': 'this.true'}` which further down the pipeline becomes
`classProp('foo', ctx.true)`. This doesn't have any payload size implications for existing code,
because we've always been prefixing implicit property reads with `ctx.`. If the property doesn't
have an identifier that can be read using dotted access, we convert it to a quoted one (e.g.
`classProp('foo', ctx['is-foo']))`.

Fixes #40220.
Fixes #40230.
Fixes #18698.

PR Close #40233
2021-01-07 13:15:46 -08:00
Pete Bacon Darwin 0fd06e5ab8 test(compiler-cli): add external template source-map tests (#40237)
This commit migrates, and supplements, compliance tests that
check the source-mapping of external templates.

PR Close #40237
2021-01-07 13:12:53 -08:00
Pete Bacon Darwin 9f662e1313 test(compiler-cli): tidy up the line-ending compliance test TEST_CASES (#40237)
Previously the names of the source and expectation files were often reused,
which caused potential confusion.

There is now a single source file for
each test-case, which is important when they are being compiled with different
compiler options, since the GOLDEN_PARTIAL file will only contain one copy
per file name.

The names of the expectation files have now been changed so that is clearer
which test-case they are related to.

PR Close #40237
2021-01-07 13:12:53 -08:00
Bjarki 6a9d7e5969 refactor(core): express trusted constants with tagged template literals (#40082)
The trustConstantHtml and trustConstantResourceUrl functions are only
meant to be passed constant strings extracted from Angular application
templates, as passing other strings or variables could introduce XSS
vulnerabilities.

To better protect these APIs, turn them into template tags. This makes
it possible to assert that the associated template literals do not
contain any interpolation, and thus must be constant.

Also add tests for the change to prevent regression.

PR Close #40082
2021-01-05 13:56:57 -08:00
JoostK e23fd1f382 refactor(compiler-cli): emit `forwardRef` invocation for forward type references (#40117)
The types of directives and pipes that are used in a component's
template may be emitted into the partial declaration wrapped inside a
closure, which is needed when the type is declared later in the module.
This poses a problem for JIT compilation of partial declarations, as
this closure is indistinguishable from a class reference itself. To mark
the forward reference function as such, this commit changes the partial
declaration codegen to emit a `forwardRef` invocation wrapped around
the closure, which ensures that the closure is properly tagged as a
forward reference. This allows the forward reference to be treated as
such during JIT compilation.

PR Close #40117
2020-12-22 08:39:58 -08:00
Andrew Kushnir caa4666335 fix(compiler): avoid duplicate i18n blocks for i18n attrs on elements with structural directives (#40077)
Currently when `ɵɵtemplate` and `ɵɵelement` instructions are generated by compiler, all static attributes are
duplicated for both instructions. As a part of this duplication, i18n translation blocks for static i18n attributes
are generated twice as well, causing duplicate entries in extracted translation files (when Ivy extraction mechanisms
are used). This commit fixes this issue by introducing a cache for i18n translation blocks (for static attributes
only).

Also this commit further aligns `ɵɵtemplate` and `ɵɵelement` instruction attributes, which should help implement
more effective attributes deduplication logic.

Closes #39942.

PR Close #40077
2020-12-15 13:40:09 -08:00
Zach Arend 9dedb62494 test(compiler-cli): fix i18n error tests (#40026)
Refactors the i18n error tests to be unit tests in ngtsc_spec.ts. There
is two reasons for doing this.

First is that the tests in compliace_old expected an expection to be be
thrown but did not fail the test if no exception was thrown. That means
that this test could miss catching a bug. It is also a big hacky to call
compile directly and expect an exception to be thrown for diagnostics.

Also, this can easily be unit tested and an end-to-end test is not
necessary since we are not making use of the goldfiles for these tests.

It is easier to maintain and less hacky to validate that we get helpful
error messages when nesting i18n sections by calling getDiagnostics
directly.

PR Close #40026
2020-12-15 13:30:52 -08:00
JoostK 1f73af77a7 refactor(compiler-cli): use `ngDevMode` guard for `setClassMetadata` call (#39987)
Prior to this change, the `setClassMetadata` call would be invoked
inside of an IIFE that was marked as pure. This allows the call to be
tree-shaken away in production builds, as the `setClassMetadata` call
is only present to make the original class metadata available to the
testing infrastructure. The pure marker is problematic, though, as the
`setClassMetadata` call does in fact have the side-effect of assigning
the metadata into class properties. This has worked under the assumption
that only build optimization tools perform tree-shaking, however modern
bundlers are also able to elide calls that have been marked pure so this
assumption does no longer hold. Instead, an `ngDevMode` guard is used
which still allows the call to be elided but only by tooling that is
configured to consider `ngDevMode` as constant `false` value.

PR Close #39987
2020-12-10 13:23:13 -08:00
Pete Bacon Darwin 85760cb170 test(compiler-cli): fix and re-enable compliance source-map tests (#40040)
These tests started failing because they had type-check
errors in their templates, and a recent commit turned on
full template type-checking by default.\

This commit fixes those templates and updates the expected
files as necessary.

PR Close #40040
2020-12-09 09:21:32 -08:00
Andrew Scott cfb094dbaf test(compiler-cli): temporary disable source mapping tests which have errors (#40033)
These tests do not pass the typecheck phase of the compiler and fail.
The option to disable typechecking was removed recently so these tests
need to be fixed to be valid applications.

PR Close #40033
2020-12-08 19:17:22 -08:00
Andrew Scott 6cc9ab120b refactor(compiler-cli): remove internal only flag to disable type checking (#40013)
A couple reasons to justify removing the flag:

* It adds code to the compiler that is only meant to support test cases
and not any production. We should avoid code in that's only
meant to support tests.
* The flag enables writing tests that do not mimic real-world behavior
because they allow invalid applications

PR Close #40013
2020-12-08 16:19:07 -08:00
Pete Bacon Darwin b8714c384f test(compiler-cli): add source-map compliance tests for inline-templates (#39939)
This test migrates source-mapping tests to the new compliance test framework.
The original tests are found in the file at:
`packages/compiler-cli/test/ngtsc/template_mapping_spec.ts`.

These new tests also check the mappings resulting from partial compilation
followed by linking, after flattening the pair of source-maps that each
process generates.

Note that there are some differences between the mappings for full compile
and linked compile modes, due to how TypeScript and Babel use source-span
information on AST nodes.  To accommodate this, there are two expectation
files for most of these source files.

PR Close #39939
2020-12-07 16:21:07 -08:00
Pete Bacon Darwin 09ba30ef29 test(compiler-cli): improve compliance test compile mode filtering (#39939)
Previously one could set a flag in a `TEST_CASES.json` file to exclude
the test-cases from being run if the input files were being compiled
partially and then linked.

There are also scenarios where one might want to exclude test-cases
from "full compile" mode test runs.

This commit changes the compliance test tooling to support a new
property `compilationModeFilter`, which is an array containing one or
more of `"full compile"` and `"linked compile"`. Only the tests
whose `compilationModeFilter` array contains the current compilation
mode will be run.

PR Close #39939
2020-12-07 16:21:04 -08:00
Pete Bacon Darwin 2afa3801bc test(compiler-cli): fix TEST_CASES.json schema (#39939)
The schema accidentally included the `expectedErrors` and `extraCheck`
properties below the `files` property instead of below the `expectations`
property.

PR Close #39939
2020-12-07 16:21:01 -08:00
Pete Bacon Darwin d2042a0da2 refactor(compiler-cli): use semver range checking for partial versions (#39847)
The partial compiler will add a version number to the objects that are
generated so that the linker can select the appropriate partial linker
class to process the metadata.

Previously this version matching was a simple number check. Now
the partial compilation writes the current Angular compiler version
into the generated metadata, and semantic version ranges are used
to select the appropriate partial linker.

PR Close #39847
2020-12-04 10:26:17 -08:00
JoostK 76ae87406f test(compiler-cli): convert components & directives compliance tests (#39920)
This commit converts the components & directives compliance tests taken
from `r3_compiler_compliance_spec.ts` to the new test runner.

PR Close #39920
2020-12-03 13:41:20 -08:00
JoostK efd0d33391 test(compiler-cli): convert bindings compliance tests (#39862)
This commit converts the binding compliance tests taken from
`r3_view_compiler_binding_spec.ts` to the new test runner.

PR Close #39862
2020-12-02 14:56:38 -08:00
Kristiyan Kostadinov 744f46c37d refactor(compiler-cli): migrate view compiler directive tests (#39929)
Migrates the compliance tests under `r3_view_compiler_directives` to the new format.

PR Close #39929
2020-12-02 14:55:58 -08:00
Kristiyan Kostadinov eac85b4e23 test(compiler-cli): migrate view compliance tests (#39914)
Migrates the `r3_view_compiler` tests to the new format.

PR Close #39914
2020-12-01 15:12:40 -08:00
Kristiyan Kostadinov 50962c1b0b test(compiler-cli): migrate template compliance tests (#39871)
Migrates the `r3_view_compiler_template` tests to the new format.
Also introduces a new matcher for unique function names.

PR Close #39871
2020-12-01 14:58:11 -08:00
Kristiyan Kostadinov 40b127c7a3 test(compiler-cli): migrate listener compliance tests (#39867)
Migrates the `r3_view_compiler_listener` compliance tests to the new format.

PR Close #39867
2020-12-01 14:56:59 -08:00
Kristiyan Kostadinov 97ea2c7bfd test(compiler-cli): migrate input/output compliance tests (#39867)
Migrates the `r3_view_compiler_input_outputs` compliance tests to the new format.

PR Close #39867
2020-12-01 14:56:59 -08:00
Kristiyan Kostadinov 71a5314335 test(compiler-cli): migrate providers compliance tests (#39878)
Migrates the `r3_view_compiler_providers` compliance tests to the new format.

PR Close #39878
2020-11-30 12:07:02 -08:00
JoostK c5619ca56e test(compiler-cli): convert styling compliance tests (#39881)
This commit converts the DI compliance tests taken from
`r3_view_compiler_styling_spec.ts` to the new test runner.

PR Close #39881
2020-11-30 11:23:30 -08:00
JoostK c622b17b0d test(compiler-cli): convert di compliance tests (#39863)
This commit converts the DI compliance tests taken from
`r3_view_compiler_di_spec.ts` to the new test runner.

PR Close #39863
2020-11-30 11:21:23 -08:00
Pete Bacon Darwin 2786292780 test(compiler-cli): migrate i18n compliance tests (#39661)
This commit provides the machinery for the new file-based compliance test
approach for i18n tests, and migrates the i18n tests to this new format.

PR Close #39661
2020-11-25 11:08:39 -08:00
JoostK e75244ec00 feat(compiler-cli): support for partial compilation of components (#39707)
This commit implements partial compilation of components, together with
linking the partial declaration into its full AOT output.

This commit does not yet enable accurate source maps into external
templates. This requires additional work to account for escape sequences
which is non-trivial. Inline templates that were represented using a
string or template literal are transplated into the partial declaration
output, so their source maps should be accurate. Note, however, that
the accuracy of source maps is not currently verified in tests; this is
also left as future work.

The golden files of partial compilation output have been updated to
reflect the generated code for components. Please note that the current
output should not yet be considered stable.

PR Close #39707
2020-11-24 13:05:49 -08:00
JoostK bfa20e11a6 test(compiler-cli): fix documentation and JSON schema references in compliance tests (#39707)
The JSON schema reference was off-by-one, preventing IDEs from finding
the file and offering suggestions and documentation. Additionally the
name of the golden file was slightly off.

PR Close #39707
2020-11-24 13:05:37 -08:00
Pete Bacon Darwin eea5d6b38f test(compiler-cli): convert element related compliance tests (#39617)
This commit converts a set of compliance tests in the `r3_compiler_compliance_spec.ts`
file to the new testing approach.

PR Close #39617
2020-11-13 11:25:57 -08:00
Pete Bacon Darwin 10525af67b test(compiler-cli): generate golden files for partial compilation (#39617)
This commit adds a JS script that can generate a partial golden file
for test cases in the compiler compliance tests.

PR Close #39617
2020-11-13 11:25:56 -08:00
Pete Bacon Darwin 793d66afa5 test(compiler-cli): create "full compile" compliance test rules (#39617)
This commit contains the basic runner logic and a couple of sample test cases
for the "full compile" compliance tests, where source files are compiled
to full definitions and checked against expectations.

PR Close #39617
2020-11-13 11:25:56 -08:00