When `checkTypeOfPipes` is set to `false`, our TCB currently generates
the a statement like the following when pipes appear in the template:
`(_pipe1 as any).transform(args)`
This did enable us to get _some_ information from the Language Service
about pipes in this case because we still had access to the pipe
instance. However, because it is immediately cast to `any`, we cannot
get type information about the transform access. That means actions like "go to
definition", "find references", "quick info", etc. will return
incomplete information or fail altogether.
Instead, this commit changes the TCB to generate `(_pipe1.transform as any)(args)`.
This gives us the ability to get complete information for the LS
operations listed above.
PR Close#40523
This commit changes the reference emitters in the Ivy compiler to prefer
non-aliased exports if they exist. This avoids selecting "private
exports" that may not be stable, e.g. the reexports that have been added
by the View Engine compiler. Such reexports are not stable and are
therefore not suitable to be emitted into partial compilations, as the
output of partial compilations should only reference stable symbols
from upstream libraries.
An alternative solution has been considered where ViewEngine-generated
exports would gain a certain prefix, such that the Ivy compiler could
just exclude those exports (see #41443). However, that solution would
be insufficient in case a library is built using partial compilation and
while depending itself on a VE-compiled library from earlier versions of
Angular, where the magic prefix would be missing. For such libraries,
ngcc would have generated reexports using the declared name if not already
present so this change does result in choosing the correct export.
Because ngcc always generates reexports using the declared name even if
an aliased export is present, this change causes those ngcc-generated
exports to be chosen in downstream libraries using partial compilation.
This is unfortunate as it means that the declared names become
effectively public even if the library author was intentionally
exporting it using an alias. This commit does not address this problem;
it is expected that this should not result in widespread issues across
the library ecosystem.
Fixes#41277
PR Close#41866
We have a check that determines whether to generate property binding instructions for an `ng-template`. The check looks at whether the tag name is exactly `ng-template`, but the problem is that if the tag is placed in a non-HTML namespace (e.g. `svg`), the tag name will actually be `:namespace:ng-template` and the check will fail.
These changes resolve the issue by looking at the tag name without the namespace.
Fixes#41308.
PR Close#41669
Currently if a component defines a template inline, but not through a
string literal, the partial compilation references the template expression
as is. This is problematic because the component declaration can no longer
be processed by the linker later as there is no static interpretation. e.g.
```js
const myTemplate = `...`;
TestCmp.ɵcmp = i0.ɵɵngDeclareComponent({
version: "0.0.0-PLACEHOLDER",
type: TestCmp,
selector: "test-cmp",
ngImport: i0,
template: myTemplate,
isInline: true
});
```
To fix this, we use the the resolved template in such cases so that
the linker can process the template/component declaration as expected.
PR Close#41583
This is follow-up from #41437 and it reduces the amount of code we generate for safe property accesses (`a?.b`) and nullish coalescing (`a ?? b`) by:
1. Reusing variables in nested nullish coalescing expressions.
2. Not initializing temporary variables to `null`. The way our code is generated means that the value will always be overwritten before we compare against it so the initializer didn't really matter.
Fixes#41491.
PR Close#41563
Previously, it was not possible to block a partial-linker from trying to
process a declaration that was defined in a newer version of Angular than
that of the partial-linker. For example, if a partial-linker was published as
part of version 12.0.0, there was no way for a partially-compiled declaration
compiled via version 13.0.0 to tell the 12.0.0 linker that it would be invalid
to attempt to process it.
This commit adds a new `minVersion` property to partial-declarations, which is
interpreted as the "minimum partial-linker version" that can process this
declaration. When selecting a partial-linker for such a declaration, the known
linker version ranges are checked to find the most recent linker whose version
range has an overlap with the interpreted declaration range.
This approach allows us to set a minimum version for a declaration, which
can inform an old partial-linker that will it not be able to accurately
process the declaration.
Note that any pre-release part to versions are ignored in this selection
process.
The file-linker can be configured, via the `unknownDeclarationVersionHandling`
property of `LinkerOptions`, to handle such a situation in one of three ways:
- `error` - the version mismatch is a fatal error
- `warn` - a warning is sent to the logger but the most recent partial-linker
will attempt to process the declaration anyway.
- `ignore` - the most recent partial-linker will, silently, attempt to process
the declaration.
The default is to throw an error.
Closes#41497
PR Close#41578
There were three options being made available to users of the linker:
- ` enableI18nLegacyMessageIdFormat`
- `i18nNormalizeLineEndingsInICUs`
- ` i18nUseExternalIds`
None of these should actually be configurable at linking time
because partially-linked libraries have tighter restrictions on
what i18n options can be used.
This commit removes those options from the `LinkerOptions` interface.
It was considered to add a check for backwards compatibilty to ensure
that if these options were being passed, and were different to the expected
defaults, we would throw an informative error. But from looking at the
Angular CLI (the only known client of the linker) it has never been setting
these options so they have already always been set to the defaults.
BREAKING CHANGE:
Linked libraries no longer generate legacy i18n message ids. Any downstream
application that provides translations for these messages, will need to
migrate their message ids using the `localize-migrate` command line tool.
Closes#40673
PR Close#41554
When an Ivy NgModule is imported into a View Engine build, it doesn't have
metadata.json files that describe it as an NgModule, so it appears to VE
builds as a plain, undecorated class. The error message shown in this
situation generic and confusing, since it recommends adding an @NgModule
annotation to a class from a library.
This commit adds special detection into the View Engine compiler to give a
more specific error message when an Ivy NgModule is imported.
PR Close#41534
When multiple occurrences of the same package exist within a single
TypeScript compilation unit, TypeScript deduplicates the source files
by introducing redirected source file proxies. Such proxies are
recreated during an incremental compilation even if the original
declaration file did not change, which caused the compiler not to reuse
any work from the prior compilation.
This commit changes the incremental driver to recognize a redirected
source file and treat them as their unredirected source file.
PR Close#41448
The Angular compiler has to actively keep default import statements
alive if they were only used in type-only positions, but have been
emitted as value expressions for DI purposes. A problem occurred in
incremental recompilations, where the relationship between an identifier
usage and its corresponding default import would not be considered. This
could result in the removal of the default import statement and caused
a `ReferenceError` at runtime.
This commit fixes the issue by storing the association from an
identifier to its default import declaration on the source file itself,
instead of within the `DefaultImportTracker` instance. The
`DefaultImportTracker` instance is only valid for a single compilation,
whereas the association from an identifier to a default import
declaration is valid as long as the `ts.SourceFile` is the same
instance.
A subsequent commit refactor the `DefaultImportTracker` to no longer
be responsible for registering the association, as its lifetime is
conceptually too short to do so.
Fixes#41377
PR Close#41557
The `emitDecoratorMetadata` compiler option does not have to be enabled
as Angular decorators are transformed by the AOT compiler. Having the
option enabled in our tests can hide issues around import preservation,
as with `emitDecoratorMetadata` enabled the TypeScript compiler itself
does not elide imports even if they are only used in type-positions.
This is unlike having `emitDecoratorMetadata` disabled, however; in that
case the Angular compiler has to actively trick TypeScript into
retaining default imports when an identifier in a type-only position has
been reified into a value position for DI purposes.
A subsequent commit addresses a bug in default import preservation
that relies on this flag being `false`.
PR Close#41557
This commit refactors the generated code for class metadata in partial
compilation mode. Instead of emitting class metadata into a top-level
`ɵsetClassMetadata` call guarded by `ngDevMode` flags, the class
metadata is now declared using a top-level `ɵɵngDeclareClassMetadata`
call.
PR Close#41200
This commit changes the partial compilation so that it outputs declarations
rather than definitions for injectables.
The JIT compiler and the linker are updated to be able to handle these
new declarations.
PR Close#41316
The other similar interfaces were renamed in https://github.com/angular/angular/pull/41119,
but this one was left since it had existed before Ivy. It looks like the interface was
never actually exposed on npm so it is safe to rename this one too.
PR Close#41316
Now that other values were removed from `R3ResolvedDependencyType`,
its meaning can now be inferred from the other properties in the
`R3DeclareDependencyMetadata` type. This commit removes this enum
and updates the code to work without it.
PR Close#41231
This instruction was created to work around a problem with injecting a
`ChangeDetectorRef` into a pipe. See #31438. This fix required special
metadata for when the thing being injected was a `ChangeDetectorRef`.
Now this is handled by adding a flag `InjectorFlags.ForPipe` to the
`ɵɵdirectiveInject()` call, which avoids the need to special test_cases
`ChangeDetectorRef` in the generated code.
PR Close#41231
This commit changes the partial compilation so that it outputs declaration
calls rather than compiled factory functions.
The JIT compiler and the linker are updated to be able to handle these
new declarations.
PR Close#41231
The `ɵɵInjectorDef` interface is internal and should not be published publicly
as part of libraries. This commit updates the compiler to render an opaque
type, `ɵɵInjectorDeclaration`, for this instead, which appears in the typings
for compiled libraries.
PR Close#41119
Th `ɵɵFactoryDef` type will appear in published libraries, via their typings
files, to describe what type dependencies a DI factory has. The parameters
on this type are used by tooling such as the Language Service to understand
the DI dependencies of the class being created by the factory.
This commit moves the type to the `public_definitions.ts` file alongside
the other types that have a similar role, and it renames it to `ɵɵFactoryDeclaration`
to align it with the other declaration types such as `ɵɵDirectiveDeclaration`
and so on.
PR Close#41119
These types are only used in the generated typings files to provide
information to the Angular compiler in order that it can compile code
in downstream libraries and applications.
This commit aliases these types to `unknown` to avoid exposing the
previous alias types such as `ɵɵDirectiveDef`, which are internal to
the compiler.
PR Close#41119
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
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
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
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
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
In Angular programs, changing a file may require other files to be
emitted as well due to implicit NgModule dependencies. For example, if
the selector of a directive is changed then all components that have
that directive in their compilation scope need to be recompiled, as the
change of selector may affect the directive matching results.
Until now, the compiler solved this problem using a single dependency
graph. The implicit NgModule dependencies were represented in this
graph, such that a changed file would correctly also cause other files
to be re-emitted. This approach is limited in a few ways:
1. The file dependency graph is used to determine whether it is safe to
reuse the analysis data of an Angular decorated class. This analysis
data is invariant to unrelated changes to the NgModule scope, but
because the single dependency graph also tracked the implicit
NgModule dependencies the compiler had to consider analysis data as
stale far more often than necessary.
2. It is typical for a change to e.g. a directive to not affect its
public API—its selector, inputs, outputs, or exportAs clause—in which
case there is no need to re-emit all declarations in scope, as their
compilation output wouldn't have changed.
This commit implements a mechanism by which the compiler is able to
determine the impact of a change by comparing it to the prior
compilation. To achieve this, a new graph is maintained that tracks all
public API information of all Angular decorated symbols. During an
incremental compilation this information is compared to the information
that was captured in the most recently succeeded compilation. This
determines the exact impact of the changes to the public API, which
is then used to determine which files need to be re-emitted.
Note that the file dependency graph remains, as it is still used to
track the dependencies of analysis data. This graph does no longer track
the implicit NgModule dependencies, which allows for better reuse of
analysis data.
These changes also fix a bug where template type-checking would fail to
incorporate changes made to a transitive base class of a
directive/component. This used to be a problem because transitive base
classes were not recorded as a transitive dependency in the file
dependency graph, such that prior type-check blocks would erroneously
be reused.
This commit also fixes an incorrectness where a change to a declaration
in NgModule `A` would not cause the declarations in NgModules that
import from NgModule `A` to be re-emitted. This was intentionally
incorrect as otherwise the performance of incremental rebuilds would
have been far worse. This is no longer a concern, as the compiler is now
able to only re-emit when actually necessary.
Fixes#34867Fixes#40635Closes#40728
PR Close#40947
For certain generated function calls, the compiler emits a 'PURE' annotation
which informs Terser (the optimizer) about the purity of a specific function
call. This commit expands that system to produce a new Closure-specific
'pureOrBreakMyCode' annotation when targeting the Closure optimizer instead
of Terser.
PR Close#41021
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
Our approach for handling cyclic imports results in code that is
not easy to tree-shake, so it is not suitable for publishing in a
library.
When compiling in partial compilation mode, we are targeting
such library publication, so we now create a fatal diagnostic
error instead of trying to handle the cyclic import situation.
Closes#40678
PR Close#40782
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
Produces a diagnostic when we cannot resolve a component's external style sheet or external template.
The previous behavior was to throw an exception, which crashed the
Language Service.
fixes angular/vscode-ng-language-service#1079
PR Close#40660
Normally the template parsing operation normalizes all template line endings
to '\n' only. This normalization operation causes source mapping errors when
the original template uses '\r\n' line endings.
The compiler already parses templates again to create a "diagnostic"
template AST with accurate source maps, to avoid other parsing issues that
affect source map accuracy. This commit configures this diagnostic parse to
also preserve line endings.
PR Close#40597
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
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
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
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
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
The parser has a list of tag definitions that it uses when parsing the template. Each tag has a
`contentType` which tells the parser what kind of content the tag should contain. The problem is
that the browser has two separate `title` tags (`HTMLTitleElement` and `SVGTitleElement`) and each
of them has to have a different `contentType`, otherwise the parser will throw an error further down
the pipeline.
These changes update the tag definitions so that each tag name can have multiple content types
associated with it and the correct one can be returned based on the element's prefix.
Fixes#31503.
PR Close#40259