Commit Graph

1221 Commits

Author SHA1 Message Date
Filipe Silva 60a8888b4f fix(compiler-cli): log ngcc skipping messages as debug instead of info (#30232)
Related to https://github.com/angular/angular-cli/issues/14194, https://github.com/angular/angular-cli/pull/14320

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

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

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

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

Fixes #29939

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

This PR resolves FW-1275.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Related #30011

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

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

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

T[] = any

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

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

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

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

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

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

Fixes #30079

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

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

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

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

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

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

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

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

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

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

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

Fixes #30064

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

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

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

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

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

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

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

Resolves FW-1272

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

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

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

Resolves FW-1271

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

This PR resolves FW-1274.

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

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

Fixes #29960

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

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

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

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

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

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

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

Testing strategy: TCB tests included.

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

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

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

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

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

Testing strategy: tested in the t2_binder tests.

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

Testing strategy: TCB tests included.

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

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

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

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

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

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

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

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

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

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

Testing strategy: TCB tests included.

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

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

Testing strategy: TCB tests included.

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

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

Testing strategy: Template type-checking tests included.

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

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

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

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

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

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

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

Testing strategy: TCB tests included.

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

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

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

Testing strategy: TCB tests included.

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh 9f5288dad3 feat(ivy): type-checking for some previously unsupported expressions (#29698)
This commit adds support for the generation of type-checking expressions for
forms which were previously unsupported:

* array literals
* map literals
* keyed property accesses
* non-null assertions

Testing strategy: TCB tests included.

Fixes #29327
FW-1218 #resolve

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh e3d5d41140 test(ivy): add tests for type_check_block.ts (#29698)
This commit adds a test suite for the Type Check Block generation which
doesn't require running the entire compiler (specifically, it doesn't even
require the creation of a ts.Program).

PR Close #29698
2019-04-19 11:15:25 -07:00
Alex Rickabaugh 0df719a461 feat(ivy): register NgModules with ids when compiled with AOT (#29980)
This commit adds registration of AOT compiled NgModules that have 'id'
properties set in their metadata. Such modules have a call to
registerNgModuleType() emitted as part of compilation.

The JIT behavior of this code is already in place.

This is required for module loading systems (such as g3) which rely on
getModuleFactory().

PR Close #29980
2019-04-19 11:12:21 -07:00
Alex Rickabaugh 4229b41057 test(ivy): replace ɵ with escape code (#29980)
PR Close #29980
2019-04-19 11:12:20 -07:00
Filipe Silva e1f51eaa55 feat(compiler-cli): export tooling definitions (#29929)
PR Close #29929
2019-04-17 17:23:01 -07:00
JoostK 83291f01b0 fix(ivy): let ngtsc unwrap expressions when resolving `forwardRef` (#29886)
Previously, ngtsc would fail to resolve `forwardRef` calls if they
contained additional parenthesis or casts. This commit changes the
behavior to first unwrap the AST nodes to see past such insignificant
nodes, resolving the issue.

Fixes #29639

PR Close #29886
2019-04-17 12:52:34 -07:00
JoostK 725148a44d feat(ivy): let ngtsc statically evaluate `Array.concat` calls (#29887)
Previously, only static evaluation of `Array.slice` was implemented in
ngtsc's static evaluator. This commit adds support for `Array.concat`.

Closes #29835

PR Close #29887
2019-04-17 12:49:13 -07:00
Filipe Silva 86a3f90954 fix(compiler-cli): pass config path to ts.parseJsonConfigFileContent (#29872)
The config path is an optional argument to `ts.parseJsonConfigFileContent`. When passed, it is added to the returned object as `options.configFilePath`, and `tsc` itself passes it in.

The new TS 3.4 [incremental](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html) build functionality relies on this property being present: 025d826339/src/compiler/emitter.ts (L56-L57)

When using The compiler-cli `readConfiguration` the config path option isn't passed, preventing consumers (like @ngtools/webpack) from obtaining a complete config object.

This PR fixes this omission and should allow JIT users of @ngtools/webpack to set the `incremental` option in their tsconfig and have it be used by the TS program.

I tested this in JIT and saw a small decrease in build times in a small project. In AOT the incremental option didn't seem to be used at all, due to how `ngc` uses the TS APIs.

Related to https://github.com/angular/angular-cli/issues/13941.

PR Close #29872
2019-04-16 13:36:08 -07:00
Alex Rickabaugh 9147092a15 Revert "feat(ivy): use i18n locale data to determine the plural form of ICU expressions (#29249)" (#29918)
This reverts commit 6a8cca7975.

PR Close #29918
2019-04-15 16:55:51 -07:00
Olivier Combe 6a8cca7975 feat(ivy): use i18n locale data to determine the plural form of ICU expressions (#29249)
Plural ICU expressions depend on the locale (different languages have different plural forms). Until now the locale was hard coded as `en-US`.
For compatibility reasons, if you use ivy with AOT and bootstrap your app with `bootstrapModule` then the `LOCALE_ID` token will be set automatically for ivy, which is then used to get the correct plural form.
If you use JIT, you need to define the `LOCALE_ID` provider on the module that you bootstrap.
For `TestBed` you can use either `configureTestingModule` or `overrideProvider` to define that provider.
If you don't use the compat mode and start your app with `renderComponent` you need to call `ɵsetLocaleId` manually to define the `LOCALE_ID` before bootstrap. We expect this to change once we start adding the new i18n APIs, so don't rely on this function (there's a reason why it's a private export).
PR Close #29249
2019-04-15 10:40:26 -07:00
Andrew Kushnir 6c018001d3 fix(ivy): keep i18n-annotated attributes in element attribute list (#29856)
Prior to this change, element attributes annotated with i18n- prefix were removed from element attribute list and processed separately by i18n-specific logic. This behavior is causing issues with directive matching, since attributes are not present in the list of attrs for matching purposes. This commit updates i18n logic to retain attributes in the main attribute list, thus allowing directive matching logic to work correctly.

PR Close #29856
2019-04-12 16:57:42 -07:00
Alex Rickabaugh b0578061ce refactor(ivy): use ɵɵ instead of Δ for now (#29850)
The `Δ` caused issue with other infrastructure, and we are temporarily
changing it to `ɵɵ`.

This commit also patches ts_api_guardian_test and AIO to understand `ɵɵ`.

PR Close #29850
2019-04-11 16:27:56 -07:00
Olivier Combe 91c7b451d5 feat(ivy): support i18n without closure (#28689)
So far using runtime i18n with ivy meant that you needed to use Closure and `goog.getMsg` (or a polyfill). This PR changes the compiler to output both closure & non-closure code, while the unused option will be tree-shaken by minifiers.
This means that if you use the Angular CLI with ivy and load a translations file, you can use i18n and the application will not throw at runtime.
For now it will not translate your application, but at least you can try ivy without having to remove all of your i18n code and configuration.
PR Close #28689
2019-04-11 08:28:45 -07:00
Kristiyan Kostadinov def73a6728 perf(ivy): avoid storing raw selectors in projectionDef (#29578)
Currently in Ivy we pass both the raw and parsed selectors to the projectionDef instruction, because the parsed selectors are used to match most nodes, whereas the raw ones are used to match against nodes with the ngProjectAs attribute. The raw selectors add a fair bit of code that won't be used in most cases, because ngProjectAs is somewhat rare.

These changes rework the compiler not to output the raw selectors in the projectionDef, but to parse the selector in ngProjectAs and to store it on the TAttributes. The logic for matching has also been changed so that it matches the pre-parsed ngProjectAs selector against the list of projection selectors.

PR Close #29578
2019-04-11 08:09:09 -07:00
Filipe Silva ef85336719 build: update to TypeScript 3.4 (#29372)
PR Close #29372
2019-04-10 12:12:16 -07:00
Ben Lesh 138ca5a246 refactor(ivy): prefix all generated instructions (#29692)
- Updates all instructions to be prefixed with the Greek delta symbol

PR Close #29692
2019-04-10 12:11:40 -07:00
Pete Bacon Darwin c65ac7fbad perf(ivy): ngcc - exit early if the targeted package has been compiled (#29740)
Previously we always walked the whole folder tree looking for
entry-points before we tested whether a target package had been
processed already. This could take >10secs!

This commit does a quick check of the target package before doing
the full walk which brings down the execution time for ngcc in this
case dramatically.

```
$ time ./node_modules/.bin/ivy-ngcc -t @angular/common/http/testing
Compiling @angular/core : fesm2015 as esm2015
Compiling @angular/core : fesm5 as esm5
Compiling @angular/core : esm2015 as esm2015
Compiling @angular/core : esm5 as esm5
Compiling @angular/common/http : fesm2015 as esm2015
Compiling @angular/common/http : fesm5 as esm5
Compiling @angular/common/http : esm2015 as esm2015
Compiling @angular/common/http : esm5 as esm5
Compiling @angular/common/http/testing : fesm2015 as esm2015
Compiling @angular/common/http/testing : fesm5 as esm5
Compiling @angular/common/http/testing : esm2015 as esm2015
Compiling @angular/common/http/testing : esm5 as esm5

real	0m19.766s
user	0m28.533s
sys	0m2.262s
```

```
$ time ./node_modules/.bin/ivy-ngcc -t @angular/common/http/testing
The target entry-point has already been processed

real	0m0.666s
user	0m0.605s
sys	0m0.113s
```

PR Close #29740
2019-04-08 09:48:20 -07:00
Pete Bacon Darwin ed12d7e949 test(ivy): ngcc - improve and use the `MockLogger` (#29740)
Previously the console logger was being used in integration tests
leading to lots of output during test runs.

PR Close #29740
2019-04-08 09:48:20 -07:00
Pete Bacon Darwin e02684e609 fix(compiler-cli): ensure LogicalProjectPaths always start with a slash (#29627)
Previously, if a matching rootDir ended with a slash then the path
returned from `logicalPathOfFile()` would not start with a slash,
which is inconsistent.

PR Close #29627
2019-04-08 09:46:16 -07:00
Pete Bacon Darwin 3246399bff fix(ivy): ngcc - show logging via CLI by default (#29686)
The new logger implementation caused a regression where
by default the ngcc CLI did not output any logging messages.

PR Close #29686
2019-04-03 15:27:39 -07:00
JoostK 60afe88bcc feat(ivy): do not emit empty providers/imports for defineInjector (#29598)
The defineInjector function specifies its providers and imports array to
be optional, so if no providers/imports are present these keys may be
omitted. This commit updates the compiler to only generate the keys when
necessary.

PR Close #29598
2019-04-02 16:03:54 -07:00
JoostK 2d372f48db feat(ivy): exclude declarations from injector imports (#29598)
Prior to this change, a module's imports and exports would be used verbatim
as an injectors' imports. This is detrimental for tree-shaking, as a
module's exports could reference declarations that would then prevent such
declarations from being eligible for tree-shaking.

Since an injector actually only needs NgModule references as its imports,
we may safely filter out any declarations from the list of module exports.
This makes them eligible for tree-shaking once again.

PR Close #29598
2019-04-02 16:03:54 -07:00
JoostK 45c6360e5a feat(ivy): emit module scope metadata using pure function call (#29598)
Prior to this change, all module metadata would be included in the
`defineNgModule` call that is set as the `ngModuleDef` field of module
types. Part of the metadata is scope information like declarations,
imports and exports that is used for computing the transitive module
scope in JIT environments, preventing those references from being
tree-shaken for production builds.

This change moves the metadata for scope computations to a pure function
call that patches the scope references onto the module type. Because the
function is marked pure, it may be tree-shaken out during production builds
such that references to declarations and exports are dropped, which in turn
allows for tree-shaken any declaration that is not otherwise referenced.

Fixes #28077, FW-1035

PR Close #29598
2019-04-02 16:03:54 -07:00
Pete Bacon Darwin 6b39c9cf32 fix(compiler-cli): ngcc - cope with processing entry-points multiple times (#29657)
With the new API, where you can choose to only process the first
matching format, it is possible to process an entry-point multiple
times, if you pass in a different format each time.

Previously, ngcc would always try to process the typings files for
the entry-point along with processing the first format of the current
execution of ngcc. But this meant that it would be trying to process
the typings a second time.

Now we only process the typings if they have not already been
processed as part of processing another format in another
even if it was in a different execution of ngcc.

PR Close #29657
2019-04-02 15:59:34 -07:00
Alex Eagle b14537a004 fix(bazel): use //:tsconfig.json as the default for ng_module (#29670)
This matches the behavior of ts_library

PR Close #29670
2019-04-02 15:57:11 -07:00
JoostK 98f8b0f328 fix(ivy): ngcc - properly handle aliases class expressions (#29119)
In ES2015, classes could have been emitted as a variable declaration
initialized with a class expression. In certain situations, an intermediary
variable suffixed with `_1` is present such that the variable
declaration's initializer becomes a binary expression with its rhs being
the class expression, and its lhs being the identifier of the intermediate
variable. This structure was not recognized, resulting in such classes not
being considered as a class in `Esm2015ReflectionHost`.

As a consequence, the analysis of functions/methods that return a
`ModuleWithProviders` object did not take the methods of such classes into
account.

Another edge-case with such intermediate variable was that static
properties would not be considered as class members. A testcase was added
to prevent regressions.

Fixes #29078

PR Close #29119
2019-04-02 10:50:46 -07:00
Pete Bacon Darwin 63013f1aeb fix(ivy): support finding the import of namespace-imported identifiers (#27675)
Currently there is no support in ngtsc for imports of the form:

```
import * as core from `@angular/core`

export function forRoot(): core.ModuleWithProviders;
```

This commit modifies the `ReflectionHost.getImportOfIdentifier(id)`
method, so that it supports this kind of return type.

PR Close #27675
2019-04-01 16:06:14 -07:00
Alex Rickabaugh 7041e61562 perf(ivy): basic incremental compilation for ngtsc (#29380)
This commit introduces a mechanism for incremental compilation to the ngtsc
compiler.

Previously, incremental information was used in the construction of the
ts.Program for subsequent compilations, but was not used in ngtsc itself.

This commit adds an IncrementalState class, which tracks state between ngtsc
compilations. Currently, this supports skipping the TypeScript emit step
when the compiler can prove the contents of emit have not changed.

This is implemented for @Injectables as well as for files which don't
contain any Angular decorated types. These are the only files which can be
proven to be safe today.

See ngtsc/incremental/README.md for more details.

PR Close #29380
2019-04-01 15:13:56 -07:00
Alex Rickabaugh 7316212c1e test(ivy): support multiple compilations in the ngtsc test env (#29380)
This commit adds support for compiling the same program repeatedly in a way
that's similar to how incremental builds work in a tool such as the CLI.

* support is added to the compiler entrypoint for reuse of the Program
  object between compilations. This is the basis of the compiler's
  incremental compilation model.

* support is added to wrap the CompilerHost the compiler creates and cache
  ts.SourceFiles in between compilations.

* support is added to track when files are emitted, for assertion purposes.

* an 'exclude' section is added to the base tsconfig to prevent .d.ts
  outputs from the first compilation from becoming inputs to any subsequent
  compilations.

PR Close #29380
2019-04-01 15:13:56 -07:00
Alex Rickabaugh aaa16f286d feat(ivy): performance trace mechanism for ngtsc (#29380)
This commit adds a `tracePerformance` option for tsconfig.json. When
specified, it causes a JSON file with timing information from the ngtsc
compiler to be emitted at the specified path.

This tracing system is used to instrument the analysis/emit phases of
compilation, and will be useful in debugging future integration work with
@angular/cli.

See ngtsc/perf/README.md for more details.

PR Close #29380
2019-04-01 15:13:55 -07:00
Alex Rickabaugh 3e569767e3 fix(ivy): avoid remote scoping if it's not actually required (#29404)
Currently, ngtsc decides to use remote scoping if the compilation of a
component may create a cyclic import. This happens if there are two
components in a scope (say, A and B) and A directly uses B. During
compilation of B ngtsc will then note that if B were to use A, a cycle would
be generated, and so it will opt to use remote scoping for B.

ngtsc already uses the R3TargetBinder to correctly track the imports that
are actually required, for future cycle tracking. This commit expands that
usage to not trigger remote scoping unless B actually does consume A in its
template.

PR Close #29404
2019-04-01 15:13:35 -07:00
Pete Bacon Darwin 8d3d75e454 feat(compiler-cli): ngcc - make logging more configurable (#29591)
This allows CLI usage to filter excessive log messages
and integrations like webpack plugins to provide their own logger.

// FW-1198

PR Close #29591
2019-04-01 11:53:28 -07:00
Pete Bacon Darwin 39345b6fae style(compiler-cli): ensure FFR type is implemented correctly (#29539)
PR Close #29539
2019-04-01 11:53:08 -07:00
Pete Bacon Darwin 06859f1335 refactor(compiler-cli): track visited source files in PartialEvaluator (#29539)
PR Close #29539
2019-04-01 11:53:08 -07:00
Pete Bacon Darwin 78ba503fb9 fix(ivy): ngcc - write `.d.ts.map` files to the correct folder (#29556)
Previously we were writing `.d.ts` and `.d.ts.map` to different
folders.

PR Close #29556
2019-03-28 15:23:35 -07:00
Pete Bacon Darwin 1df9908579 fix(ivy): ngcc - ensure generated source map paths are correct (#29556)
Previously we were using absolute paths, but since at rendering time
we do not know exactly where the file will be written it is more correct
to  change to using relative paths. This is actually better all round
since it allows the folders to be portable to different machines, etc.

PR Close #29556
2019-03-28 15:23:35 -07:00
Pete Bacon Darwin c456b73302 refactor(ivy): ngcc - remove the `targetPath` properties of Transformer and Renderer (#29556)
We have already removed this concept from the public API. This just cleans it out altogether.

The `targetPath` was an alternative output path to the original `basePath`.
This is not really a very useful concept, since the actual target path
of each output file is more complex and not consistently relative to the `basePath`.

PR Close #29556
2019-03-28 15:23:35 -07:00
Paul Gschwendtner 1e5a818719 fix(ivy): ngtsc is unable to detect flat module entry-point on windows (#29453)
Currently when building an Angular project with `ngtsc`
and `flatModuleOutFile` enabled, the Ngtsc build will fail
if there are multiple source files as root file names.

Ngtsc and NGC currently determine the entry-point for multiple
root file names by looking for files ending with `/index.ts`.

This functionality is technically deprecated, but still supported
and currently breaks on Windows as the root file names are not
guaranteed to be normalized POSIX-like paths.

In order to make this logic more reliable in the future, this commit
also switches the shim generators and entry-point logic to the branded
path types. This ensures that we don't break this in the future.

PR Close #29453
2019-03-27 13:46:37 -07:00
Paul Gschwendtner e57ed61448 refactor(ivy): fix incorrect error message in ngtsc "PathSegment" (#29453)
PR Close #29453
2019-03-27 13:46:37 -07:00
Ben Lesh 96b800c8bc feat(ivy): select instruction now generated in front of all relevant instructions (#29546)
PR Close #29546
2019-03-27 12:37:03 -07:00
Ben Lesh a2f8f5595f refactor(ivy): rename flushHooksUpTo to select (#29527)
PR Close #29527
2019-03-27 09:35:55 -07:00
Marc Laval c412374854 fix(ivy): DebugNode.query should query nodes in the logical tree (#29480)
PR Close #29480
2019-03-26 12:48:37 -07:00
George Kalpakas 21835af70c fix(ivy): handle class declarations consistently in ES5 code (#29209)
PR Close #29209
2019-03-21 22:20:24 +00:00
George Kalpakas 2790352d04 refactor(ivy): use `ClassDeclaration` in more `ReflectionHost` methods (#29209)
PR Close #29209
2019-03-21 22:20:23 +00:00
George Kalpakas bb6a3632f6 refactor(ivy): correctly type class declarations in `ngtsc`/`ngcc` (#29209)
Previously, several `ngtsc` and `ngcc` APIs dealing with class
declaration nodes used inconsistent types. For example, some methods of
the `DecoratorHandler` interface expected a `ts.Declaration` argument,
but actual `DecoratorHandler` implementations specified a stricter
`ts.ClassDeclaration` type.

As a result, the stricter methods would operate under the incorrect
assumption that their arguments were of type `ts.ClassDeclaration`,
while the actual arguments might be of different types (e.g. `ngcc`
would call them with `ts.FunctionDeclaration` or
`ts.VariableDeclaration` arguments, when compiling ES5 code).

Additionally, since we need those class declarations to be referenced in
other parts of the program, `ngtsc`/`ngcc` had to either repeatedly
check for `ts.isIdentifier(node.name)` or assume there was a `name`
identifier and use `node.name!`. While this assumption happens to be
true in the current implementation, working around type-checking is
error-prone (e.g. the assumption might stop being true in the future).

This commit fixes this by introducing a new type to be used for such
class declarations (`ts.Declaration & {name: ts.Identifier}`) and using
it consistently throughput the code.

PR Close #29209
2019-03-21 22:20:23 +00:00
George Kalpakas 2d859a8c3a refactor(ivy): implement `DtsModuleScopeResolver` from `MetadataDtsModuleScopeResolver` (#29209)
PR Close #29209
2019-03-21 22:20:23 +00:00
George Kalpakas 70fffba054 refactor(ivy): remove unused code from `TypeCheckContext` (#29209)
PR Close #29209
2019-03-21 22:20:23 +00:00
Greg Magolan 861d6f1523 build(bazel): back out of @bazel/jasmine 0.27.7 with shard count (#29444)
PR Close #29444
2019-03-21 09:59:13 -07:00
Alex Rickabaugh dc10355d61 build(compiler-cli): enable full TypeScript strictness (#29436)
This commit enables strict: true in TypeScript builds of
//packages/compiler-cli.

PR Close #29436
2019-03-21 12:14:39 -04:00
JoostK 9eb8274991 fix(ivy): emit generic type arguments in Pipe metadata (#29403)
Previously, only directives and services with generic type parameters
would emit `any` as generic type when emitting Ivy metadata into .d.ts
files. Pipes can also have generic type parameters but did not emit
`any` for all type parameters, resulting in the omission of those
parameters which causes compilation errors.

This commit adds support for pipes with generic type arguments and emits
`any` as generic type in the Ivy metadata.

Fixes #29400

PR Close #29403
2019-03-20 16:11:22 -04:00
Alan Agius 68a9fe817c test: remove symlink workaround (#29426)
This is no longer required. And is causing some errors to some of our engineers

PR Close #29426
2019-03-20 15:13:09 -04:00
Pete Bacon Darwin 64e5628897 feat(ivy): ngcc - support creating a new copy of the entry-point format (#29092)
This commit adds a `NewEntryPointFileWriter` that will be used in
webpack integration. Instead of overwriting files in-place, this `FileWriter`
will make a copy of the TS program files and write the transformed files
there. It also updates the package.json with new properties that can be
used to access the new entry-point format.

FW-1121

PR Close #29092
2019-03-20 14:45:55 -04:00
Pete Bacon Darwin 849b327986 refactor(ivy): ngcc - extract file writing out into a class (#29092)
This is in preparation of having different file writing strategies.

PR Close #29092
2019-03-20 14:45:55 -04:00
Pete Bacon Darwin a827bc2e3a refactor(ivy): ngcc - mark target entry-point as processed even if ngcc was a noop (#29092)
If `targetEntryPointPath` is provided to `mainNgcc` then we will now mark all
the `propertiesToConsider` for that entry-point if we determine that
it does not contain code that was compiled by Angular (for instance it has
no `...metadata.json` file).

The commit also renames `__modified_by_ngcc__` to `__processed_by_ivy_ngcc__`, since
there may be entry-points that are marked despite ngcc not actually compiling anything.

PR Close #29092
2019-03-20 14:45:55 -04:00
Pete Bacon Darwin 083fb99033 fix(ivy): ngcc - fail build-marker check if any formats were compiled with different ngcc (#29092)
Now we check the build-marker version for all the formats
rather than just the one we are going to compile.

This way we don't get into the situation where one format was
built with one version of ngcc and another format was built with
another version.

PR Close #29092
2019-03-20 14:45:55 -04:00
Pete Bacon Darwin 55ea8da6eb refactor(ivy): ngcc - clean up the public API and export `hasBeenProcessed` helper (#29092)
Now the public API does not contain internal types, such as `AbsoluteFsPath` and
`EntryPointJsonProperty`. Instead we just accept strings and then guard them in
`mainNgcc` as appropriate.

A new public API function (`hasBeenProcessed`) has been exported to allow programmatic
checking of the build marker when the package.json contents are already known.

PR Close #29092
2019-03-20 14:45:55 -04:00
Pete Bacon Darwin 7ea0d1bd3a refactor(ivy): ngcc - use a fixed set of properties to compile if none provided (#29092)
Previously we always considered all the properties in the package.json
if no `propertiesToConsidere` were provided.
But this results in computing a new set of properties for each entry-point
plus iterating through many of the package.json properties that are
not related to bundle-format paths.

PR Close #29092
2019-03-20 14:45:55 -04:00
Pete Bacon Darwin bdcbd9ed4b fix(ivy): ngcc - teach Esm5ReflectionHost about aliased variables (#29092)
Sometimes, in ESM5 code, aliases to exported variables are used internally
to refer to the exported value. This prevented some analysis from being
able to match up a reference to an export to the actual export itself.

For example in the following code:

```
var HttpClientXsrfModule = /** @class */ (function () {
  function HttpClientXsrfModule() {
  }
  HttpClientXsrfModule_1 = HttpClientXsrfModule;
  HttpClientXsrfModule.withOptions = function (options) {
      if (options === void 0) { options = {}; }
      return {
          ngModule: HttpClientXsrfModule_1,
          providers: [],
      };
  };
  var HttpClientXsrfModule_1;
  HttpClientXsrfModule = HttpClientXsrfModule_1 = tslib_1.__decorate([
      NgModule({
          providers: [],
      })
  ], HttpClientXsrfModule);
  return HttpClientXsrfModule;
}());
```

We were not able to tell that the `ngModule: HttpClientXsrfModule_1` property
assignment was actually meant to refer to the `function HttpClientXrsfModule()`
declaration.  This caused the `ModuleWithProviders` processing to fail.

This commit ensures that we can compile typings files using the ESM5
format, so we can now update the examples boilerplate tool so that it
does not need to compile the ESM2015 format at all.

PR Close #29092
2019-03-20 14:45:55 -04:00
Pete Bacon Darwin b48d6e1b13 fix(ivy): ngcc - empower `Esm5ReflectionHost` to analyze `ModuleWithProviders` functions (#29092)
In ESM5 code, static methods appear as property assignments onto the constructor
function. For example:

```
var MyClass = (function() {
  function MyClass () {}
  MyClass.staticMethod = function() {};
  return MyClass;
})();
```

This commit teaches ngcc how to process these forms when searching
for `ModuleWithProviders` functions that need to be updated in the typings
files.

PR Close #29092
2019-03-20 14:45:55 -04:00
Pete Bacon Darwin 68f9d705f8 build(ivy): ngcc - only test under `no-ivy-aot` mode (#29092)
We want ngcc to test non-AOT builds of the Angular packages,
so we filter the tests in using the `no-ivy-aot` tag.

PR Close #29092
2019-03-20 14:45:54 -04:00
Pete Bacon Darwin 229f035969 feat(ivy): ngcc - support only compiling the first format property to match (#29092)
By default ngcc will compile all the format properties specified. With this
change you can configure ngcc so that it will stop compiling an entry-point
after the first property that matches the `propertiesToConsider`.

PR Close #29092
2019-03-20 14:45:54 -04:00
Pete Bacon Darwin c9f7cdaafd refactor(ivy): ngcc - simplify `Transformer.transform` API (#29092)
By ensuring that EntryPointBundle contains everything that `Transformer.transform()`
needs to do its work, we can simplify its signature.

PR Close #29092
2019-03-20 14:45:54 -04:00
Pete Bacon Darwin 7b55ba58b9 refactor(ivy): ngcc - remove flat-format and use AbsoluteFsPath (#29092)
Now that we are using package.json properties to indicate which
entry-point format to compile, it turns out that we don't really
need to distinguish between flat and non-flat formats, unless we
are compiling `@angular/core`.

PR Close #29092
2019-03-20 14:45:54 -04:00
Pete Bacon Darwin cd449021c1 feat(ivy): ngcc - compile only specified package.json format properties (#29092)
You can now specify a list of properties in the package.json that
should be considered (in order) to find the path to the format to compile.

The build marker system has been updated to store the markers in
the package.json rather than an additional external file.
Also instead of tracking the underlying bundle format that was compiled,
it now tracks the package.json property.

BREAKING CHANGE:

The `proertiesToConsider` option replaces the previous `formats` option,
which specified the final bundle format, rather than the property in the
package.json.
If you were using this option to compile only specific bundle formats,
you must now modify your usage to pass in the properties in the package.json
that map to the format that you wish to compile.

In the CLI, the `--formats` is no longer available. Instead use the
`--properties` option.

FW-1120

PR Close #29092
2019-03-20 14:45:54 -04:00
Pete Bacon Darwin 4bb0259bc0 feat(ivy): ngcc - support targeting a start entry-point (#29092)
You can now, programmatically, specify an entry-point where
the ngcc compilation will occur.
Only this entry-point and its dependencies will be compiled.

FW-1119

PR Close #29092
2019-03-20 14:45:54 -04:00
Pete Bacon Darwin 66239b9d09 refactor(ivy): expose ngcc programmatically (#29092)
The `mainNgcc()` function has been refactored to make it easier to call
ngcc from JavaScript, rather than via the command line.

For example, the `yargs` argument parsing and the exception
handling/logging have moved to the `main-ngcc.ts`
file so that it is only used for the command line version.

FW-1118

PR Close #29092
2019-03-20 14:45:54 -04:00
Pete Bacon Darwin a770aa231d refactor(ivy): move ngcc into a higher level folder (#29092)
PR Close #29092
2019-03-20 14:45:54 -04:00
Pete Bacon Darwin cf4718c366 feat(ivy): ngcc - support dts compilation via ES5 bundles (#29092)
Previously we only compiled the typings files, in ngcc, if there was
an ES2015 formatted bundle avaiable. This turns out to be an artificial
constraint and we can also support typings compilation via ES5 formats
too.

This commit changes the ngcc compiler to attempt typings compilation
via ES5 if necessary. The order of the formats to consider is now:
FESM2015, FESM5, ESM2015, ESM5.

FW-1122

PR Close #29092
2019-03-20 14:45:54 -04:00
Pete Bacon Darwin 07aeafa75c style(ivy): ngcc - fix typo in comment (#29092)
PR Close #29092
2019-03-20 14:45:54 -04:00
Greg Magolan 7c4afb0da7 build: enable shard_count for some jasmine tests that have many specs (#29375)
PR Close #29375
2019-03-19 23:39:36 -04:00
Matias Niemelä 8714daf276 fix(ivy): introduce host-specific styling instructions (#29292)
This patch is the first of a few patches which separates the
styling logic between template bindings (e.g. <div [style])
from host bindings (e.g. @HostBinding('style')). This patch
in particular introduces a series of host-specific styling
instructions and changes the existing set of template styling
instructions not to accept directives. The underyling code (which
communicates with the styling algorithm) still works as it did
before.

This PR also separates the styling instruction code into a separate
file and moves over all other instructions into an dedicated
instructions directory.

PR Close #29292
2019-03-19 16:33:39 -04:00
Alex Eagle 86aba1e8f3 build: add moduleName to ngFactory sourcefiles (#29385)
PR Close #29385
2019-03-19 01:10:49 -04:00
Alex Rickabaugh ae4a86e3b5 fix(ivy): don't track identifiers of ffr-resolved references (#29387)
This fix is for a bug in the ngtsc PartialEvaluator, which statically
evaluates expressions.

Sometimes, evaluating a reference requires resolving a function which is
declared in another module, and thus no function body is available. To
support this case, the PartialEvaluator has the concept of a foreign
function resolver.

This allows the interpretation of expressions like:

const router = RouterModule.forRoot([]);

even though the definition of the 'forRoot' function has no body. In
ngtsc today, this will be resolved to a Reference to RouterModule itself,
via the ModuleWithProviders foreign function resolver.

However, the PartialEvaluator also associates any Identifiers in the path
of this resolution with the Reference. This is done so that if the user
writes

const x = imported.y;

'x' can be generated as a local identifier instead of adding an import for
'y'.

This was at the heart of a bug. In the above case with 'router', the
PartialEvaluator added the identifier 'router' to the Reference generated
(through FFR) to RouterModule.

This is not correct. References that result from FFR expressions may not
have the same value at runtime as they do at compile time (indeed, this is
not the case for ModuleWithProviders). The Reference generated via FFR is
"synthetic" in the sense that it's constructed based on a useful
interpretation of the code, not an accurate representation of the runtime
value. Therefore, it may not be legal to refer to the Reference via the
'router' identifier.

This commit adds the ability to mark such a Reference as 'synthetic', which
allows the PartialEvaluator to not add the 'router' identifier down the
line. Tests are included for both the PartialEvaluator itself as well as the
resultant buggy behavior in ngtsc overall.

PR Close #29387
2019-03-19 01:10:17 -04:00
George Kalpakas ce4da3f8e5 fix(ivy): run annotations handlers' `resolve()` in `ngcc` (#28963)
The `resolve` phase (run after all handlers have analyzed) was
introduced in 7d954dffd, but `ngcc` was not updated to run the handlers'
`resolve()` methods. As a result, certain operations (such as listing
directives used in component templates) would not be performed by
`ngcc`.

This commit fixes it by running the `resolve()` methods once analysis
has been completed.

PR Close #28963
2019-03-18 17:43:20 -04:00
George Kalpakas e79f57a6b8 test(ivy): expand `ngcc` `DecorationAnalyzer` tests to cover more cases (#28963)
PR Close #28963
2019-03-18 17:43:20 -04:00
George Kalpakas c439e14d39 refactor(ivy): avoid code duplication in `ngcc` tests (#28963)
PR Close #28963
2019-03-18 17:43:20 -04:00
George Kalpakas a8d84660e5 refactor(ivy): improve error message in `ngtsc`'s `findExportedNameOfNode()` (#28963)
PR Close #28963
2019-03-18 17:43:20 -04:00
George Kalpakas 4525619a73 refactor(ivy): remove unnecessary escaping in RegExp (#28963)
PR Close #28963
2019-03-18 17:43:20 -04:00
Paul Gschwendtner 105cfaf5e4 fix(compiler-cli): incorrect metadata bundle for multiple unnamed re-exports (#29360)
Currently if an Angular library has multiple unnamed module re-exports, NGC will
generate incorrect metdata if the project is using the flat-module bundle option.

e.g.

_public-api.ts_
```ts
export * from '@mypkg/secondary1';
export * from '@mypkg/secondary2';
```

There are clearly two unnamed re-exports in the `public-api.ts` file. NGC right now
accidentally overwrites all previous re-exports with the last one. Resulting in the
generated metadata only containing a reference to `@mypkg/secondary2`.

This is problematic as it is common for primary library entry-points to have
multiple re-exports (e.g. Material re-exporting all public symbols; or flex-layout
exporting all public symbols from their secondary entry-points).

Currently Angular Material works around this issue by manually creating
a metadata file that declares the re-exports from all unnamed re-exports.

(see: https://github.com/angular/material2/blob/master/tools/package-tools/build-release.ts#L78-L85)

This workaround works fine currently, but is no longer easily integrated when
building the package output with Bazel. In order to be able to build such
libraries with Bazel (Material/flex-layout), we need to make sure that NGC
generates the proper flat-module metadata bundle.

PR Close #29360
2019-03-18 15:08:40 -04:00
Alex Eagle 4d912b6b12 Revert "build: enable shard_count for some jasmine tests that have many specs (#29196)" (#29347)
This reverts commit a5c747f46d.

PR Close #29347
2019-03-15 19:47:00 -04:00
Alex Eagle a5c747f46d build: enable shard_count for some jasmine tests that have many specs (#29196)
This partitions the spects across multiple processes so they run in parallel.

PR Close #29196
2019-03-14 13:14:03 -04:00
Kristiyan Kostadinov 0ffa2f2e73 fix(ivy): unable to inherit view queries into component from directive (#29203)
Fixes components not being able to inherit their view queries from a directive.

This PR resolves FW-1146.

PR Close #29203
2019-03-13 17:12:14 -04:00
Igor Minar 75748d6044 feat: add support for TypeScript 3.3 (and drop older versions) (#29004)
https://blogs.msdn.microsoft.com/typescript/2019/01/31/announcing-typescript-3-3/

BREAKING CHANGE: TypeScript 3.1 and 3.2 are no longer supported.

Please update your TypeScript version to 3.3

PR Close #29004
2019-03-13 10:38:37 -07:00
Alex Rickabaugh 73da2792c9 fix(ivy): properly compile NgModules with forward referenced types (#29198)
Previously, ngtsc would resolve forward references while evaluating the
bootstrap, declaration, imports, and exports fields of NgModule types.
However, when generating the resulting ngModuleDef, the forward nature of
these references was not taken into consideration, and so the generated JS
code would incorrectly reference types not yet declared.

This commit fixes this issue by introducing function closures in the
NgModuleDef type, similarly to how NgComponentDef uses them for forward
declarations of its directives and pipes arrays. ngtsc will then generate
closures when required, and the runtime will unwrap them if present.

PR Close #29198
2019-03-12 18:26:42 -07:00
Alex Rickabaugh ccb70e1c64 fix(ivy): reuse default imports in type-to-value references (#29266)
This fixes an issue with commit b6f6b117. In this commit, default imports
processed in a type-to-value conversion were recorded as non-local imports
with a '*' name, and the ImportManager generated a new default import for
them. When transpiled to ES2015 modules, this resulted in the following
correct code:

import i3 from './module';

// somewhere in the file, a value reference of i3:
{type: i3}

However, when the AST with this synthetic import and reference was
transpiled to non-ES2015 modules (for example, to commonjs) an issue
appeared:

var module_1 = require('./module');
{type: i3}

TypeScript renames the imported identifier from i3 to module_1, but doesn't
substitute later references to i3. This is because the import and reference
are both synthetic, and never went through the TypeScript AST step of
"binding" which associates the reference to its import. This association is
important during emit when the identifiers might change.

Synthetic (transformer-added) imports will never be bound properly. The only
possible solution is to reuse the user's original import and the identifier
from it, which will be properly downleveled. The issue with this approach
(which prompted the fix in b6f6b117) is that if the import is only used in a
type position, TypeScript will mark it for deletion in the generated JS,
even though additional non-type usages are added in the transformer. This
again would leave a dangling import.

To work around this, it's necessary for the compiler to keep track of
identifiers that it emits which came from default imports, and tell TS not
to remove those imports during transpilation. A `DefaultImportTracker` class
is implemented to perform this tracking. It implements a
`DefaultImportRecorder` interface, which is used to record two significant
pieces of information:

* when a WrappedNodeExpr is generated which refers to a default imported
  value, the ts.Identifier is associated to the ts.ImportDeclaration via
  the recorder.
* when that WrappedNodeExpr is later emitted as part of the statement /
  expression translators, the fact that the ts.Identifier was used is
  also recorded.

Combined, this tracking gives the `DefaultImportTracker` enough information
to implement another TS transformer, which can recognize default imports
which were used in the output of the Ivy transform and can prevent them
from being elided. This is done by creating a new ts.ImportDeclaration for
the imports with the same ts.ImportClause. A test verifies that this works.

PR Close #29266
2019-03-12 18:02:08 -07:00
Andrew Kushnir fe76494759 fix(ivy): use default selector for Components if selector is empty (#29239)
Prior to this change default selector for Components was not applied in case selector is missing or defined as an empty string. This update aligns this behavior between Ivy and VE: now default selector is used for Components when it's needed. Directives with empty selector are not allowed and trigger a compile-time error in both Ivy and VE.

PR Close #29239
2019-03-12 14:09:46 -07:00
Alan Agius df354d1b34 fix(bazel): add missing binary path for api-extractor (#29202)
`api-extractor` binary is required for external consumers of `ng_module` that want to use the `bundle_dts` flag.

This also sets a different api-exttractor binary to use for ng_module, based if it's internal or external.

PR Close #29202
2019-03-12 10:49:49 -07:00
Andrew Kushnir 1d88c2bb81 fix(ivy): handle aliased Angular decorators (#29195)
Prior to this change the code didn't take into account the fact that decorators can be aliases while importing into a script. As a result, these decorators were not recognized by Angular and various failures happened because of that. Now we take aliases into account and resolve decorator name properly.

PR Close #29195
2019-03-11 11:20:41 -07:00
Alan ca20f571b8 fix(ivy): always convert `rootDirs` to `AbsoluteFsPath` in `getRootDirs` (#29151)
`getCurrentDirectory` directory doesn't return a posix separated normalized path. While `rootDir` and `rootDirs` should return posix separated paths, it's best to not assume as other paths within the compiler options can be returned not posix separated such as `basePath`

See: https://github.com/Microsoft/TypeScript/blob/master/src/compiler/sys.ts#L635

This partially fixes #29140, however there needs to be a change in the CLI as well to handle this, as at the moment we are leaking devkit paths which is not correct.

Fixes #29140

PR Close #29151
2019-03-11 08:31:52 -07:00
Alan Agius a5b8420234 fix(ivy): render alias exports for private declarations if possible (#28735)
Sometimes declarations are not exported publicly but are exported under
a private name. In this case, rather than adding a completely new
export to the entry point, we should create an export that aliases the
private name back to the original public name.

This is important when the typings files have been rolled-up using a tool
such as the [API Extractor](https://api-extractor.com/). In this case
the internal type of an aliased private export will be removed completely
from the typings file, so there is no "original" type to re-export.

For example:

If there are the following TS files:

**entry-point.ts**

```ts
export {Internal as External} from './internal';
```

**internal.ts**

```ts
export class Internal {
  foo(): void;
}
```

Then the API Extractor might roll up the .d.ts files into:

```ts
export declare class External {
  foo(): void;
}
```

In this case ngcc should add an export so the file looks like:

```ts
export declare class External {
  foo(): void;
}
export {External as Internal};
```

PR Close #28735
2019-03-11 07:17:19 -07:00
Alex Rickabaugh 49dccf4bfc fix(ivy): process separate declarations and exports for summaries (#29193)
ngsummary files were generated with an export for each class declaration.
However, some Angular code declares classes (class Foo) and exports them
(export {Foo}) separately, which was causing incomplete summary files.

This commit expands the set of symbol names for which summary exports will
be generated, fixing this issue.

PR Close #29193
2019-03-08 16:11:32 -08:00
Alex Rickabaugh 3a6ba00286 fix(ivy): escape all required characters in reexport aliases (#29194)
Previously, the compiler did not escape . or $, and this was causing issues
in google3. Now these characters are escaped.

PR Close #29194
2019-03-08 16:10:57 -08:00
Alex Rickabaugh c37ec8b255 fix(ivy): produce ts.Diagnostics for NgModule scope errors (#29191)
Previously, when the NgModule scope resolver discovered semantic errors
within a users NgModules, it would throw assertion errors. TODOs in the
codebase indicated these should become ts.Diagnostics eventually.

Besides producing better-looking errors, there is another reason to make
this change asap: these assertions were shadowing actual errors, via an
interesting mechanism:

1) a component would produce a ts.Diagnostic during its analyze() step
2) as a result, it wouldn't register component metadata with the scope
   resolver
3) the NgModule for the component references it in exports, which was
   detected as an invalid export (no metadata registering it as a
   component).
4) the resulting assertion error would crash the compiler, hiding the
   real cause of the problem (an invalid component).

This commit should mitigate this problem by converting scoping errors to
proper ts.Diagnostics. Additionally, we should consider registering some
marker indicating a class is a directive/component/pipe without actually
requiring full metadata to be produced for it, which would allow suppression
of errors like "invalid export" for such invalid types.

PR Close #29191
2019-03-08 14:21:48 -08:00
Alan b012ab210b test: add interm fix for test that rely on an index.d.ts file (#28884)
At the moment, certain tests relies on resolving the module with an index.d.ts, this root cause might be some implementations are missing from the mocks.

Similar to: 58b4045359

PR Close #28884
2019-03-08 12:36:55 -08:00
Alex Rickabaugh b6f6b1178f fix(ivy): generate type references to a default import (#29146)
This commit refactors and expands ngtsc's support for generating imports of
values from imports of types (this is used for example when importing a
class referenced in a type annotation in a constructor).

Previously, this logic handled "import {Foo} from" and "import * as foo
from" style imports, but failed on imports of default values ("import
Foo from"). This commit moves the type-to-value logic to a separate file and
expands it to cover the default import case. Doing this also required
augmenting the ImportManager to track default as well as non-default import
generation. The APIs were made a little cleaner at the same time.

PR Close #29146
2019-03-08 11:57:08 -08:00
Alex Rickabaugh 37c5a26421 perf(ivy): switch ngtsc to use single-file emit (#29147)
In the TypeScript compiler API, emit() can be performed either on a single
ts.SourceFile or on the entire ts.Program simultaneously.

ngtsc previously used whole-program emit, which was convenient to use while
spinning up the project but has a significant drawback: it causes a type
checking operation to occur for the whole program, including .d.ts files.
In large Bazel environments (such as Google's codebase), an ngtsc invocation
can have a few .ts files and thousands of .d.ts inputs. This unwanted type
checking is therefore a significant drain on performance.

This commit switches ngtsc to emit each .ts file individually, avoiding the
unwanted type checking.

PR Close #29147
2019-03-08 11:56:46 -08:00
Pete Bacon Darwin 142ac41cac fix(ivy): ngcc - handle prototype pseudo-member from typings file in ESM5 host (#29158)
When processing a JavaScript program, TS may come across a symbol that has
been imported from a TypeScript typings file.

In this case the compiler may pass the ReflectionHost a `prototype` symbol
as an export of the class.

This pseudo-member symbol has no declarations, which previously caused the
code in `Esm5ReflectionHost.reflectMembers()` to crash.

Now we just quietly ignore such a symbol and leave `Esm2015ReflectionHost`
to deal with it.

(As it happens `Esm2015ReflectionHost` also quietly ignores this symbol).

PR Close #29158
2019-03-08 09:34:20 -08:00
Andrew Kushnir fd5cd100a3 fix(ivy): move i18n instructions after listener ones (#29173)
Prior to this commit, i18n instructions (i18n, i18nStart) were generated before listener instructions. As a result, event listeners were attached to the wrong element (text node, not the parent element). This change updates the order of instructions and puts i18n ones after listeners, to make sure listeners are attached to the right elements.

PR Close #29173
2019-03-07 15:36:39 -08:00
Pete Bacon Darwin 5ad2097be8 fix(ivy): teach template type checker about template attributes (#29041)
For the template type checking to work correctly, it needs to know
what attributes are bound to expressions or directives, which may
require expressions in the template to be evaluated in a different
scope.

In inline templates, there are attributes that are now marked as
"Template" attributes. We need to ensure that the template
type checking code looks at these "bound" attributes as well as the
"input" attributes.

PR Close #29041
2019-03-07 11:27:36 -08:00
Pete Bacon Darwin f535f31d78 fix(ivy): match attribute selectors for content projection with inline-templates (#29041)
The content projection mechanism is static, in that it only looks at the static
template nodes before directives are matched and change detection is run.
When you have a selector-based content projection the selection is based
on nodes that are available in the template.

For example:

```
<ng-content selector="[some-attr]"></ng-content>
```

would match

```
<div some-attr="..."></div>
```

If you have an inline-template in your projected nodes. For example:

```
<div *ngIf="..." some-attr="..."></div>
```

This gets pre-parsed and converted to a canonical form.

For example:

```
<ng-template [ngIf]="...">
  <div some-attr=".."></div>
</ng-template>
```

Note that only structural attributes (e.g. `*ngIf`) stay with the `<ng-template>`
node. The other attributes move to the contained element inside the template.

When this happens in ivy, the ng-template content is removed
from the component template function and is compiled into its own
template function. But this means that the information about the
attributes that were on the content are lost and the projection
selection mechanism is unable to match the original
`<div *ngIf="..." some-attr>`.

This commit adds support for this in ivy. Attributes are separated into three
groups (Bindings, Templates and "other"). For inline-templates the Bindings
and "other" types are hoisted back from the contained node to the `template()`
instruction, so that they can be used in content projection matching.

PR Close #29041
2019-03-07 11:27:36 -08:00
Pete Bacon Darwin 423ac01dcf refactor: rename `AttributeMarker.ProjectOnly` to `AttributeMarker.Bindings` (#29041)
PR Close #29041
2019-03-07 11:27:35 -08:00
Alex Eagle 887faffa25 docs: cleanup contributors (#28930)
- remove individuals from @angular/* package.json, we don't keep them up-to-date
- switch keys in contributors.json to GitHub handles, seems like a better identifier and lets us grab avatar images from GitHub account
- move emeritus ppl to a new Alumni group (won't yet appear on the site)
- add "lead/mentor" keys so we know who is coordinating work
- add a script that generates an "org chart" graphic

PR Close #28930
2019-03-06 14:48:30 -08:00
Andrew Kushnir dc6192c8e5 fix(ivy): properly detect "inputs" and "outputs" field names that should be wrapped in quotes (#29126)
Prior to this change, the RegExp that was used to check for dashes in field names used "g" (global) flag that retains lastIndex, which might result in skipping some fields that should be wrapped in quotes (since lastIndex advanced beyond the next "-" location). This commit removes this flag and updates the test to make sure there are no regressions.

PR Close #29126
2019-03-06 11:01:53 -08:00
Alex Rickabaugh 881807dc36 fix(ivy): never use imported type references as values (#29111)
ngtsc occasionally converts a type reference (such as the type of a
parameter in a constructor) to a value reference (argument to a
directiveInject call). TypeScript has a bad habit of sometimes removing
the import statement associated with this type reference, because it's a
type only import when it initially looks at the file.

A solution to this is to always add an import to refer to a type position
value that's imported, and not rely on the existing import.

PR Close #29111
2019-03-05 16:47:41 -08:00
Marc Laval 25166d4f41 fix(ivy): support property values changed in ngOnChanges (forward rref case) (#29054)
PR Close #29054
2019-03-05 14:27:08 -08:00
Alan b446095c4d refactor: remove unused functions and classes in diagnostics (#28923)
PR Close #28923
2019-03-05 11:40:08 -08:00
Alex Rickabaugh 866d500324 fix(ivy): copy top-level comments into generated factory shims (#29065)
When ngtsc generates a .ngfactory shim, it does so based on the contents of
an original file in the program. Occasionally these original files have
comments at the top which are load-bearing (e.g. they contain jsdoc
annotations which are significant to downstream bundling tools). The
generated factory shims should preserve this comment.

This commit adds a step to the ngfactory generator to preserve the top-level
comment from the original source file.

FW-1006 #resolve
FW-1095 #resolve

PR Close #29065
2019-03-04 15:59:07 -08:00
Andrew Kushnir aa57bdbf90 fix(ivy): wrap "inputs" and "outputs" keys if they contain unsafe characters (#28919)
Prior to this change, keys in "inputs" and "outputs" objects generated by compiler were not checked against unsafe characters. As a result, in some cases the generated code was throwing JS error. Now we check whether a given key contains any unsafe chars and wrap it in quotes if needed.

PR Close #28919
2019-03-04 14:40:42 -08:00
Andrew Kushnir dcafddefb8 fix(ivy): change for-of to forEach for pipes represented with Map (#29068)
This commit fixes the problem with using for-of for pipes represented with Map (by replacing it with forEach operation).

PR Close #29068
2019-03-01 19:00:25 -08:00
Alex Rickabaugh a06824aef6 fix(ivy): correctly evaluate enum references in template expressions (#29062)
The ngtsc partial evaluator previously would not handle an enum reference
inside a template string expression correctly. Enums are resolved to an
`EnumValue` type, which has a `resolved` property with the actual value.

When effectively toString-ing a `ResolvedValue` as part of visiting a
template expression, the partial evaluator needs to translate `EnumValue`s
to their fully resolved value, which this commit does.

PR Close #29062
2019-03-01 15:47:24 -08:00
Alex Rickabaugh b1df9a30f4 fix(ivy): use the imported name of decorators for detection (#29061)
Currently, ngtsc has a bug where if you alias the name of a decorator when
importing it, it won't be detected properly. This is because the compiler
uses the aliased name and not the original, declared name of the decorator
for detection.

This commit fixes the compiler to compare against the declared name of
decorators when available, and adds a test to prevent regression.

PR Close #29061
2019-03-01 15:19:34 -08:00
Alex Rickabaugh 3e5c1bcb9f fix(ivy): track cyclic imports that are added (#29040)
ngtsc has cyclic import detection, to determine when adding an import to a
directive or pipe would create a cycle. However, this detection must also
account for already inserted imports, as it's possible for both directions
of a circular import to be inserted by Ivy (as opposed to at least one of
those edges existing in the user's program).

This commit fixes the circular import detection for components to take into
consideration already added edges. This is difficult for one critical
reason: only edges to files which will *actually* be imported should be
considered. However, that depends on which directives & pipes are used in
a given template, which is currently only known by running the
TemplateDefinitionBuilder during the 'compile' phase. This is too late; the
decision whether to use remote scoping (which consults the import graph) is
made during the 'resolve' phase, before any compilation has taken place.

Thus, the only way to correctly consider synthetic edges is for the compiler
to know exactly which directives & pipes are used in a template during
'resolve'. There are two ways to achieve this:

1) refactor `TemplateDefinitionBuilder` to do its work in two phases, with
directive matching occurring as a separate step which can be performed
earlier.

2) use the `R3TargetBinder` in the 'resolve' phase to independently bind the
template and get information about used directives.

Option 1 is ideal, but option 2 is currently used for practical reasons. The
cost of binding the template can be shared with template-typechecking.

PR Close #29040
2019-03-01 15:18:50 -08:00
Alex Rickabaugh b50283ed67 fix(ivy): support dynamic host attribute bindings (#29033)
In the @Component decorator, the 'host' field is an object which represents
host bindings. The type of this field is complex, but is generally of the
form {[key: string]: string}. Several different kinds of bindings can be
specified, depending on the structure of the key.

For example:

```
@Component({
  host: {'[prop]': 'someExpr'}
})
```

will bind an expression 'someExpr' to the property 'prop'. This is known to
be a property binding because of the square brackets in the binding key.

If the binding key is a plain string (no brackets or parentheses), then it
is known as an attribute binding. In this case, the right-hand side is not
interpreted as an expression, but is instead a constant string.

There is no actual requirement that at build time, these constant strings
are known to the compiler, but this was previously enforced as a side effect
of requiring the binding expressions for property and event bindings to be
statically known (as they need to be parsed). This commit breaks that
relationship and allows the attribute bindings to be dynamic. In the case
that they are dynamic, the references to the dynamic values are reflected
into the Ivy instructions for attribute bindings.

PR Close #29033
2019-03-01 15:18:13 -08:00
Alex Rickabaugh a23a0bc3a4 feat(ivy): support tracking the provenance of DynamicValue (#29033)
DynamicValues are generated whenever a partially evaluated expression is
unable to be resolved statically. They contain a reference to the ts.Node
which wasn't resolvable.

They can also be nested. For example, the expression 'a + b' is resolvable
only if 'a' and 'b' are themselves resolvable. If either 'a' or 'b' resolve
to a DynamicValue, the whole expression must also resolve to a DynamicValue.

Previously, if 'a' resolved to a DynamicValue, the entire expression might
have been resolved to the same DynamicValue. This correctly indicated that
the expression wasn't resolvable, but didn't return a reference to the
shallow node that couldn't be resolved (the expression 'a + b'), only a
reference to the deep node that couldn't be resolved ('a').

In certain situations, it's very useful to know the shallow unresolvable
node (for example, to use it verbatim in the output). To support this,
the partial evaluator is updated to always wrap DynamicValue to point to
each unresolvable expression as it's processed, ensuring the receiver can
determine exactly which expression node failed to resolve.

PR Close #29033
2019-03-01 15:18:13 -08:00
Greg Magolan ea09430039 build: rules_nodejs 0.26.0 & use @npm instead of @ngdeps now that downstream angular build uses angular bundles (#28871)
PR Close #28871
2019-02-28 12:06:36 -08:00
Rado Kirov 03d2e5cb1d refactor: Consistently use index access on index signature types. (#28937)
This change helps highlight certain misoptimizations with Closure
compiler. It is also stylistically preferable to consistently use index
access on index sig types.

Roughly, when one sees '.foo' they know it is always checked for typos
in the prop name by the type system (unless 'any'), while "['foo']" is
always not.

Once all angular repos are conforming this will become a tsetse.info
check, enforced by bazel.

PR Close #28937
2019-02-28 02:49:14 -08:00
Andrew Kushnir 772b24ccc3 fix(ivy): avoid missing imports for types that can be represented as values (#28941)
Prior to this change, TypeScript stripped out some imports in case we reference a type that can be represented as a value (for ex. classes). This fix ensures that we use correct symbol identifier, which makes TypeScript retain the necessary import statements.

PR Close #28941
2019-02-27 15:13:40 -08:00
Kristiyan Kostadinov efa10e33a9 fix(ivy): resolve forwardRef when analyzing NgModule (#28942)
Fixes forward refs not being resolved when an NgModule is being analyzed by ngtsc.

This PR resolves FW-1094.

PR Close #28942
2019-02-27 14:02:41 -08:00
Alex Rickabaugh 827e89cfc4 feat(ivy): support inline <style> and <link> tags in components (#28997)
Angular supports using <style> and <link> tags inline in component
templates, but previously such tags were not implemented within the ngtsc
compiler. This commit introduces that support.

FW-1069 #resolve

PR Close #28997
2019-02-27 11:56:40 -08:00
Andrew Kushnir 40833ba54b fix(ivy): process property bindings in i18n blocks similar to non-i18n bindings (#28969)
Prior to this change i18n block bindings were converted to Expressions right away (once we first access them), when in non-i18n cases we processed them differently: the actual conversion happens at instructions generation. Because of this discrepancy, the output for bindings in i18n blocks was generated incorrectly (with invalid indicies in pipeBindN fns and invalid references to non-existent local variables). Now the bindings processing is unified and i18nExp instructions should contain right bind expressions.

PR Close #28969
2019-02-27 11:56:12 -08:00
Alan Agius 34bdebcdd2 feat(ivy): add support for windows concrete types for paths (#28752)
This commit introduces support for the windows paths in the new concrete types mechanism that was introduced in this PR https://github.com/angular/angular/pull/28523

Normalized posix paths that start with either a `/` or `C:/` are considered to be an absolute path.

Note: `C:/` is used as a reference, as other drive letters are also supported.

Fixes #28754

PR Close #28752
2019-02-27 11:27:04 -08:00
Andrew Kushnir 034de06ab1 fix(ivy): avoid duplicate i18n consts to be present in generated output (#28967)
Prior to this change, the logic that outputs i18n consts (like `const MSG_XXX = goog.getMsg(...)`) didn't have a check whether a given const that represent a certain i18n message was already included into the generated output. This commit adds the logic to mark corresponding i18n contexts after translation was generated, to avoid duplicate consts in the output.

PR Close #28967
2019-02-27 10:33:41 -08:00
Alex Rickabaugh d127d05dc3 fix(ivy): correctly resolve shorthand property declarations (#28936)
The partial evaluator in ngtsc can handle a shorthand property declaration
in the middle evaluation, but fails if evaluation starts at the shorthand
property itself. This is because evaluation starts at the ts.Identifier
of the property (the ts.Expression representing it), not the ts.Declaration
for the property.

The fix for this is to detect in TypeScriptReflectionHost when a ts.Symbol
refers to a shorthand property, and to use the ts.TypeChecker method
getShorthandAssignmentValueSymbol() to resolve the value of the assignment
instead.

FW-1089 #resolve

PR Close #28936
2019-02-27 08:48:54 -08:00
Wassim Chegham dad5a258b8 style: enforce buildifier lint on CI (#28186)
PR Close #28186
2019-02-26 16:57:41 -08:00
Wassim Chegham ce68b4d839 style: enforce buildifier lint on CI (#28186)
PR Close #28186
2019-02-26 16:57:41 -08:00
Marc Laval 8f8f9a6e61 fix(ivy): ngtsc should correctly bind to context in nested template with many bindings (#28982)
PR Close #28982
2019-02-26 11:54:13 -08:00
Alex Rickabaugh c1392ce618 feat(ivy): produce and consume ES2015 re-exports for NgModule re-exports (#28852)
In certain configurations (such as the g3 repository) which have lots of
small compilation units as well as strict dependency checking on generated
code, ngtsc's default strategy of directly importing directives/pipes into
components will not work. To handle these cases, an additional mode is
introduced, and is enabled when using the FileToModuleHost provided by such
compilation environments.

In this mode, when ngtsc encounters an NgModule which re-exports another
from a different file, it will re-export all the directives it contains at
the ES2015 level. The exports will have a predictable name based on the
FileToModuleHost. For example, if the host says that a directive Foo is
from the 'root/external/foo' module, ngtsc will add:

```
export {Foo as ɵng$root$external$foo$$Foo} from 'root/external/foo';
```

Consumers of the re-exported directive will then import it via this path
instead of directly from root/external/foo, preserving strict dependency
semantics.

PR Close #28852
2019-02-22 12:15:58 -08:00
Alex Rickabaugh 15c065f9a0 refactor(ivy): extract selector scope logic to a new ngtsc package (#28852)
This commit splits apart selector_scope.ts in ngtsc and extracts the logic
into two separate classes, the LocalModuleScopeRegistry and the
DtsModuleScopeResolver. The logic is cleaned up significantly and new tests
are added to verify behavior.

LocalModuleScopeRegistry implements the NgModule semantics for compilation
scopes, and handles NgModules declared in the current compilation unit.
DtsModuleScopeResolver implements simpler logic for export scopes and
handles NgModules declared in .d.ts files.

This is done in preparation for the addition of re-export logic to solve
StrictDeps issues.

PR Close #28852
2019-02-22 12:15:58 -08:00
Kristiyan Kostadinov 32ae84da28 fixup! fix(ivy): incorrectly remapping certain properties that refer to inputs (#28765)
PR Close #28765
2019-02-21 17:59:50 -08:00
Greg Magolan ebffde7143 build: update to rules_typescript 0.25.1 (#28625)
Updated a spot in the compiler which assumed es5 downlevelling get ready for es2015 devmode in the future.

PR Close #28625
2019-02-21 07:46:21 -08:00
Andrew Kushnir 95d9aa22ef fix(ivy): allow HTML comments to be present inside <ng-content> (#28849)
Prior to this change presence of HTML comments inside <ng-content> caused compiler to throw an error that <ng-content> is not empty. Now HTML comments are not considered as a meaningful content, thus no error is thrown. This behavior is now aligned in Ivy/VE.

PR Close #28849
2019-02-21 00:13:40 -08:00
Andrew Kushnir df627e65df fix(ivy): correct absolute path processing for templateUrl and styleUrls (#28789)
Prior to this change absolute file paths (like `/a/b/c/style.css`) were calculated taking current component file location into account. As a result, absolute file paths were calculated using current file as a root. This change updates this logic to ignore current file path in case of absolute paths.

PR Close #28789
2019-02-21 00:13:12 -08:00
Andrew Kushnir 72d043f669 fix(ivy): check the presence of .css resource for styleUrls (#28770)
Prior to this change, Ivy and VE CSS resource resolution was different: in addition to specified styleUrl (with .scss, .less and .styl extensions), VE also makes an attempt to resolve resource with .css extension. This change introduces similar logic for Ivy to make sure Ivy behavior is backwards compatible.

PR Close #28770
2019-02-21 00:12:43 -08:00
Andrew Kushnir be121bba85 fix(ivy): restore @fileoverview annotations for Closure (#28723)
Prior to this change, the @fileoverview annotations added by users in source files or by tsickle during compilation might have change a location due to the fact that Ngtsc may prepend extra imports or constants. As a result, the output file is considered invalid by Closure (misplaced @fileoverview annotation). In order to resolve the problem we relocate @fileoverview annotation if we detect that its host node shifted.

PR Close #28723
2019-02-21 00:12:14 -08:00
Paul Gschwendtner 58436fd81a fix(ivy): unable to import shim factory files on case-insensitive platforms (#28831)
This change is kind of similar to #27466, but instead of ensuring that
these shims can be generated, we also need to make sure that developers
are able to also use the factory shims like with `ngc`.

This issue is now surfacing because we have various old examples which
are now also built with `ngtsc`  (due to the bazel migration). On case insensitive
platforms (e.g. windows) these examples cannot be built because ngtsc fails
the app imports a generated shim file (such as the factory shim files).

This is because the `GeneratedShimsHostWrapper` TypeScript host uses
the `getCanonicalFileName` method in order to check whether a given
file/module exists in the generator file maps. e.g.

```
// Generator Map:
'C:/users/paul/_bazel_paul/lm3s4mgv/execroot/angular/packages/core/index.ngfactory.ts' =>
'C:/users/paul/_bazel_paul/lm3s4mgv/execroot/angular/packages/core/index.ts',

// Path passed into `fileExists`
C:/users/paul/_bazel_paul/lm3s4mgv/execroot/angular/packages/core/index.ngfactory.ts

// After getCanonicalFileName (notice the **lower-case drive name**)
c:/users/paul/_bazel_paul/lm3s4mgv/execroot/angular/packages/core/index.ngfactory.ts
```

As seen above, the generator map does not use the canonical file names, as well as
TypeScript internally does not pass around canonical file names. We can fix this by removing
the manual call to `getCanonicalFileName` and just following TypeScript internal-semantics.

PR Close #28831
2019-02-20 18:26:05 -08:00
Paul Gschwendtner 3336de0970 refactor(ivy): fix typo in ngtsc "listLazyRoutes" method (#28831)
Fixes a minor typo in the `listLazyRoutes` method for `ngtsc`. Also in
addition fixes that a newly introduced test for `listLazyRoutes` broke the
tests in Windows. It's clear that we still don't run tests against
Windows, but we also made all other tests pass (without CI verification),
and it's not a big deal fixing this while being at it.

PR Close #28831
2019-02-20 18:26:05 -08:00
Matias Niemelä d0e81eb593 feat(ivy): open up ivy_switch_mode to non-core packages (#28711)
Prior to this fix, using the compiler's ivy_switch mechanism was
only available to core packages. This patch allows for this variable
switching mechanism to work across all other angular packages.

PR Close #28711
2019-02-20 13:46:14 -08:00
Greg Magolan 25aae64274 build(bazel): do not build rxjs from source under Bazel (#28720)
PR Close #28720
2019-02-19 16:28:14 -08:00
Kara Erickson 3c1a1620e3 fix(ivy): support static ContentChild queries (#28811)
This commit adds support for the `static: true` flag in `ContentChild`
queries. Prior to this commit, all `ContentChild` queries were resolved
after change detection ran. This is a problem for backwards
compatibility because View Engine also supported "static" queries which
would resolve before change detection.

Now if users add a `static: true` option, the query will be resolved in
creation mode (before change detection runs). For example:

```ts
@ContentChild(TemplateRef, {static: true}) template !: TemplateRef;
```

This feature will come in handy for components that need
to create components dynamically.

PR Close #28811
2019-02-19 15:29:01 -08:00
Kara Erickson a4638d5a81 fix(ivy): support static ViewChild queries (#28811)
This commit adds support for the `static: true` flag in
`ViewChild` queries. Prior to this commit, all `ViewChild`
queries were resolved after change detection ran. This is
a problem for backwards compatibility because View Engine
also supported "static" queries which would resolve before
change detection.

Now if users add a `static: true` option, the query will be
resolved in creation mode (before change detection runs).
For example:

```ts
@ViewChild(TemplateRef, {static: true}) template !: TemplateRef;
```

This feature will come in handy for components that need
to create components dynamically.

PR Close #28811
2019-02-19 15:29:00 -08:00
George Kalpakas 745c9c5ca7 build(compiler-cli): upgrade chokidar to latest version (#28797)
Fixes #28771

PR Close #28797
2019-02-19 12:54:11 -08:00
Paul Gschwendtner 4131715df5 fix(compiler-cli): incorrect bundled metadata for static class member call expressions (#28762)
Currently if developers use call expressions in their static
class members ([like we do in Angular](https://github.com/angular/angular/blob/master/packages/core/src/change_detection/differs/keyvalue_differs.ts#L121)),
the metadata that is generated for flat modules is invalid. This
is because the metadata bundler logic currently does not handle
call expressions in static class members and the symbol references
are not rewritten to avoid relative paths in the bundle.

Static class members using a call expression are not relevant for
the ViewEngine AOT compilation, but it is problematic that the
bundled metadata references modules using their original relative
path. This means that the bundled metadata is no longer encapsulated
and depends on other emitted files to be emitted in the proper place.

These incorrect relative paths can now cause issues where NGC
looks for the referenced symbols in the incorrect path. e.g.

```
src/
 | lib/
    | index.ts -> References the call expression using `../../di`
```

Now the metadata looks like that:

```
node_modules/
  | @angular/
  -- | core/
  -- -- | core.metadata.json -> Says that the call expr. is in `../../di`.
  | di/
```

Now if NGC tries to use the metadata files and create the summary files,
NGC resolves the call expression to the `node_modules/di` module. Since
the "unexpected" module does not contain the desired symbol, NGC will
error out.

We should fix this by ensuring that we don't ship corrupted metadata
to NPM which contains relative references that can cause such
failures (other imports can be affected as well; it depends on what
modules the developer has installed and how we import our call
expressions).

Fixes #28741.

PR Close #28762
2019-02-19 12:53:18 -08:00
Filipe Silva 1923c2f99c feat(compiler-cli): make enableIvy ngtsc/true equivalent (#28616)
Currently setting `enableIvy` to true runs a hybrid mode of `ngc` and `ngtsc`. This is counterintuitive given the name of the flag itself.

This PR makes the `true` value equivalent to the previous `ngtsc`, and `ngtsc` becomes an alias for `true`. Effectively this removes the hybrid mode as well since there's no other way to enable it.

PR Close #28616
2019-02-19 12:28:44 -08:00
George Kalpakas 6b511a33f6 fix(ivy): fix class inheritance detection for ES5 code in `ngtsc` (#28773)
Previously, `ngtsc` detected class inheritance in a way that only worked
in TS or ES2015 code. As a result, inheritance would not be detected for
code in ES5 format, such as when running `ngtsc` through `ngcc` to
transform old-style Angular code to ivy format.

This commit fixes it by delegating class inheritance detection to the
current `ReflectionHost`, which is able to correctly interpret the used
code format.

PR Close #28773
2019-02-16 21:00:50 -08:00
Kristiyan Kostadinov 80a5934af6 fix(ivy): support schemas at runtime (#28637)
Accounts for schemas in when validating properties in Ivy.

This PR resolves FW-819.

A couple of notes:
* I had to rework the test slightly, in order to have it fail when we expect it to. The one in master is passing since Ivy's validation runs during the update phase, rather than creation.
* I had to deviate from the design in FW-819 and not add an `enableSchema` instruction, because the schema is part of the `NgModule` scope, however the scope is only assigned to a component once all of the module's declarations have been resolved and some of them can be async. Instead, I opted to have the `schemas` on the component definition.

PR Close #28637
2019-02-14 19:31:51 +00:00
Paul Gschwendtner 7cbc36fdac build: remove unused rollup.config.js files (#28646)
Since we build and publish the individual packages
using Bazel and `build.sh` has been removed, we can
safely remove the `rollup.config.js` files which are no
longer needed because the `ng_package` bazel rule
automatically handles the rollup settings and globals.

PR Close #28646
2019-02-14 19:28:08 +00:00
Alex Rickabaugh 423b39e216 feat(ivy): use fileNameToModuleName to emit imports when it's available (#28523)
The ultimate goal of this commit is to make use of fileNameToModuleName to
get the module specifier to use when generating an import, when that API is
available in the CompilerHost that ngtsc is created with.

As part of getting there, the way in which ngtsc tracks references and
generates import module specifiers is refactored considerably. References
are tracked with the Reference class, and previously ngtsc had several
different kinds of Reference. An AbsoluteReference represented a declaration
which needed to be imported via an absolute module specifier tracked in the
AbsoluteReference, and a RelativeReference represented a declaration from
the local program, imported via relative path or referred to directly by
identifier if possible. Thus, how to refer to a particular declaration was
encoded into the Reference type _at the time of creation of the Reference_.

This commit refactors that logic and reduces Reference to a single class
with no subclasses. A Reference represents a node being referenced, plus
context about how the node was located. This context includes a
"bestGuessOwningModule", the compiler's best guess at which absolute
module specifier has defined this reference. For example, if the compiler
arrives at the declaration of CommonModule via an import to @angular/common,
then any references obtained from CommonModule (e.g. NgIf) will also be
considered to be owned by @angular/common.

A ReferenceEmitter class and accompanying ReferenceEmitStrategy interface
are introduced. To produce an Expression referring to a given Reference'd
node, the ReferenceEmitter consults a sequence of ReferenceEmitStrategy
implementations.

Several different strategies are defined:

- LocalIdentifierStrategy: use local ts.Identifiers if available.
- AbsoluteModuleStrategy: if the Reference has a bestGuessOwningModule,
  import the node via an absolute import from that module specifier.
- LogicalProjectStrategy: if the Reference is in the logical project
  (is under the project rootDirs), import the node via a relative import.
- FileToModuleStrategy: use a FileToModuleHost to generate the module
  specifier by which to import the node.

Depending on the availability of fileNameToModuleName in the CompilerHost,
then, a different collection of these strategies is used for compilation.

PR Close #28523
2019-02-13 19:13:11 -08:00
Alex Rickabaugh a529f53031 feat(ivy): introduce concrete types for paths in ngtsc (#28523)
This commit introduces a new ngtsc sub-library, 'path', which contains
branded string types for the different kind of paths that ngtsc manipulates.
Having static types for these paths will reduce the number of path-related
bugs (especially on Windows) and will eliminate unnecessary defensive
normalizing.

See the README.md file for more detail.

PR Close #28523
2019-02-13 19:13:11 -08:00
Alex Rickabaugh 99d8582882 feat(ivy): support @Injectable on already decorated classes (#28523)
Previously, ngtsc would throw an error if two decorators were matched on
the same class simultaneously. However, @Injectable is a special case, and
it appears frequently on component, directive, and pipe classes. For pipes
in particular, it's a common pattern to treat the pipe class also as an
injectable service.

ngtsc actually lacked the capability to compile multiple matching
decorators on a class, so this commit adds support for that. Decorator
handlers (and thus the decorators they match) are classified into three
categories: PRIMARY, SHARED, and WEAK.

PRIMARY handlers compile decorators that cannot coexist with other primary
decorators. The handlers for Component, Directive, Pipe, and NgModule are
marked as PRIMARY. A class may only have one decorator from this group.

SHARED handlers compile decorators that can coexist with others. Injectable
is the only decorator in this category, meaning it's valid to put an
@Injectable decorator on a previously decorated class.

WEAK handlers behave like SHARED, but are dropped if any non-WEAK handler
matches a class. The handler which compiles ngBaseDef is WEAK, since
ngBaseDef is only needed if a class doesn't otherwise have a decorator.

Tests are added to validate that @Injectable can coexist with the other
decorators and that an error is generated when mixing the primaries.

PR Close #28523
2019-02-13 19:13:10 -08:00
Alex Rickabaugh d2742cf473 feat(ivy): compile @Injectable on classes not meant for DI (#28523)
In the past, @Injectable had no side effects and existing Angular code is
therefore littered with @Injectable usage on classes which are not intended
to be injected.

A common example is:

@Injectable()
class Foo {
  constructor(private notInjectable: string) {}
}

and somewhere else:

providers: [{provide: Foo, useFactory: ...})

Here, there is no need for Foo to be injectable - indeed, it's impossible
for the DI system to create an instance of it, as it has a non-injectable
constructor. The provider configures a factory for the DI system to be
able to create instances of Foo.

Adding @Injectable in Ivy signifies that the class's own constructor, and
not a provider, determines how the class will be created.

This commit adds logic to compile classes which are marked with @Injectable
but are otherwise not injectable, and create an ngInjectableDef field with
a factory function that throws an error. This way, existing code in the wild
continues to compile, but if someone attempts to use the injectable it will
fail with a useful error message.

In the case where strictInjectionParameters is set to true, a compile-time
error is thrown instead of the runtime error, as ngtsc has enough
information to determine when injection couldn't possibly be valid.

PR Close #28523
2019-02-13 19:13:10 -08:00
Alex Rickabaugh f8b67712bc fix(ivy): translate WriteKeyExpr expressions properly (#28523)
Translation of WriteKeyExpr expressions was not implemented in the ngtsc
expression translator. This resulted in binding expressions like
"target[key] = $event" not compiling.

This commit fixes the bug by implementing WriteKeyExpr translation.

PR Close #28523
2019-02-13 19:13:10 -08:00
Alex Rickabaugh 3477610f6d fix(ivy): resolve enum values in host bindings (#28523)
Some applications use enum values in their host bindings:

@Component({
  host: {
    '[prop]': EnumType.Key,
  }, ...
})

This commit changes the resolution of host properties to follow the enum
declaration and extract the correct value for the binding.

PR Close #28523
2019-02-13 19:13:10 -08:00
Alex Rickabaugh 09af7ea4f5 fix(compiler): fix two existing expression transformer issues (#28523)
Testing of Ivy revealed two bugs in the AstMemoryEfficientTransformer
class, a part of existing View Engine compiler infrastructure that's
reused in Ivy. These bugs cause AST expressions not to be transformed
under certain circumstances.

The fix is simple, and tests are added to ensure the specific expression
forms that trigger the issue compile properly under Ivy.

PR Close #28523
2019-02-13 19:13:10 -08:00
Andrew Kushnir 39d0311e4e refactor(ivy): combine contentQueries and contentQueriesRefresh functions (#28503)
Prior to this update we had separate contentQueries and contentQueriesRefresh functions to handle creation and update phases. This approach was inconsistent with View Queries, Host Bindings and Template functions that we generate for Component/Directive defs. Now the mentioned 2 functions are combines into one (contentQueries), creation and update logic is separated with RenderFlags (similar to what we have in other generated functions).

PR Close #28503
2019-02-13 12:01:32 -08:00
Paul Gschwendtner 91b7152852 feat(compiler-cli): no longer re-export external symbols by default (#28633)
With #28594 we refactored the `@angular/compiler` slightly to
allow opting out from external symbol re-exports which are
enabled by default.

Since symbol re-exports only benefit projects which have a
very strict dependency enforcement, external symbols should
not be re-exported by default as this could grow the size of
factory files and cause unexpected behavior with Angular's
AOT symbol resolving (e.g. see: #25644).

Note that the common strict dependency enforcement for source
files does still work with external symbol re-exports disabled,
but there are also strict dependency checks that enforce strict
module dependencies also for _generated files_ (such as the
ngfactory files). This is how Google3 manages it's dependencies
and therefore external symbol re-exports need to be enabled within
Google3.

Also "ngtsc" also does not provide any way of using external symbol
re-exports, so this means that with this change, NGC can partially
match the behavior of "ngtsc" then (unless explicitly opted-out).

As mentioned before, internally at Google symbol re-exports need to
be still enabled, so the `ng_module` Bazel rule will enable the symbol
re-exports by default when running within Blaze.

Fixes #25644.

PR Close #28633
2019-02-13 09:49:51 -08:00
JoostK 2afc40608d fix(ivy): support injecting ChangeDetectorRef on templates (#27565)
Previously, using a pipe in an input binding on an ng-template would
evaluate the pipe in the context of node that was processed before the
template. This caused the retrieval of e.g. ChangeDetectorRef to be
incorrect, resulting in one of the following bugs depending on the
template's structure:

1. If the template was at the root of a view, the previously processed
node would be the component's host node outside of the current view.
Accessing that node in the context of the current view results in a crash.
2. For templates not at the root, the ChangeDetectorRef injected into the
pipe would correspond with the previously processed node. If that node
hosts a component, the ChangeDetectorRef would not correspond with the
view that the ng-template is part of.

The solution to the above problem is two-fold:

1. Template compilation is adjusted such that the template instruction
is emitted before any instructions produced by input bindings, such as
pipes. This ensures that pipes are evaluated in the context of the
template's container node.
2. A ChangeDetectorRef can be requested for container nodes.

Fixes #28587

PR Close #27565
2019-02-13 09:46:53 -08:00
Pete Bacon Darwin d68a98f0cd test(ivy): add template source mapping tests (#28055)
PR Close #28055
2019-02-12 20:58:28 -08:00
Pete Bacon Darwin 08de52b9f0 feat(ivy): add source mappings to compiled Angular templates (#28055)
During analysis, the `ComponentDecoratorHandler` passes the component
template to the `parseTemplate()` function. Previously, there was little or
no information about the original source file, where the template is found,
passed when calling this function.

Now, we correctly compute the URL of the source of the template, both
for external `templateUrl` and in-line `template` cases. Further in the
in-line template case we compute the character range of the template
in its containing source file; *but only in the case that the template is
a simple string literal*. If the template is actually a dynamic value like
an interpolated string or a function call, then we do not try to add the
originating source file information.

The translator that converts Ivy AST nodes to TypeScript now adds these
template specific source mappings, which account for the file where
the template was found, to the templates to support stepping through the
template creation and update code when debugging an Angular application.

Note that some versions of TypeScript have a bug which means they cannot
support external template source-maps. We check for this via the
`canSourceMapExternalTemplates()` helper function and avoid trying to
add template mappings to external templates if not supported.

PR Close #28055
2019-02-12 20:58:28 -08:00
Pete Bacon Darwin c0dac184cd fix(compiler): markup lexer should not capture quotes in attribute value (#28055)
When tokenizing markup (e.g. HTML) element attributes
can have quoted or unquoted values (e.g. `a=b` or `a="b"`).
The `ATTR_VALUE` tokens were capturing the quotes, which
was inconsistent and also affected source-mapping.

Now the tokenizer captures additional `ATTR_QUOTE` tokens,
which the HTML related parsers understand and factor into their
token parsing.

PR Close #28055
2019-02-12 20:58:27 -08:00
Pete Bacon Darwin 673ac2945c refactor(compiler): use `options` argument for parsers (#28055)
This commit consolidates the options that can modify the
parsing of text (e.g. HTML, Angular templates, CSS, i18n)
into an AST for further processing into a single `options`
hash.

This makes the code cleaner and more readable, but also
enables us to support further options to parsing without
triggering wide ranging changes to code that should not
be affected by these new options.  Specifically, it will let
us pass information about the placement of a template
that is being parsed in its containing file, which is essential
for accurate SourceMap processing.

PR Close #28055
2019-02-12 20:58:27 -08:00
George Kalpakas cdabda1fc0 test(ivy): test listing lazy routes to different root directories (#28542)
PR Close #28542
2019-02-11 16:23:30 -08:00
George Kalpakas 188f20fb16 fix(ivy): support listing lazy route for project-root-relative entry point in `ngtsc` (#28542)
I don't know of any use of this API with a project-root-relative path
(i.e. the cli will always call it with an absolute path), but keeping
the API backwards compatible just in case.

PR Close #28542
2019-02-11 16:23:30 -08:00
George Kalpakas 3eec314ba9 test(ivy): fix `ngtools_api` test under ivy (#28542)
PR Close #28542
2019-02-11 16:23:29 -08:00
George Kalpakas e6c51b3e06 feat(ivy): implement listing lazy routes for specific entry point in `ngtsc` (#28542)
Related: angular/angular-cli#13532

Jira issue: FW-860

PR Close #28542
2019-02-11 16:23:29 -08:00
George Kalpakas f358188ec1 refactor(ivy): create lazy route keys that are similar to ngtools lazy routes (#28542)
This will make it easier to retrieve routes for specific entry points in
`listLazyRoutes()` (which is necessary for CLI integration but not yet
implemented).

PR Close #28542
2019-02-11 16:23:29 -08:00
George Kalpakas 5db3a6b198 refactor(ivy): remove unnecessary method from ngtsc's `RouterEntryPoint` (#28542)
PR Close #28542
2019-02-11 16:23:29 -08:00
Matias Niemelä fe8301c462 feat(ivy): provide support for map-based host bindings for [style] and [class] (#28246)
Up until now, `[style]` and `[class]` bindings (the map-based ones) have only
worked as template bindings and have not been supported at all inside of host
bindings. This patch ensures that multiple host binding sources (components and
directives) all properly assign style values and merge them correctly in terms
of priority.

Jira: FW-882

PR Close #28246
2019-02-11 16:21:19 -08:00
Alexey Zuev 2bf0d1a56f fix(ivy): compile pipe in context of ternary operator (#28635)
Previously, it wasn't possible to compile template that contains pipe in context of ternary operator `{{ 1 ? 2 : 0 | myPipe }}` due to the error `Error: Illegal state: Pipes should have been converted into functions. Pipe: async`.

This PR fixes a typo in expression parser so that pipes are correctly converted into functions.

PR Close #28635
2019-02-11 14:52:13 -08:00
Andrew Kushnir a9afe629c7 feat(ivy): allow non-unique #localRefs to be defined in a template (#28627)
Prior to this change in Ivy we had strict check that disabled non-unique #localRefs usage within a given template. While this limitation was technically present in View Engine, in many cases View Engine neglected this restriction and as a result, some apps relied on a fact that multiple non-unique #localRefs can be defined and utilized to query elements via @ViewChild(ren) and @ContentChild(ren). In order to provide better compatibility with View Engine, this commit removes existing restriction.

As a part of this commit, are few tests were added to verify VE and Ivy compatibility in most common use-cases where multiple non-unique #localRefs were used.

PR Close #28627
2019-02-11 14:51:31 -08:00
Filipe Silva 2caa419990 fix(compiler-cli): don't throw when listing lazy routes for an entry route (#28372)
In https://github.com/angular/angular/pull/27697 the listLazyRoutes was fixed to work with ivy.

Since the entryRoute argument is not supported, it was made to also error.

But by erroring it breaks existing usage with Angular CLI where the entry route is sent in as an argument.

This commit changes listLazyRoutes to not error out, but instead ignore the argument.

PR Close #28372
2019-02-07 12:36:51 -08:00
Andrew Kushnir 3f73dfa151 fix(ivy): sanitize external i18n ids before generating const names (#28522)
Prior to this change there was no i18n id sanitization before we output goog.getMsg calls. Due to the fact that message ids are used as a part of const names, some characters were bcausing issues while executing generated code. This commit adds sanitization to i18n ids used to generate i18n-related consts.

PR Close #28522
2019-02-05 23:29:44 -05:00
Greg Magolan 0d1e065a1c build: update to rules_typescript 0.23.2 and rules_nodejs 0.16.8 (#28532)
PR Close #28532
2019-02-05 16:55:43 -05:00
Paul Gschwendtner 744b0205e2 build: fix failing compiler-cli tests on windows (#28352)
Note that this fixes `compiler-cli` tests within `compiler-cli/test`,
but there seem to be remaining `ngcc` tests within `compiler-cli/src`
which aren't working on Windows. This is out-of-scope for this commit.

PR Close #28352
2019-02-05 14:31:10 -05:00
Paul Gschwendtner 40da1be1e1 build: support running ngtsc tests on windows (#28352)
Currently the "ngtsc` testing helpers resolve the `fake_core` NPM
package using the `TEST_SRCDIR` variable. This is problematic on Windows
where Bazel runfiles are not symlinked into the runfiles directory.
In order to properly resolve the NPM Bazel tree artifact, we use the
`resolveTreeNpmArtifact` runfile helper that properly resolves the artifact
properly on all platforms.

PR Close #28352
2019-02-05 14:31:10 -05:00
Paul Gschwendtner c10d86cbc0 build: support running compiler-cli tests on windows (#28352)
In order to support running "compiler-cli" tests that use the "test_support.ts"
utilities on Windows with Bazel, we need to imporve the logic that resolves NPM
packages and symlinks them into a temporary directory.

A more Bazel idiomatic and windows compatible way of resolving Bazel runfiles
is to use the "RUNFILES_MANIFEST" if present. This ensures that the NPM
packages can be also symlinked on Windows, and tests can execute properly
on Windows. Read more about why this is needed here:

* https://github.com/bazelbuild/bazel/issues/3726#issue-257062364

PR Close #28352
2019-02-05 14:31:10 -05:00
Paul Gschwendtner b91a25bfb2 build: remove unused "test.sh" leftover code in compiler-cli (#28352)
Since we recently removed the `test.sh` script, and now run
all tests with Bazel, we can remove the unused logic that makes
compiler-cli tests pass in non-Bazel.

This cleans up the tests, and also makes it easier to write tests
without worrying about two ways of the Angular package output
(Bazel `ng_package` rules vs. old `build.sh` logic of building)

PR Close #28352
2019-02-05 14:31:10 -05:00
Paul Gschwendtner 4aa189da67 fix(compiler-cli): diagnostics should respect "newLine" compiler option (#28352)
PR Close #28352
2019-02-05 14:31:10 -05:00
Alex Eagle 7219639ff3 fix(compiler-cli): base synthetic filepaths on input filepath (#28453)
This change is needed to work in google3, where file paths in the
ts.Program must always be absolute.

PR Close #28453
2019-02-04 17:27:35 -05:00
Kara Erickson f2621dbb37 fix(core): remove createInjector() from public API (#28509)
createInjector() is an Ivy-only API that should not have
been exported as part of the public API. This commit removes
the export. It will be re-exported when Ivy is released.

PR Close #28509
2019-02-04 16:54:26 -05:00
Alex Eagle a227c528ca feat(compiler-cli): expose ngtsc as a TscPlugin (#28435)
This lets us run ngtsc under the tsc_wrapped custom compiler (Used in Bazel)
It also allows others to simply wire ngtsc into an existing typescript compilation binary

PR Close #28435
2019-01-29 16:41:59 -08:00
Kara Erickson fdc6e159b4 fix(ivy): throw if @Input and @ContentChild share a property (#28415)
In View Engine, we supported @Input and @ContentChild annotations
on the same property. This feature was somewhat brittle because
it would only work for static queries, so it would break if a
content child was passed in wrapped in an *ngIf. Due to the
inconsistent behavior and low usage both internally and externally,
we will likely be deprecating it in the next version, and it does
not make sense to perpetuate it in Ivy.

This commit ensures that we now throw in Ivy if we encounter the
two annotations on the same property.

PR Close #28415
2019-01-29 16:40:22 -08:00
cexbrayat 66ce3b2f2f fix(ivy): scan simple children routes with no infinite recursion (#28370)
PR Close #28370
2019-01-29 16:37:48 -08:00
Andrew Kushnir 76cedb8bf3 fix(ivy): verify Host Bindings and Host Listeners before compiling them (#28356)
Prior to this change we may encounter some errors (like pipes being used where they should not be used) while compiling Host Bindings and Listeners. With this update we move validation logic to the analyze phase and throw an error if something is wrong. This also aligns error messages between Ivy and VE.

PR Close #28356
2019-01-29 16:36:22 -08:00
onlyflix 41e68f7a7a style: change to American English (#27266)
PR Close #27266
2019-01-29 16:30:25 -08:00
Filipe Silva bcf17bc91c refactor(compiler-cli): return TS nodes from TypeTranslatorVisitor (#28342)
The TypeTranslatorVisitor visitor returned strings because before it wasn't possible to transform declaration files directly through the TypeScript custom transformer API.

Now that's possible though, so it should return nodes instead.

PR Close #28342
2019-01-29 12:00:55 -08:00
Filipe Silva d45d3a3ef9 refactor(compiler-cli): use a transformer for dts files (#28342)
The current DtsFileTransformer works by intercepting file writes and editing the source string directly.

This PR refactors it as a afterDeclaration transform in order to fit better in the TypeScript API.

This is part of a greater effort of converting ngtsc to be usable as a TS transform plugin.

PR Close #28342
2019-01-29 12:00:55 -08:00
Filipe Silva f99a668b04 refactor(compiler-cli): refactor import adding logic into helper (#28342)
This logic will be common to transforms that add imports. Using it as a helper helps reduce duplication

PR Close #28342
2019-01-29 12:00:55 -08:00
Jason Aden 227f7e44d6 Revert "feat(compiler-cli): expose ngtsc as a TscPlugin" (#28433)
This reverts commit df2221c6476df1f2d2478b949702f3270c3a4565.

PR Close #28433
2019-01-29 11:29:48 -08:00
Alex Eagle 22f76df8f2 feat(compiler-cli): expose ngtsc as a TscPlugin (#28431)
This lets us run ngtsc under the tsc_wrapped custom compiler (Used in Bazel)
It also allows others to simply wire ngtsc into an existing typescript compilation binary

PR Close #28431
2019-01-29 09:44:58 -08:00
Jason Aden e18a52e24a Revert "feat(compiler-cli): expose ngtsc as a TscPlugin" (#28416)
This reverts commit cf4edbce40a3a65fdefe90760a93e43bc45b7d19.

PR Close #28416
2019-01-28 22:39:56 -08:00
Alex Eagle 59cc724e3b feat(compiler-cli): expose ngtsc as a TscPlugin (#27806)
This lets us run ngtsc under the tsc_wrapped custom compiler (Used in Bazel)
It also allows others to simply wire ngtsc into an existing typescript compilation binary

PR Close #27806
2019-01-28 20:16:47 -08:00
Paul Gschwendtner 8ced999e47 build: improve compiler-cli codegen output test (#28191)
* Improves the `compiler-cli/integrationtest` codegen output test slightly by using a more clear test description and by adding an assertion that ensures that decorators are downleveled.

PR Close #28191
2019-01-28 20:07:22 -08:00
Paul Gschwendtner 4c8d17ffd4 build: fix outdated ngtools compiler-cli test logic (#28191)
* Fixes that the test logic for `ngtools` in the offline compiler test is no longer working due to being unmaintained for a long time
* Makes the path comparison logic platform agnostic, so that the tests can be also executed on Windows

PR Close #28191
2019-01-28 20:07:22 -08:00
Paul Gschwendtner 3e6a1f0bc4 build: fix outdated i18n compiler-cli test assertions (#28191)
PR Close #28191
2019-01-28 20:07:22 -08:00
Paul Gschwendtner 40d64b6b58 build: run offline_compiler_test using bazel (#28191)
PR Close #28191
2019-01-28 20:07:22 -08:00
Andrew Kushnir bb94434d85 fix(ivy): Content Queries inheritance fix (#28324)
Prior to this change contentQueriesRefresh functions that represent refresh logic for @ContentQuery list were not composable, which caused problems in case one Directive inherits another one and both of them contain Content Queries. Due to the fact that we used indices to reference queries in refresh function, results were placed into wrong Queries. In order to avoid that we no longer use indices to reference queries and instead maintain current content query index while iterating through them. This allows us to compose contentQueriesRefresh functions and make inheritance feature work with Content Queries.

PR Close #28324
2019-01-28 19:59:00 -08:00
Kristiyan Kostadinov ebac5dba38 fix(ivy): don't generate code for blank NgModule fields (#28387)
Currently `compileNgModule` generates an empty array for optional fields that are omitted from an `NgModule` declaration (e.g. `bootstrap`, `exports`). This isn't necessary, because `defineNgModule` has some code to default these fields to empty arrays at runtime if they aren't defined. The following changes will only output code if there are values for the particular field.

PR Close #28387
2019-01-28 19:50:44 -08:00
Alex Rickabaugh 66335c36e6 fix(ivy): getSourceFile() of transformed nodes returns undefined (#28412)
In some cases, calling getSourceFile() on a node from within a TS
transform can return undefined (against the signature of the method).
In these cases, getting the original node first will work.

PR Close #28412
2019-01-28 16:42:48 -08:00
George Kalpakas 9d3dae42e9 fix(ivy): return correct declaration for class indentifiers for ES5 in ngcc (#26947)
PR Close #26947
2019-01-28 14:01:12 -08:00
Alex Rickabaugh 7d954dffd0 feat(ivy): detect cycles and use remote scoping of components if needed (#28169)
By its nature, Ivy alters the import graph of a TS program, adding imports
where template dependencies exist. For example, if ComponentA uses PipeB
in its template, Ivy will insert an import of PipeB into the file in which
ComponentA is declared.

Any insertion of an import into a program has the potential to introduce a
cycle into the import graph. If for some reason the file in which PipeB is
declared imports the file in which ComponentA is declared (maybe it makes
use of a service or utility function that happens to be in the same file as
ComponentA) then this could create an import cycle. This turns out to
happen quite regularly in larger Angular codebases.

TypeScript and the Ivy runtime have no issues with such cycles. However,
other tools are not so accepting. In particular the Closure Compiler is
very anti-cycle.

To mitigate this problem, it's necessary to detect when the insertion of
an import would create a cycle. ngtsc can then use a different strategy,
known as "remote scoping", instead of directly writing a reference from
one component to another. Under remote scoping, a function
'setComponentScope' is called after the declaration of the component's
module, which does not require the addition of new imports.

FW-647 #resolve

PR Close #28169
2019-01-28 12:10:25 -08:00
Alex Rickabaugh cac9199d7c feat(ivy): cycle detector for TypeScript programs (#28169)
This commit implements a cycle detector which looks at the import graph of
TypeScript programs and can determine whether the addition of an edge is
sufficient to create a cycle. As part of the implementation, module name
to source file resolution is implemented via a ModuleResolver, using TS
APIs.

PR Close #28169
2019-01-28 12:10:25 -08:00
Alex Rickabaugh a789a3f532 test(ivy): clean up two parameters in ngtsc_spec.ts inferred as 'any' (#28169)
PR Close #28169
2019-01-28 12:10:25 -08:00
JoostK f8c70011b1 fix(ivy): ngcc - handle accessor pairs in ES2015 (#28357)
ngcc's reflection host needs to be able to determine all members of a
class, which it does by using the `ts.Symbol` from TypeScript's
TypeChecker.  Such Symbol however may represent multiple class members
in the case of accessors; an equally named getter/setter accessor pair
is combined into a single `ts.Symbol`.

This commit introduces logic to recognize such accessors in order for
both the getter and setter to be considered as class member, similar to
ngtsc's behavior when operating on original TypeScript code.

One difference wrt the TypeScript host is that ngcc cannot see to which
accessor originally had any decorators applied to them, as decorators
are applied to the property descriptor in general, not a specific accessor.
If an accessor has both a setter and getter, any decorators are only
attached to the setter member.

PR Close #28357
2019-01-28 11:58:44 -08:00
JoostK adfc55e2c3 fix(ivy): ngcc - recognize accessor members in ES5 (#28357)
Prior to this change, accessor functions for getters and setters would
not be considered as class member, as their declaration is vastly
different from ES2015 syntax.

With this change, the ES5 reflection host has learned to recognize the
downleveled syntax for accessors, allowing for them to be considered as
class member once again.

Fixes #28226

PR Close #28357
2019-01-28 11:58:44 -08:00
Andrew Kushnir 2da82db3bc fix(ivy): proper i18n postprocessing in case of nested templates (#28209)
Prior to this change the postprocess step relied on the order of placeholders combined in one group (e.g. [�#1�|�*1:1�]). The order is not guaranteed in case we have nested templates (since we use BFS to process templates) and some tags are represented using same placeholders. This change performs postprocessing more accurate by keeping track of currently active template and searching for matching placeholder.

PR Close #28209
2019-01-25 12:54:29 -08:00
Andrew Kushnir 9098225ff0 fix(ivy): View Queries inheritance fix (#28309)
Prior to this change `viewQuery` functions that represent @ViewQuery list were not composable, which caused problems in case one Component/Directive inherits another one and both of them contain View Queries. Due to the fact that we used indices to reference queries, resulting query set was corrupted (child component queries were overridden by super class ones). In order to avoid that we no longer use indices assigned at compile time and instead maintain current view query index while iterating through them. This allows us to compose `viewQuery` functions and make inheritance feature work with View Queries.

PR Close #28309
2019-01-23 14:57:17 -08:00
Ben Lesh 5430d2bc66 fix(ivy): NgOnChangesFeature no longer included in hello_world (#28187)
- Wraps the NgOnChangesFeature in a factory such that no side effects occur in the module root
- Adds comments to ngInherit property on feature definition interface to help guide others not to make the same mistake
- Updates compiler to generate the feature properly after the change to it being a factory
- Updates appropriate tests

PR Close #28187
2019-01-23 10:59:34 -08:00
Ben Lesh 5552661fd7 refactor(ivy): revert onChanges change back to a feature (#28187)
- adds fixmeIvy annotation to tests that should remain updated so we can resolve those issues in the subsequent commits

PR Close #28187
2019-01-23 10:59:33 -08:00
Kristiyan Kostadinov d8f2318811 fix(ivy): generating incorrect tag name with namespace (#28298)
Fixes the template generation function generating an incorrect tag name when the element has a namespace (e.g. `:svg:circle` gets generated rather than `circle`).

PR Close #28298
2019-01-23 10:55:44 -08:00
Alex Rickabaugh 1964be0b17 feat(ivy): implement listLazyRoutes() for ngtsc (#27697)
This commit uses the NgModuleRouteAnalyzer introduced previously to
implement listLazyRoutes() for NgtscProgram. Currently this implementation
is limited to listing routes globally and cannot list routes for a given lazy
module. Testing seems to indicate that the CLI uses the global form, but this
should be verified.

Jira issue: FW-629

PR Close #27697
2019-01-22 12:02:10 -08:00
Alex Rickabaugh 41b2499f17 test(ivy): introduce route testing mode for ngtsc tests (#27697)
This commit introduces a new mode for the NgtscTestEnvironment which
builds the NgtscProgram and then asks for the list of lazy routes,
instead of running the TS emit phase.

PR Close #27697
2019-01-22 12:02:10 -08:00
Alex Rickabaugh da85cee07c feat(ivy): implement ngtsc's route analysis (#27697)
This commit introduces the NgModuleRouteAnalyzer & friends, which given
metadata about the NgModules in a program can extract the list of lazy
routes in the same format that the ngtools API uses.

PR Close #27697
2019-01-22 12:02:10 -08:00
George Kalpakas 2fc5f002e0 refactor(ivy): re-use the `ForeignFunctionResolver` interface when appropriate (#27697)
This makes the types (and intentions) more explicit and clear.

PR Close #27697
2019-01-22 12:02:10 -08:00
Alex Rickabaugh 19a2b783cf feat(ivy): create a ModuleResolver to map module paths to files (#27697)
PR Close #27697
2019-01-22 12:02:10 -08:00
Alex Rickabaugh 9e5016c845 feat(ivy): DynamicValue now indicates why the value is dynamic (#27697)
This commit changes the partial evaluation mechanism to propagate
DynamicValue errors internally during evaluation, and not to "poison"
entire data structures when a single value is dynamic. For example,
previously if any entry in an array was dynamic, evaluating the entire
array would return DynamicValue. Now, the array is returned with only
the specific dynamic entry as DynamicValue.

Instances of DynamicValue also report the node that was determined to
be dynamic, as well as a potential reason for the dynamic-ness. These
can be nested, so an expression `a + b` may have a DynamicValue that
indicates the 'a' term was DynamicValue, which will itself contain a
reason for the dynamic-ness.

This work was undertaken for the implementation of listLazyRoutes(),
which needs to partially evaluate provider arrays, parts of which are
dynamic and parts of which contain useful information.

PR Close #27697
2019-01-22 12:02:09 -08:00
Paul Gschwendtner 070fca1591 fix(ivy): ngtsc fails building flat module out on windows (#27993)
`ngtsc` currently fails building a flat module out file on Windows because it generates an invalid flat module TypeScript source file. e.g:

```ts
5 export * from './C:\Users\Paul\Desktop\test\src\export';
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```

This is because `path.posix.relative` does not properly with non-posix paths, and only expects posix paths in order to work.

PR Close #27993
2019-01-22 11:49:53 -08:00
Pete Bacon Darwin 73dcd72afb refactor(ivy): expose resolving URLs in the `ResourceLoader` (#28199)
Resources can be loaded in the context of another file, which
means that the path to the resource file must be resolved
before it can be loaded.

Previously the API of this interface did not allow the client
code to get access to the resolved URL which is used to load
the resource.

Now this API has been refactored so that you must do the
resource URL resolving first and the loading expects a
resolved URL.

PR Close #28199
2019-01-18 11:03:53 -08:00
Alex Eagle 38343a2388 build: set a default module_name for ts_library rules (#28051)
PR Close #28051
2019-01-18 10:16:39 -08:00
Alex Eagle a58fd210e9 feat(compiler-cli): resolve generated Sass/Less files to .css inputs (#28166)
Users might have run the CSS Preprocessor tool *before* the Angular
compiler. For example, we do it that way under Bazel. This means that
the design-time reference is different from the compile-time one - the
input to the Angular compiler is a plain .css file.

We assume that the preprocessor does a trivial 1:1 mapping using the same
basename with a different extension.

PR Close #28166
2019-01-18 09:49:19 -08:00
Matias Niemelä 6940992932 fix(ivy): ensure animation component host listeners are rendered in the sub component (#28210)
Due to the fact that animations in Angular are defined in the component metadata,
all animation trigger definitions are localized to the component and are
inaccessible outside of it. Animation host listeners in Ivy are
rendered in the context of the parent component, but the VE renders them
differently. This patch ensures that animation host listeners are
always registered in the sub component's renderer

Jira issue: FW-943
Jira issue: FW-958

PR Close #28210
2019-01-18 09:37:23 -08:00
Matias Niemelä e172e97e13 fix(ivy): ensure animation @trigger ordering is correctly delivered to the renderer (#28165)
In Ivy when elements are created a series of static attribute names are provided
over to the construction instruction of that element. Static attribute names
include non-binding attribues (like `<div selected>`) as well as animation bindings
that do not have a RHS value (like `<div @foo>`). Because of this distinction,
value-less animation triggers are rendered first before value-full animation
bindings are and this improper ordering has caused various existing tests to fail.
This patch ensures that animation bindings are evaluated in the order that they
exist within the HTML template code (or host binding code).

PR Close #28165
2019-01-17 09:58:29 -08:00
Matias Niemelä 0d6913f037 fix(ivy): ensure interpolated style/classes do not cause tracking issues for bindings (#28190)
With the refactoring or how styles/classes are implmented in Ivy,
interpolation has caused the binding code to mess up since interpolation
itself takes up its own slot in Ivy's memory management code. This patch
makes sure that interpolation works as expected with class and style
bindings.

Jira issue: FW-944

PR Close #28190
2019-01-17 09:58:14 -08:00
Andrew Kushnir 9a81f0d9a8 fix(ivy): update i18n/i18nStart and i18nAttributes instruction order (#28163)
Prior to this change element's i18n attributes like "i18n-title" were processed after "i18n" ones that placed "i18n" and "i18nAttributes" instructions in wrong order, thus "i18nAttributes" failed to target its host element at runtime. This change updates processing order and puts "i18nAttributes" instructions in front of "i18n" ones to resolve the problem.

PR Close #28163
2019-01-16 09:50:53 -08:00
Alan bc02e31185 fix(ivy): normalize summary and factory shim files paths (#28006)
At the moment, paths stored in `maps` are not normalized and in Windows is causing files not to be found when enabling factory shimming.

For example, the map contents will be
```
Map {
  'C:\\git\\cli-repos\\ng-factory-shims\\index.ngfactory.ts' => 'C:\\git\\cli-repos\\ng-factory-shims\\index.ts' }
```

However, ts compiler normalized the paths and is causing;
```
error TS6053: File 'C:/git/cli-repos/ng-factory-shims/index.ngfactory.ts' not found.
error TS6053: File 'C:/git/cli-repos/ng-factory-shims/index.ngsummary.ts' not found.
```

The changes normalized the paths that are stored within the factory and summary maps.

PR Close #28006
2019-01-15 11:21:58 -08:00
cexbrayat 6072ca87e1 fix(ivy): deps are actually supported (#28076)
This code was throwing if the `deps` array of a provider has several elements, but at the next line it resolves them... With this check `ngtsc` couldn’t compile `ng-bootstrap` for example.

PR Close #28076
2019-01-15 11:01:00 -08:00
Matias Niemelä 693045165c refactor(ivy): remove def.attributes in favor of the `elementHostAttrs` instruction (#28089)
Up until this point, all static attribute values (things like `title` and `id`)
defined within the `host` are of a Component/Directive definition were
generated into a `def.attributes` array and then processed at runtime.
This design decision does not lend itself well to tree-shaking and is
inconsistent with other static values such as styles and classes.

This fix ensures that all static attribute values (attributes, classes,
and styles) that exist within a host definition for components and
directives are all assigned via the `elementHostAttrs` instruction.

```
// before
defineDirective({
  ...
  attributes: ['title', 'my title']
  ...
})

//now
defineDirective({
  ...
  hostBindings: function() {
    if (create) {
      elementHostAttrs(..., ['title', 'my-title']);
    }
    ...
  }
  ...
})
```

PR Close #28089
2019-01-15 09:45:41 -08:00
Marc Laval fa53150692 test(ivy): NodeInjector should know how to get itself (INJECTOR) (#28009)
PR Close #28009
2019-01-14 17:09:26 -08:00
Kara Erickson 6fff74e576 test(ivy): re-enable passing tests and misc cleanup (#28093)
PR Close #28093
2019-01-14 10:03:57 -08:00
Andrew Kushnir 9260b5e0b4 fix(ivy): ignore empty bindings (#28059)
This update aligns Ivy behavior with ViewEngine related to empty bindings (for example <div [someProp]></div>): empty bindings are ignored.

PR Close #28059
2019-01-11 15:17:54 -08:00
Ben Lesh 8ebdb437dc fix(ivy): ngOnChanges only runs for binding updates (#27965)
PR Close #27965
2019-01-11 14:28:35 -08:00
Alex Rickabaugh 61bc61fc59 fix(ivy): ensure @nocollapse is added to static fields (#28050)
ngtsc has a hack to add @nocollapse jsdoc annotations to generated static
fields. This hack is currently broken (likely due to a TypeScript change
in the way writeFile() works).

This commit fixes the hack and introduces an ngtsc_spec test to ensure it
does not regress again.

PR Close #28050
2019-01-11 11:19:32 -08:00
Pete Bacon Darwin e31afb7118 fix(ivy): ngcc - identify all ESM5 decorated classes (#27848)
In ESM5 decorated classes can be indicated by calls to `__decorate()`.
Previously the `ReflectionHost.findDecoratedClasses()` call would identify
helper calls of the form:

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

But it was missing calls of the form:

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

This form is common in `@NgModule()` decorations, where the class
being decorated is referenced inside the decorator or another
member.

This commit now ensures that a chain of assignments, of any length,
is now identified as a class decoration if it results in a call to
`__decorate()`.

Fixes #27841

PR Close #27848
2019-01-11 11:14:01 -08:00
Kristiyan Kostadinov 9277142d54 fix(ivy): support multiple exportAs (#27996)
Allows for multiple, comma-separated `exportAs` names, similarly to `ViewEngine`.

These changes fix FW-708.

PR Close #27996
2019-01-10 16:53:26 -08:00
Pete Bacon Darwin feebe03523 fix(ivy): pass ngContentSelectors through to `defineComponent()` calls (#27867)
Libraries that create components dynamically using component factories,
such as `@angular/upgrade` need to pass blocks of projected content
through to the `ComponentFactory.create()` method. These blocks
are extracted from the content by matching CSS selectors defined in
`<ng-content select="..">` tags found in the component's template.

The Angular compiler collects these CSS selectors when compiling a component's
template, and exposes them via the `ComponentFactory.ngContentSelectors`
property.

This change ensures that this property is filled correctly when the
component factory is created by compiling a component with the Ivy engine.

PR Close #27867
2019-01-10 13:36:37 -08:00
Marc Laval 76ed13bffe fix(ivy): directives without selector should not be supported (#28021)
PR Close #28021
2019-01-10 10:51:30 -08:00
Andrew Kushnir c5ab3e8fd2 fix(ivy): proper resolution of Enums in Component decorator (#27971)
Prior to this change Component decorator was resolving `encapsulation` value a bit incorrectly, which resulted in `encapsulation: NaN` in compiled code. Now we resolve the value as Enum memeber and throw if it's not the case. As a part of this update, the `changeDetection` field handling is also added, the resolution logic is the same as the one used for `encapsulation` field.

PR Close #27971
2019-01-10 10:49:03 -08:00
Alex Rickabaugh 142553abc6 feat(ivy): accept multiple values for exportAs in the compiler (#28001)
exportAs in @Directive metadata supports multiple values, separated by
commas. Previously it was treated as a single value string.

This commit modifies the compiler to understand that exportAs is a
string[]. It stops short of carrying the multiple values through to the
runtime. Instead, it only emits the first one. A future commit will modify
the runtime to accept all the values.

PR Close #28001
2019-01-10 10:47:49 -08:00
Alex Rickabaugh 6003145422 fix(ivy): properly rewrite imports in generated factory shims (#27998)
Generated factory shims can import from @angular/core. However, we have
special logic in place to rewrite self-imports when generating code for
@angular/core.

This commit leverages the new standalone ImportRewriter interface to
properly rewrite imports in generated factory shims. Before this fix,
a generated factory file for core would look like:

```typescript
import * as i0 from './r3_symbols';

export var ApplicationModuleNgFactory = new ɵNgModuleFactory(...);
```

This is invalid, as ɵNgModuleFactory is just NgModuleFactory when imported
via r3_symbols.

FW-881 #resolve

PR Close #27998
2019-01-10 10:46:32 -08:00
Alex Rickabaugh 3cf1b62722 refactor(ivy): extract import rewriting into a separate interface (#27998)
Currently the ImportManager class handles various rewriting actions of
imports when compiling @angular/core. This is required as code compiled
within @angular/core cannot import from '@angular/core'. To work around
this, imports are rewritten to get core symbols from a particular file,
r3_symbols.ts.

In this refactoring, this rewriting logic is moved out of the ImportManager
and put behind an interface, ImportRewriter. There are three implementers
of the interface:

* NoopImportRewriter, used for compiling all non-core packages.
* R3SymbolsImportRewriter, used when ngtsc compiles @angular/core.
* NgccFlatImportRewriter, used when ngcc compiles @angular/core (special
  logic is needed because ngcc has to rewrite imports in flat bundles
  differently than in non-flat bundles).

This is a precursor to using this rewriting logic in other contexts besides
the ImportManager.

PR Close #27998
2019-01-10 10:46:32 -08:00
JoostK d68ad3e617 fix(ivy): ngcc - recognize synthesized constructors (#27897)
A constructor function may have been "synthesized" by TypeScript during
JavaScript emit, in the case no user-defined constructor exists and e.g.
property initializers are used. Those initializers need to be emitted
into a constructor in JavaScript, so the TypeScript compiler generates a
synthetic constructor.

This commit adds identification of such constructors as ngcc needs to be
able to tell if a class did originally have a constructor in the
TypeScript source. When a class has a superclass, a synthesized
constructor must not be considered as a user-defined constructor as that
prevents a base factory call from being created by ngtsc, resulting in a
factory function that does not inject the dependencies of the superclass.
Hence, we identify a default synthesized super call in the constructor
body, according to the structure that TypeScript emits.

PR Close #27897
2019-01-09 11:48:10 -08:00
Andrew Kushnir c3aa24c3f9 fix(ivy): sanitization for Host Bindings (#27939)
This commit adds sanitization for `elementProperty` and `elementAttribute` instructions used in `hostBindings` function, similar to what we already have in the `template` function. Main difference is the fact that for some attributes (like "href" and "src") we can't define which SecurityContext they belong to (URL vs RESOURCE_URL) in Compiler, since information in Directive selector may not be enough to calculate it. In order to resolve the problem, Compiler injects slightly different sanitization function which detects proper Security Context at runtime.

PR Close #27939
2019-01-08 17:17:04 -08:00
Alex Rickabaugh 1c39ad38d3 feat(ivy): reference external classes by their exported name (#27743)
Previously, ngtsc would assume that a given directive/pipe being imported
from an external package was importable using the same name by which it
was declared. This isn't always true; sometimes a package will export a
directive under a different name. For example, Angular frequently prefixes
directive names with the 'ɵ' character to indicate that they're part of
the package's private API, and not for public consumption.

This commit introduces the TsReferenceResolver class which, given a
declaration to import and a module name to import it from, can determine
the exported name of the declared class within the module. This allows
ngtsc to pick the correct name by which to import the class instead of
making assumptions about how it was exported.

This resolver is used to select a correct symbol name when creating an
AbsoluteReference.

FW-517 #resolve
FW-536 #resolve

PR Close #27743
2019-01-08 16:36:18 -08:00
Alex Rickabaugh 0b9094ec63 feat(ivy): produce diagnostics for missing exports, incorrect entrypoint (#27743)
This commit adds tracking of modules, directives, and pipes which are made
visible to consumers through NgModules exported from the package entrypoint.
ngtsc will now produce a diagnostic if such classes are not themselves
exported via the entrypoint (as this is a requirement for downstream
consumers to use them with Ivy).

To accomplish this, a graph of references is created and populated via the
ReferencesRegistry. Symbols exported via the package entrypoint are compared
against the graph to determine if any publicly visible symbols are not
properly exported. Diagnostics are produced for each one which also show the
path by which they become visible.

This commit also introduces a diagnostic (instead of a hard compiler crash)
if an entrypoint file cannot be correctly determined.

PR Close #27743
2019-01-08 16:36:18 -08:00
Alex Rickabaugh f4a9f5dae8 refactor(ivy): prep ngtsc and ngcc for upcoming import resolution work (#27743)
Upcoming work to implement import resolution will change the dependencies
of some higher-level classes in ngtsc & ngcc. This necessitates changes in
how these classes are created and the lifecycle of the ts.Program in ngtsc
& ngcc.

To avoid complicating the implementation work with refactoring as a result
of the new dependencies, the refactoring is performed in this commit as a
separate prepatory step.

In ngtsc, the testing harness is modified to allow easier access to some
aspects of the ts.Program.

In ngcc, the main change is that the DecorationAnalyzer is created with the
ts.Program as a constructor parameter. This is not a lifecycle change, as
it was previously created with the ts.TypeChecker which is derived from the
ts.Program anyways. This change requires some reorganization in ngcc to
accommodate, especially in testing harnesses where DecorationAnalyzer is
created manually in a number of specs.

PR Close #27743
2019-01-08 16:36:18 -08:00
Alex Rickabaugh 2a6108af97 refactor(ivy): split apart the 'metadata' package in the ngtsc compiler (#27743)
This refactoring moves code around between a few of the ngtsc subpackages,
with the goal of having a more logical package structure. Additional
interfaces are also introduced where they make sense.

The 'metadata' package formerly contained both the partial evaluator,
the TypeScriptReflectionHost as well as some other reflection functions,
and the Reference interface and various implementations. This package
was split into 3 parts.

The partial evaluator now has its own package 'partial_evaluator', and
exists behind an interface PartialEvaluator instead of a top-level
function. In the future this will be useful for reducing churn as the
partial evaluator becomes more complicated.

The TypeScriptReflectionHost and other miscellaneous functions have moved
into a new 'reflection' package. The former 'host' package which contained
the ReflectionHost interface and associated types was also merged into this
new 'reflection' package.

Finally, the Reference APIs were moved to the 'imports' package, which will
consolidate all import-related logic in ngtsc.

PR Close #27743
2019-01-08 16:36:18 -08:00
Alex Rickabaugh 37b716b298 refactor(ivy): move the flat module index generator to its own package (#27743)
This commit moves the FlatIndexGenerator to its own package, in preparation
to expand its capabilities and support re-exporting of private declarations
from NgModules.

PR Close #27743
2019-01-08 16:36:18 -08:00
Andrew Kushnir 6e7c46af1b fix(ivy): adding event listeners for global objects (window, document, body) (#27772)
This update introduces support for global object (window, document, body) listeners, that can be defined via host listeners on Components and Directives.

PR Close #27772
2019-01-08 10:33:17 -08:00
Paul Gschwendtner 98472da03f build: remove "build.sh" script (#27937)
this script is now obsolete and not needed any more. yay!!!

PR Close #27937
2019-01-07 15:35:09 -08:00
Paul Gschwendtner 7ac8b02ec5 build: remove "test.sh" script (#27937)
test.sh is no longer needed... all the tests should now be executed via bazel.

if for whatever reason we need to run the legacy unit test setup, we should should follow the commands that we use to execute those tests in .circle/config.yaml

PR Close #27937
2019-01-07 15:35:09 -08:00