This commit refactors the process for determining the type of an Angular
attribute to be use a function that takes an attribute name and returns
the Angular attribute kind and name, rather than requiring the user to
query match the attribute name with the regex and query the matching
array.
This refactor prepares for a future change that will improve the
experience of completing attributes in `()`, `[]`, or `[()]` contexts.
PR Close#36301
clang-format was recently updated and any PRs that touch files in the
language service will have to reformat all the files.
Instead of changing the formatting in those PRs, this PR formats all
files in language-service package once and for all.
PR Close#36426
Currently the language service only provides support for determining the
type of array-like members when the array-like object is an `Array`.
However, there are other kinds of array-like objects, including
`ReadonlyArray`s and `readonly`-property arrays. This commit adds
support for retrieving the element type of arbitrary array-like objects.
Closes#36191
PR Close#36312
This commit improves the context of a non-callable function error
message by providing the affected call target and its non-callable type.
PR Close#35271
This commit propagates the `sourceSpan` and `valueSpan` of a `VariableBinding`
in a microsyntax expression to `ParsedVariable`, and subsequently to
View Engine Variable AST and Ivy Variable AST.
Note that this commit does not propagate the `keySpan`, because it involves
significant changes to the template AST.
PR Close#36047
Today, the language service infers the type of variables bound to the
"ngIf" template context member of an NgIf directive, but does not do the
same for the the "$implicit" context member. This commit adds support
for that.
Fixes https://github.com/angular/vscode-ng-language-service/issues/676
PR Close#35941
This commit adds fine-grained text spans to TemplateBinding for microsyntax expressions.
1. Source span
By convention, source span refers to the entire span of the binding,
including its key and value.
2. Key span
Span of the binding key, without any whitespace or keywords like `let`
The value span is captured by the value expression AST.
This is part of a series of PRs to fix source span mapping in microsyntax expression.
For more info, see the doc https://docs.google.com/document/d/1mEVF2pSSMSnOloqOPQTYNiAJO0XQxA1H0BZyESASOrE/edit?usp=sharing
PR Close#35897
This commit adds support in the Angular monorepo and in the Angular
compiler(s) for TypeScript 3.8. All packages can now compile with
TS 3.8.
For most of the repo, only a handful few typings adjustments were needed:
* TS 3.8 has a new `CustomElementConstructor` DOM type, which enforces a
zero-argument constructor. The `NgElementConstructor` type previously
declared a required `injector` argument despite the fact that its
implementation allowed `injector` to be optional. The interface type was
updated to reflect the optionality of the argument.
* Certain error messages were changed, and expectations in tests were
updated as a result.
* tsserver (part of language server) now returns performance information in
responses, so test expectations were changed to only assert on the actual
body content of responses.
For compiler-cli and schematics (which use the TypeScript AST) a major
breaking change was the introduction of the export form:
```typescript
export * as foo from 'bar';
```
This is a `ts.NamespaceExport`, and the `exportClause` of a
`ts.ExportDeclaration` can now take this type as well as `ts.NamedExports`.
This broke a lot of places where `exportClause` was assumed to be
`ts.NamedExports`.
For the most part these breakages were in cases where it is not necessary
to handle the new `ts.NamedExports` anyway. ngtsc's design uses the
`ts.TypeChecker` APIs to understand syntax and so automatically supports the
new form of exports.
The View Engine compiler on the other hand extracts TS structures into
metadata.json files, and that format was not designed for namespaced
exports. As a result it will take a nontrivial amount of work if we want to
support such exports in View Engine. For now, these new exports are not
accounted for in metadata.json, and so using them in "folded" Angular
expressions will result in errors (probably claiming that the referenced
exported namespace doesn't exist).
Care was taken to only use TS APIs which are present in 3.7/3.6, as Angular
needs to remain compatible with these for the time being.
This commit does not update angular.io.
PR Close#35864
This commit accomplishes two tasks:
- Fixes the span of queried pipes to only be applied on pipe names
- By consequence, fixes how pipes are located in arguments (previously,
pipes with arguments could not be found because the span of a pipe
uses a relative span, while the template position is absolute)
The screenshots attached to the PR for this commit demonstrate the
change.
Closes https://github.com/angular/vscode-ng-language-service/issues/677
PR Close#35986
The test libs should only be included in one jasmine_node_test
otherwise `bazel build //packages/language-service/...` would
end up running `feature_test` and `infra_test` twice.
PR Close#35816
This commit performs a modularization of the Language Service's existing
diagnostic messages. Such a modularization has two primary advantages:
- Centralization and decoupling of error messages from the code that
generates them makes it easy to add/delete/edit diagnostic messages,
and allows for independent iteration of diagnostic messages and
diagnostic generation.
- Prepares for additional features like annotating the locations where a
diagnostic is generated and enabling the configuration of which
diagnostics should be reported by the language service.
Although it would be preferable to place the diagnostics registry in an
independent JSON file, for ease of typing diagnostic types as an enum
variant of 'ts.DiagnosticCategory', the registry is stored as an object.
Part of #32663.
PR Close#35678
This commit removes the `NullAstVisitor` and `visitAstChildren` exported
from `packages/compiler/src/expression_parser/ast.ts` because they
contain duplicate and buggy implementation, and their use cases could be
sufficiently covered by `RecursiveAstVisitor` if the latter implements the
`visit` method. This use case is only needed in the language service.
With this change, any visitor that extends `RecursiveAstVisitor` could
just define their own `visit` function and the parent class will behave
correctly.
A bit of historical context:
In language service, we need a way to tranverse the expression AST in a
selective manner based on where the user's cursor is. This means we need a
"filtering" function to decide which node to visit and which node to not
visit. Instead of refactoring `RecursiveAstVisitor` to support this,
`visitAstChildren` was created. `visitAstChildren` duplicates the
implementation of `RecursiveAstVisitor`, but introduced some bugs along
the way. For example, in `visitKeyedWrite`, it visits
```
obj -> key -> obj
```
instead of
```
obj -> key -> value
```
Moreover, because of the following line
```
visitor.visit && visitor.visit(ast, context) || ast.visit(visitor, context);
```
`visitAstChildren` visits every node *twice*.
PR Close#35619
This commit differentiates language service feature and language service
infrastructure tests. This is primarily to make testing of different
components at the development level easier. This commit continues a
small effort to expand our test coverage and normalize testing
structure.
Also adds test coverage to language service tests. We have quite a bit
to go on that front 🙂.
PR Close#35688
This commit normalizes hover and util tests in the language service.
This is part of a small effort to simplify and normalize the language
service testing structure, which currently contains specs that are
largely created and left without relation to other tests.
PR Close#35656
For example, '<div><p string-model~{cursor}></p></div>', when provide the hover info for 'string-model', the 'path.head' is root tag 'div'. Use the parent of 'path.tail' instead.
PR Close#35317
* it's tricky to get out of the runfiles tree with `bazel test` as `BUILD_WORKSPACE_DIRECTORY` is not set but I employed a trick to read the `DO_NOT_BUILD_HERE` file that is one level up from `execroot` and that contains the workspace directory. This is experimental and if `bazel test //:test.debug` fails than `bazel run` is still guaranteed to work as `BUILD_WORKSPACE_DIRECTORY` will be set in that context
* test //integration:bazel_test and //integration:bazel-schematics_test exclusively
* run "exclusive" and "manual" bazel-in-bazel integration tests in their own CI job as they take 8m+ to execute
```
//integration:bazel-schematics_test PASSED in 317.2s
//integration:bazel_test PASSED in 167.8s
```
* Skip all integration tests that are now handled by angular_integration_test except the tests that are tracked for payload size; these are:
- cli-hello-world*
- hello_world__closure
* add & pin @babel deps as newer versions of babel break //packages/localize/src/tools/test:test
@babel/core dep had to be pinned to 7.6.4 or else //packages/localize/src/tools/test:test failed. Also //packages/localize uses @babel/generator, @babel/template, @babel/traverse & @babel/types so these deps were added to package.json as they were not being hoisted anymore from @babel/core transitive.
NB: integration/hello_world__systemjs_umd test must run with systemjs 0.20.0
NB: systemjs must be at 0.18.10 for legacy saucelabs job to pass
NB: With Bazel 2.0, the glob for the files to test `"integration/bazel/**"` is empty if integation/bazel is in .bazelignore. This glob worked under these conditions with 1.1.0. I did not bother testing with 1.2.x as not having integration/bazel in .bazelignore is correct.
PR Close#33927
I think the bug is introduced in my PR#34847. For example, 'model="{{title}}"', the attribute value cannot be parsed by 'parseTemplateBindings'.
PR Close#35494
The completions list don't include the 'ngTemplateOutlet'. The directive is a structural directive when it has injected the 'TemplateRef' or 'ViewContainerRef'.
PR Close#35466
Under strict mode, the language service fails to typecheck nullable
symbols that have already been verified to be non-null.
This generates incorrect (false positive) and confusing diagnostics
for users.
To work around this issue in the short term, this commit changes the
diagnostic message from an error to a suggestion, and prompts users to
use the safe navigation operator (?) or non-null assertion operator (!).
For example, instead of
```typescript
{{ optional && optional.toString() }}
```
the following is cleaner:
```typescript
{{ optional?.toString() }}
{{ optional!.toString() }}
```
Note that with this change, users who legitimately make a typo in their
code will no longer see an error. I think this is acceptable, since
false positive is worse than false negative. However, if users follow
the suggestion, add ? or ! to their code, then the error will be surfaced.
This seems a reasonable trade-off.
References:
1. Safe navigation operator (?)
https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths
2. Non-null assertion operator (!)
https://angular.io/guide/template-syntax#the-non-null-assertion-operator---
PR closes https://github.com/angular/angular/pull/35070
PR closes https://github.com/angular/vscode-ng-language-service/issues/589
PR Close#35200
This commit cleans up `expression_type.ts` by
1. Removing the unnecessary `TypeDiagnostic` class. It's replaced by
`ng.Diagnostic`.
2. Consolidating `reportError()` and `reportWarning()` to
`reportDiagnostic()`.
This is prep work so that we could make some of the type diagnostics a
suggestion in later PRs.
PR Close#35085
The language service reports an error when a directive's template
context is missing a member that is being used in a template (e.g. if
`$implicit` is being used with a template context typed as `any`).
While this diagnostic message is valuable, typing template contexts
loosely as `any` or `object` is very widespread in community packages,
and often still compiles correctly, so reporting the diagnostic as an
error may be misleading to users.
This commit changes the diagnostic to be a warning, and adds additional
information about how the user can eliminate the warning entirely -- by
refining the template context type.
Closes https://github.com/angular/vscode-ng-language-service/issues/572
PR Close#35036
Sometimes, a request for definitions will return multiple of the same
definition. This can happen in at least the cases of
- two-way bindings (one of the same definition for the property and
event binding)
- multiple template binding expressions in the same attribute
- something like "*ngFor="let i of items; trackBy: test" has two
template bindings, resulting in two template binding ASTs at the
same location (the attribute span). The language service then parses
both of these bindings individually, resulting in two independent
but identical definitions. For more context, see https://github.com/angular/angular/pull/34847#discussion_r371006680.
This commit prunes duplicate definitions by signing definitions with
their location, and checking if that location signature has been seen in
a previous definition returned to the client.
PR Close#34995
This commit adds support for completions of properties on `$event`
variables in bound outputs.
This is the second major PR to support completions for `$event`
variables (https://github.com/angular/vscode-ng-language-service/issues/531).
The final completion support that must be provided is for `$event`
variables in bindings targeting DOM events, like `(click)`.
PR Close#34570
This commit makes `findOutputBinding` a utility function for the
language service, which will be used by the `expression_diagnostics`
module in #34570. Keeping the function in `locate_symbol` results in a
circular dependency between `expression_diagnostics` and
`locate_symbol`.
PR Close#34997
For the structural directive, the 'path' will contain multiple `BoundDirectivePropertyAst` which depends on the number of directive property in the attribute value(e.g. '*ngFor="let item of []; trackBy: test;"', it has 2 `BoundDirectivePropertyAst`, 'ngForOf' and 'ngForTrackBy').
PR Close#34847
As part of the effort to tighten the API surface of
`TypeScriptServiceHost` in preparation for the migration to Ivy, I realized
some recently added APIs are not strictly needed.
They can be safely removed without sacrificing functionality.
This allows us to clean up the code, especially in the implementation of
QuickInfo, where the `TypeScriptServiceHost` is leaked outside of the
`LanguageService` class.
This refactoring also cleans up some duplicate code where the QuickInfo
object is generated. The logic is now consolidated into a simple
`createQuickInfo` method shared across two different implementations.
PR Close#34941
Right now, if an Angular diagnostic is generated for a TypeScript node,
the span points to the decorator Identifier, i.e. the Identifier node
like `@NgModule`, `@Component`, etc.
This is weird. It should point to the class name instead.
Note, we do not have a more fine-grained breakdown of the span when
diagnostics are emitted, this work remains to be done.
PR Close#34932
This commit elaborates diagnostics produced for invalid template
contexts by including the name of the embedded template type using the
template context, and in the common case that the implicity property is
being referenced (e.g. in a `for .. of ..` expression), suggesting to
refine the type of the context. This suggestion is provided because
users will sometimes use a base class as the type of the context in the
embedded view, and a more specific context later on (e.g. in an
`ngOnChanges` method).
Closes https://github.com/angular/vscode-ng-language-service/issues/251
PR Close#34751
This commit adds a regression test to check that the language service
recognizes inputs and outputs declared in a directive decorator.
See #34874.
PR Close#34875
In Angular, symbol can have multiple definitions (e.g. a two-way
binding). This commit adds support for for multiple definitions for a
queried location in a template.
PR Close#34782
This commit makes the Angular Language Service interface a strict subset
of TypeScript's Language Service by renaming all methods to be
consistent with TypeScript's.
The custom Angular `LanguageService` interface was needed before the
inception of TypeScript tsserver plugin, but is now obsolete since
Angular LS is a proper tsserver plugin.
This allows us to easily adapt to upstream TS changes in the future, and
also allows us to reuse all data types defined in TypeScript.
PR Close#34888
The Template AST that corresponds to a given HTML AST is not always
complete, and often has to be reconstructed. This commit refactors the
code to make it easier to adapt to multiple cases.
PR Close#34764
Adds a `typeArguments` method to the `Symbol` interface, cleaning up how
type parameters of a TypeScript type are currently found. This will be
necessary for providing completions for `$event` variables' properties
(#34570).
This commit also performs some fly-by cleanups seen while implementing
the `typeArguments` methods. There is more clean up to do in the
`typescript_symbols` file, but the scope of this commit didn't need to
get larger.
PR Close#34571
Currently the language service constructs an `AttrAst` anytime it is
missing from a `TemplateAst` path. However, this should only be done
when the path does not contain an "attribute-like" AST, which can
includes bound properties or bound events.
This commit also refactors `visitAttr` to parse bindings only for
microsyntax expressions and does some other minor cleanup to make
linters happy.
This is some cleanup to help the language service eventually use
`BoundDirectivePropertyAst`s for providing completions for template
bindings rather than performing the manual parsing currently done.
PR Close#34743
This commit removes some test scenarios from `parsing-cases.ts` and
colocate them with the test code instead. This makes the tests easier to
read and understand.
PR Close#34716
This commit renames `addAttributeValuesToCompletions`, which generates
expression completions and is not exclusive to processing attributes, to
`processExpressionCompletions`. Also removes the expression completion
logic in `visitBoundText` for a call to `processExpressionCompletions`.
The conditional branch in `visitBoundText` is also removed. This branch
was added in one of the first commits to the language service
(519a324454) and appears to be
unnecessary, as the expression AST is constructed from the template
position anyway.
PR Close#34518
The compiler's `I18NHtmlParser` may expand template nodes that have
internationalization metadata attached to them; for instance,
```html
<div i18n="@@i18n-el">{{}}</div>
```
gets expanded to an AST with the i18n metadata extracted and text filled
in as necessary; to the language service, the template above, as read in
the AST, now looks something like
```html
<div>{{$implicit}}</div>
```
This is undesirable for the language service because we want to preserve
the original form of the source template source code, and have
information about the original values of the template. The language
service also does not need to use an i18n parser -- we don't generate
any template output.
To fix this turns out to be as easy as moving to using a raw
`HtmlParser`.
---
A note on the testing strategy: as mentioned above, we don't need to use
an i18n parser, but we don't **not** need to use one if the parser
does not heavily modify the template AST. For this reason, the tests
target the functionality of not modifying a template with i18n metadata
rather than testing that the language service does not use an i18n parser.
---
Closes https://github.com/angular/vscode-ng-language-service/issues/272
PR Close#34531
Currently, the language service provides completions in a template node
attribute by first checking if the attribute contains template bindings
to provide completions for, and then providing completions for the
expression in the attribute.
In the latter case, the expression AST was being constructed
"synthetically" inside the language service, in particular declaring the
expression to be a `PropertyRead` with an implicit receiver.
Unfortunately, this AST can be incorrect if the expression is actually a
property read on a component property receiver (e.g. when reading
`key` in the expression `obj.key`, `obj` is the receiver).
The fix is pretty simple - rather than a synthetic construction of the
AST, ask the expression parser to parse the expression in the attribute.
Fixes https://github.com/angular/vscode-ng-language-service/issues/523
PR Close#34517
This commit fixes a bug in which we do testing for completions.
Subsequently, this exposes another bug in our implementation whereby
suggestions are not provided in "ngFor" where there should have been.
Currently, multiple test cases are grouped together in a single
template. This requires the template to be somewhat complete so that
test cases that depend on variables declared earlier would pass.
Consider the following example:
```
template: `
<div *ngFor="let ~{for-person}person of ~{for-people}people">
<span>Name: {{~{for-interp-person}person.~{for-interp-name}name}}</span>
<span>Age: {{person.~{for-interp-age}age}}</span>
</div>`,
```
In order to test `~{for-interp-person}`, `people` has to be included after
`~{for-people}`. This means the test case for `~{for-people}` is not
reflective of the actual use case because the variable is already there!
In real case, the expression would be incomplete, and our implementation
failed to take that into account.
This commit breaks such test into individual tests, and fix the bugs in
the underlying implementation.
PR Close#34473
When a HTML Ast containing an Attribute node is converted to a Template Ast,
the attribute node might get dropped from the Template Ast path.
This is because the AttrNode is not even in the Template Ast to begin with.
In this case, we manually fix the path by converting the Attribute node
to a AttrAst node and appending it to the path.
This allows the `ExpressionVisitor` to properly visit the leaf node in the
TemplateAst path. We no longer need to visit the `Element` and look for
attributes.
PR Close#34459
Given the following HTML and cursor position:
```
<div c|></div>
^ cursor is here
```
Note that the cursor is **after** the attribute `c`.
Under the current implementation, only `Element` is included in the
path. Instead, it should be `Element -> Attribute`.
This bug occurs only for cases where the cursor is right after the Node,
and it is because the `end` position of the span is excluded from the search.
Instead, the `end` position should be included.
PR Close#34440
`let` and `of` should be considered reserved keywords in template syntax
and thus should not be part of the autocomplete suggestions.
For reference, TypeScript does not provide such completions.
This commit removes these results and cleans up the code.
PR Close#34434
Due to a bug in the existing banner, `typescript` module was require-d
instead of reusing the module passed in from tsserver.
This bug is caused by some source files in language-service that imports
`typescript` instead of `typescript/lib/tsserverlibrary`.
This is not an unsupported use case, it's just that when typescript is
resolved in the banner we have to be very careful about which modules to
"require".
The convoluted logic in the banner makes it very hard to detect
anomalies. This commit cleans it up and removes a lot of unneeded code.
This commit also removes `ts` import in typescript_host.ts and use `tss`
instead to make it less confusing.
PR Close#34262
If a Component or Directive is not part of any NgModule, the language
service currently produces an error message. This should not be an
error. Instead, it should be a suggestion.
This PR removes `ng.DiagnosticKind`, and instead reuses
`ts.DiagnosticCategory`.
PR closes https://github.com/angular/vscode-ng-language-service/issues/458
PR Close#34115
The language service incorrectly reports an error if it fails to find
NgModule metadata for a particular Component / Directive. In many cases,
the use case is legit, particularly in test.
This commit removes such diagnostic message and cleans up the interface
for `TypeScriptHost.getTemplateAst()`.
PR closes https://github.com/angular/vscode-ng-language-service/issues/463
PR Close#34113
Currently, variables of an unknown type in an `*ngFor` expression are
refined to have the type of the iterable binding of the `*ngFor`
expression. Unfortunately, this is a bug for variables aliasing
[values exported by
`*ngFor`](https://angular.io/api/common/NgForOf#local-variables),
including `index` and `first`, because they are also given the type of
the binding expression, but they are not of the binding type. For
example, in
```typescript
@Component({
selector: 'test',
template: `
<div *ngFor="let hero of heroes; let i = index; let isFirst = first">
{{ hero }}
</div>
`
})
export class TestComponent {
heroes: Hero[];
}
```
The local variables `i` and `isFirst` are determined to have a type of
`Hero`, when actually their types are `number` and `boolean`,
respectively.
This commit fixes this bug by checking if the value of a variable in an
`*ngFor` expression is known to be an export and assigning the variable
the type of that export value. Only if the variable does not alias an
export is it typed with the binding value of the `*ngFor` expression.
Closes https://github.com/angular/vscode-ng-language-service/issues/460
PR Close#34089
Commit 53fc2ed8bf added support for
determining index types accessed using index signatures, but did not
include support for index types accessed using dot notation:
```typescript
const obj<T>: { [key: string]: T };
obj['stringKey']. // gets `T.` completions
obj.stringKey. // did not peviously get `T.` completions
```
This adds support for determining an index type accessed via dot
notation by rigging an object's symbol table to return the string index
signature type a property access refers to, if that property does not
explicitly exist on the object. This is very similar to @ivanwonder's
work in #29811.
`SymbolWrapper` now takes an additional parameter to explicitly set the
type of the symbol wrapped. This is done because
`SymbolTableWrapper#get` only has access to the symbol of the index
type, _not_ the index signature symbol itself. An attempt to get the
type of the index type will give an error.
Closes#29811
Closes https://github.com/angular/vscode-ng-language-service/issues/126
PR Close#33884
When performing diagnostic checks or completions, we should take into
account members and properties in the base class, if any. Otherwise, the
language service will produce a false error.
PR closes https://github.com/angular/vscode-ng-language-service/issues/93
PR Close#34041
Previously, indexing a container type would not return completions for
the indexed type because for every TypeScript type, the recorded index
type was always marked as `undefined`, regardless of the index
signature.
This PR now returns the index type of TypeScript containers with numeric
or string index signatures. This allows use to generate completions for
arrays and defined index types:
```typescript
interface Container<T> {
[key: string]: T;
}
const ctr: Container<T>;
ctr['stringKey']. // gives `T.` completions
const arr: T[];
arr[0]. // gives `T.` completions
```
Note that this does _not_ provide completions for properties indexed by
string literals, e.g.
```typescript
interface Container<T> {
foo: T;
}
const ctr: Container<T>;
ctr['foo']. // does not give `T.` completions
```
Closes angular/vscode-ng-language-service#110
Closes angular/vscode-ng-language-service#277
PR Close#33775
This commit fixes a bug whereby completions for attribute values are only
provided for directives that support the micro-syntax format, all other
bindings are ignored.
I'm not sure if this is a regresssion or a bug, because there were no
tests prior to this.
PR Close#33839
This commit fixes a few issues with helper method
`getBuiltInTypeFromTsType`.
1. The function is wrongly named. It should be the other way round.
2. The ts.Type returned by the function should not contain any value.
This is because for some data types like Number and String, the
SourceFile (context.node) is not the correct value. Value is never
needed for program correctness in this case.
PR Close#33778
This commit fixes a bug brought up by @andrius-pra whereby the language
service host would recompute the analyzed modules even when none of the
source files changes. This is due to a bug in our unit test that
precludes non-TS files from incrementing the project version.
Consequently, when the external template is updated, the program remains
the same.
With the bug fixed, the next step is to figure out if any source files
have been added / changed / removed since the last computation. The
previously analyzed could be safely retained only when none of these
operations happen.
PR Close#33806
The method `getTemplateReferences()` appears in both the LanguageService
interface and LanguageServiceHost interface. It should belong in the
latter and not the former, since the former deals with the semantics of
the language and not the mechanics.
PR Close#33807
The following files are consumed only by the language service and do not
have to be in compiler-cli:
1. expression_diagnostics.ts
2. expression_type.ts
3. typescript_symbols.ts
4. symbols.ts
PR Close#33809
The legacy nodejs rules rollup_bundle is now deprecated and will be removed in the nodejs rules 1.0 release due in mid-November. This PR brings in the rules_nodejs internal API deps that ng_rollup_bundle, ng_package and ls_rollup_bundle depend on into this repo to break the dependency. In the future these rules should switch to use the new rollup_bundle via a macro as done in https://github.com/angular/angular/pull/33329 but this is not possible right now due to the complication of having esm5 re-rooted ts_library dependencies.
The es6 sources now have .mjs extensions so they no longer need to be re-rooted to `{package}.es6`. This eliminates the need for the collect_es6_sources() function.
Note: repo has been updated to the newest working version of rollup which is 1.25.2. There is some regression in 1.26.0 which causes the following bundling failure:
```
ERROR: /Users/greg/google/angular/packages/localize/BUILD.bazel:20:1: Optimizing JavaScript packages/localize/localize.umd.min.js [terser] failed (Exit 1) terser.sh failed: error executing command bazel-out/host/bin/external/npm/terser/bin/terser.sh bazel-out/darwin-fastbuild/bin/packages/localize/localize.umd.js --output bazel-out/darwin-fastbuild/bin/packages/localize/localize.umd.min.js ... (remaining 5 argument(s) skipped)
Use --sandbox_debug to see verbose messages from the sandbox
Parse error at packages/localize/localize.umd.js:491,4
export * from './src/constants';
^
ERROR: Export statement may only appear at top level
at js_error (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/parse.js:357:11)
at Dn.visit (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/scope.js:347:13)
at Dn._visit (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:1207:24)
at AST_Export._walk (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:718:17)
at walk_body (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:168:17)
at AST_Function.call (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:430:13)
at descend (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:1208:21)
at Dn.visit (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/scope.js:256:13)
at Dn._visit (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:1207:24)
at AST_Function._walk (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:424:24)
[Function]
Target //packages/localize:npm_package failed to build
Use --verbose_failures to see the command lines of failed build steps.
ERROR: /Users/greg/google/angular/packages/localize/BUILD.bazel:20:1 Optimizing JavaScript packages/localize/localize.umd.min.js [terser] failed (Exit 1) terser.sh failed: error executing command bazel-out/host/bin/external/npm/terser/bin/terser.sh bazel-out/darwin-fastbuild/bin/packages/localize/localize.umd.js --output bazel-out/darwin-fastbuild/bin/packages/localize/localize.umd.min.js ... (remaining 5 argument(s) skipped)
```
Will leave that for another day.
Terser also updated to 4.3.3. Updating to 4.3.4 (https://github.com/terser/terser/blob/master/CHANGELOG.md) turns comments preservation on by default which increases the size of the //packages/core/test/bundling/todo:bundle.min.js in CI. After bazelbuild/rules_nodejs#1317 terser can be updated to the latest as passing —comments /a^/ to args can turn off all comments for the //packages/core/test/bundling/todo:bundle.min.js size test.
PR Close#33201
PR Close#33607
The legacy nodejs rules rollup_bundle is now deprecated and will be removed in the nodejs rules 1.0 release due in mid-November. This PR brings in the rules_nodejs internal API deps that ng_rollup_bundle, ng_package and ls_rollup_bundle depend on into this repo to break the dependency. In the future these rules should switch to use the new rollup_bundle via a macro as done in https://github.com/angular/angular/pull/33329 but this is not possible right now due to the complication of having esm5 re-rooted ts_library dependencies.
The es6 sources now have .mjs extensions so they no longer need to be re-rooted to `{package}.es6`. This eliminates the need for the collect_es6_sources() function.
Note: repo has been updated to the newest working version of rollup which is 1.25.2. There is some regression in 1.26.0 which causes the following bundling failure:
```
ERROR: /Users/greg/google/angular/packages/localize/BUILD.bazel:20:1: Optimizing JavaScript packages/localize/localize.umd.min.js [terser] failed (Exit 1) terser.sh failed: error executing command bazel-out/host/bin/external/npm/terser/bin/terser.sh bazel-out/darwin-fastbuild/bin/packages/localize/localize.umd.js --output bazel-out/darwin-fastbuild/bin/packages/localize/localize.umd.min.js ... (remaining 5 argument(s) skipped)
Use --sandbox_debug to see verbose messages from the sandbox
Parse error at packages/localize/localize.umd.js:491,4
export * from './src/constants';
^
ERROR: Export statement may only appear at top level
at js_error (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/parse.js:357:11)
at Dn.visit (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/scope.js:347:13)
at Dn._visit (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:1207:24)
at AST_Export._walk (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:718:17)
at walk_body (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:168:17)
at AST_Function.call (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:430:13)
at descend (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:1208:21)
at Dn.visit (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/scope.js:256:13)
at Dn._visit (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:1207:24)
at AST_Function._walk (/private/var/tmp/_bazel_greg/5e8f8a9cd1c6fbc1afd11e37ee1fe2e5/sandbox/darwin-sandbox/79/execroot/angular/bazel-out/host/bin/external/npm/terser/bin/terser.sh.runfiles/npm/node_modules/terser/lib/ast.js:424:24)
[Function]
Target //packages/localize:npm_package failed to build
Use --verbose_failures to see the command lines of failed build steps.
ERROR: /Users/greg/google/angular/packages/localize/BUILD.bazel:20:1 Optimizing JavaScript packages/localize/localize.umd.min.js [terser] failed (Exit 1) terser.sh failed: error executing command bazel-out/host/bin/external/npm/terser/bin/terser.sh bazel-out/darwin-fastbuild/bin/packages/localize/localize.umd.js --output bazel-out/darwin-fastbuild/bin/packages/localize/localize.umd.min.js ... (remaining 5 argument(s) skipped)
```
Will leave that for another day.
Terser also updated to 4.3.3. Updating to 4.3.4 (https://github.com/terser/terser/blob/master/CHANGELOG.md) turns comments preservation on by default which increases the size of the //packages/core/test/bundling/todo:bundle.min.js in CI. After bazelbuild/rules_nodejs#1317 terser can be updated to the latest as passing —comments /a^/ to args can turn off all comments for the //packages/core/test/bundling/todo:bundle.min.js size test.
PR Close#33201
Adds a `replacementSpan` field on a completion that will allow typed
text to be replaced with the suggested completion value if a user
selects the completion. Previously, the completion value would simply be
appended to the text already typed. E.g. if we had
```
{{ti}}
```
typed in a template and `title` was recommended as a completion and
selected, the template would become
```
{{tititle}}
```
With `replacementSpan`, the original text `ti` will be replaced for
`title`.
PR Close#33091
This commit simplifies the logic of `ExpressionVisitor` in
`completions.ts`.
Specifically,
1. helper functions `uniqueByName` and `lowerName` are removed.
2. Clean up the logic in visitElement()
3. Reorder constructor params
4. Add methods `addAttributeValuesToCompletions`,
`addKeysToCompletions`, and `addSymbolsToCompletions`.
PR Close#33391
This commit removes HTML elements and HTML attributes from the
completions list for external template. This is because these
completions should be handled by the native HTML extension, and not
Angular.
Once we setup TextMate grammar for inline templates, we could remove the
HTML completions completely.
PR closes https://github.com/angular/vscode-ng-language-service/issues/370
PR Close#33388
Moves to using the absolute span of an expression AST (relative to an
entire template) rather than a relative span (relative to the start
of the expression) to find an expression AST given a position in a
template.
This is part of the changes needed to support text replacement in
templates (#33091).
PR Close#33387
It is messy to keep casting `CompletionEntry.kind` from
`ng.CompletionKind` to `ts.ScriptElementKind`.
Instead, create a new type `ng.CompletionEntry` that is exactly the same
as `ts.CompletionEntry`, but with the `kind` type overridden to
`ng.CompletionKind`.
This way, we only have to cast it once, and can do so in a safe manner.
PR Close#33379
This is a potential fix for https://github.com/angular/vscode-ng-language-service/issues/235
suggested by @andrius-pra in
47696136e3.
Currently, CRLF line endings are converted to LFs and this causes the
diagnostics span to be off in templates that use CRLF. The line endings
must be preserved in order to maintain correct span offset. The solution
is to add an option to the Tokenizer to indicate such preservation.
PR Close#33241
This commit speeds up the tests by calling `MockHost.reset()` in
`beforeEach()` instead of destroying the entire language service and
creating a new one. The creation of a new language service instance is
expensive due to the need to initialize many core Symbols when creating
a new program.
This speeds ups the test (on my local machine) from 35 secs to 15 secs.
PR Close#33200
There are many specs in `ts_plugin_spec.ts` that exercise the behavior
of completions. These specs should belong in `completions_spec` instead.
In addition,
1. Tests for `getExternalFiles()` added in `ts_plugin_spec.ts`
2. Fixed bug in MockHost.reset() to remove overriden script names
3. Add test for TS diagnostics when `angularOnly = true` is not set
PR Close#33159
Now, hovering over an attribute on an element will provide information
about the directive that attribute matches in the element, if any.
(More generally, we return information about directive symbols
matched on an element attribute.)
I believe this is similar to how the indexer provides this kind of
information, though more precise in the sense that this commit provides
directive information only if the directive selector exactly matches the
attribute selector. In another sense, this is a limitation.
In fact, there are the limitations of:
- Directives matched on the element, but with a selector of anything
more than the attribute (e.g. `div[string-model]` or
`[string-model][other-attr]`) will not be returned as symbols matching
on the attribute.
- Only one symbol can be returned currently. If the attribute matches
multiple directives, only one directive symbol will be returned.
Furthermore, we cannot say that the directive symbol returned is
determinstic.
Resolution of these limitations can be discussed in the future. At least
the second limitation should be very easy to fixup in a future commit.
This relies solely on the template compiler and is agnostic to any Ivy
changes, so this is strictly a feature enhancement that will not have to
be refactored when we migrate the language service to Ivy.
PR Close#33127
This PR adds es2015 lib to the `tsconfig.json` of the test project so
that `Promise` could be used. Note this only affects diagnostics in the
IDE. The tsconfig in Language Service Mock Host is the actual config
values used, and it already has es2015 lib.
- Other minor cleanup: Rename imports in `main.ts`.
- Add more cases to `parsing-cases.ts`, which are tested in later PRs
PR Close#33157
Enables providing information about the NgModule a component is in when
its selector is hovered on in a template. Also enables differentiation
of a component and a directive when a directive class name is hovered
over in a TypeScript file.
Next step is to enable hover information for directives.
Part of #32565.
PR Close#33118
Currently, method `getVarDeclarations()` does not try to resolve the type of
exported variable from *ngIf directive. It always returns `any` type.
By resolving the real type of exported variable, it is now possible to use this
type information in language service and provide completions, go to definition
and quick info functionality in expressions that use exported variable.
Also language service will provide more accurate diagnostic errors during
development.
PR Close#33016
Currently, the spans of expressions are recorded only relative to the
template node that they reside in, not their source file.
Introduce a `sourceSpan` property on expression ASTs that records the
location of an expression relative to the entire source code file that
it is in. This may allow for reducing duplication of effort in
ngtsc/typecheck/src/diagnostics later on as well.
Child of #31898
PR Close#31897
A few specs in `completions_spec.ts` are non-deterministic and do not provide much value to test a specific behavior of language service.
Besides that, they are also slow to run.
PR Close#33120
Remove the following methods from MockHost:
1. `getMarkerLocations`: Replaced with `getLocationMarkerFor()`
2. `getReferenceMarkers`: Replaced with `getReferenceMarkerFor()`
PR Close#33115
The current `typings` value in `package.json` causes the import of
`@angular/language-service` in TypeScript to be generated as
```
const language_service_1 = require("@angular/language-service/language-service");
```
in CJS output.
This breaks the import shim that overwrites the behavior of `require` at
runtime. Changing the typings to `index.d.ts` fixes the issue.
PR Close#33043
The creation of StaticReflector in createMetadataResolver() is a very expensive operation because it involves numerous module resolutions.
To make matter worse, since the API of the Reflector does not provide the ability to invalidate its internal caches, it has to be destroyed and recreated on *every* program change.
This has a HUGE impact on performance.
This PR fixes this problem by carefully invalidating all StaticSymbols in a file that has changed, thereby reducing the overhead of recomputation on program change.
PR Close#32543
Adds information about the NgModule a Directive is declared in when the
Directive class name is hovered over, in the form
```
(directive) NgModule.Directive: class
```
Closes#32565
PR Close#32763
Sometimes modules retreived from the language service need to be
synchronized to the last time they were updated, and not updated
on-the-fly. This PR adds a flag to
`TypeScriptServiceHost#getAnalyzedModules` that retreives cached
analyzed NgModules rather than potentially recomputing them.
PR Close#32779
This is the last part in refactoring of the test project.
This PR turns on strict mode for typechecking and fixed tests that
fail under this mode.
PR Close#32783
readFileContent() has the exact same functionality as readFile(), but it
is not actually part of ts.LanguageServiceHost interface.
It's not actually needed, so replace it with readFile() instead.
PR Close#32782
Remove MockData from the constructor parameters of MockTypescriptHost
since the entire Tour of Heroes (TOH) project is now loaded from disk.
Added a new method `reset()` to MockTypescriptHost that is necessary to
reset the state of the project before each spec if run to make sure
previous overrides are cleared.
PR Close#32752
Language service uses a canonical "Tour of Heroes" project to test
various features, but the files are all contained in test_data.ts which
is hard to read and often contains errors that are difficult to catch
without proper IDE syntax highlighting. The directory structure is also
not clear from first glance.
This PR refactors the test project into standalone files in the proper
format.
Next up:
[ ] Update the interface of MockTypeScript to only accept scriptNames.
[ ] Remove test_data.ts
PR Close#32653
This sets up the Language Service to support #32565.
This PR exposes a `getDirectiveModule` method on `TypeScriptServiceHost`
that returns the NgModule owning a Directive given the Directive's
TypeScript node or its Angular `StaticSymbol`. Both types are supported
to reduce extraneous helper methods.
PR Close#32710