Rather than mutating the span on the template when renaming literal strings,
this commit updates the logic to mutate the `TextSpan` equivalent that
is used by the Language Service.
PR Close#40484
Many `ts.LanguageService` APIs accept a filename, for example
```ts
getQuickInfoAtPosition(fileName: string, position: number)
```
The requirement is that `fileName` is agnostic to the platform (Linux, Mac,
Windows, etc), and is always normalized to TypeScript's internal
`NormalizedPath`.
This is evident from the way these APIs are called from the language server:
```ts
private onHover(params: lsp.TextDocumentPositionParams) {
const lsInfo = this.getLSAndScriptInfo(params.textDocument);
if (lsInfo === undefined) {
return;
}
const {languageService, scriptInfo} = lsInfo;
const offset = lspPositionToTsPosition(scriptInfo, params.position);
const info = languageService.getQuickInfoAtPosition(scriptInfo.fileName, offset);
// ...
}
```
9fca9c6651/server/src/session.ts (L594)
Here `scriptInfo.fileName` is always a `ts.server.NormalizedPath`.
However, https://github.com/angular/angular/pull/39917 accidentally leaked
the platform-specific paths, and caused a mismatch between the incoming paths
and the paths stored in the internal data structure `fileToComponent`.
This PR fixes the bug by always normalizing the paths, and updating the
type to reflect the format of the underlying data.
Fixes https://github.com/angular/vscode-ng-language-service/issues/1063
PR Close#40492
The initial implementation assumed that the consuming editors would
de-duplicate rename locations. In fact, vscode treats overlapping rename
locations as distinct and errors when trying to preview the renames.
This commit updates the language service to de-duplicate exact file+span
matches before returning rename and reference locations.
While vscode _does_ de-duplicate reference results, it still makes sense
to de-duplicate them on our side when possible to make tests more
understandable. If a template has 3 instances of a variable, it makes
sense to get get 3 reference results rather than 4+ with some duplicates.
PR Close#40454
The current "go to definition" is broken for template variables and
references when a template is overridden. This is because we get the
file url from the source span, which uses the overridden name
'override.html'. Instead, we can retrieve the template file from the
compiler in the same manner that is done for references.
Another way to fix this would have been to use the real template file path when
overriding a template, but this was the more straightforward fix since
the strategy was already used in find references and rename locations.
fixes https://github.com/angular/vscode-ng-language-service/issues/1054
PR Close#40455
The `getRenameInfo` action is used by consumers to
1. Determine if a location is a candidate for renames
2. Determine what text to use as the starting point for the rename
PR Close#40439
This commit lays the groundwork for potentially providing rename
locations from the Ivy native LS. The approach is very similar to what
was done with the feature to find references. One difference, however,
is that we did not require the references to be fully "correct". That
is, the exact text spans did not matter so much, as long as we provide a
location that logically includes the referenced item.
An example of a necessary difference between rename locations and references is
directives. The entire element in the template is a "reference" of the
directive's class. However, it's not a valid location to be renamed. The
same goes for aliased inputs/outputs. The locations in the template
directly map to the class property, which is correct for references, but
would not be correct for rename locations, which should instead map to
the string node fo the alias.
As an initial approach to address the aforementioned issues with rename
locations, we check that all the rename location nodes have the same text. If
_any_ node has text that differs from the request, we do not return any
rename locations. This works as a way to prevent renames that could
break the the program by missing some required nodes in the rename action, but
allowing other nodes to be renamed.
PR Close#40140
Report non-template diagnotics when calling `getDiagnotics` function of
the language service we only returned template diagnotics. This change
causes it to return all diagnotics, not just diagnostics from the
template type checker.
PR Close#40331
This commit fixes a bug in the **View Engine** implementation of
`getSemanticDiagnostics` and `getDefinitionAndBoundSpan` for node in the
decorator metadata that represents an external URL
(`templateUrl` or `styleUrls`).
The URL could be either relative or absolute, but the latter was not taken
into account.
Fix https://github.com/angular/vscode-ng-language-service/issues/1055
PR Close#40406
The parser has a list of tag definitions that it uses when parsing the template. Each tag has a
`contentType` which tells the parser what kind of content the tag should contain. The problem is
that the browser has two separate `title` tags (`HTMLTitleElement` and `SVGTitleElement`) and each
of them has to have a different `contentType`, otherwise the parser will throw an error further down
the pipeline.
These changes update the tag definitions so that each tag name can have multiple content types
associated with it and the correct one can be returned based on the element's prefix.
Fixes#31503.
PR Close#40259
Currently the language service has to force `compileNonExportedClasses` to
`true` to handle inline NgModules in tests, regardless of the value in user's
tsconfig.json.
However, the override is not reinstated after the compiler option changes
(triggered by a change in tsconfig.json).
This commit fixes the bug.
PR Close#40364
This commit adds special handling to the completion builder by detecting
a two way binding context and ensuring that we filter out any `Input`s
that do not support two way binding.
PR Close#40185
Rather than expecting that a position in a template only targets a
single node, this commit simply adjusts the approach to account for two way
bindings. Specifically, we attempt to get references for each targeted
node and then return the combination of all results, or `undefined` if
none of the target nodes had references.
PR Close#40185
Rather than expecting that a position in a template only targets a
single node, this commit adjusts the approach to account for two way
bindings. In particular, we attempt to get definitions for each targeted
node and then return the combination of all results, or `undefined` if
none of the target nodes had definitions.
PR Close#40185
Adjust the visitor logic of the template target as well as the
consumption of the visitor result to account for two-way bindings.
This sets up downstream consumers for being able to handle the
possibility of a template position that targets both an input and an
output.
PR Close#40185
The current template target implementation only allows a way to
represent the template position as targeting a single node in the
template AST. However, there is at least one case (banana-in-a-box)
where a given template position refers to two template targets.
This commit expands the contexts that the `TemplateTarget` can return to
include support for the banana-in-a-box syntax, which has two logically
targetted AST nodes given a position within the `keySpan` of the
binding.
PR Close#40185
This commit ensures that the template type checker returns symbols for
all outputs if a template output listener binds to more than one.
PR Close#40144
We need a means to preserve typecheck files when a project is reloaded,
otherwise the Ivy compiler will throw an error when it's unable to find
them. This commit implements `getExternalFiles()` called by the langauge
server to achieve this goal.
For more info see https://github.com/angular/vscode-ng-language-service/issues/1030
PR Close#40162
`ts.server.ServerHost.resolvePath()` is different from Angular's
`FileSystem.resolve()` because the signature of the former is
```ts
resolvePath(path: string): string; // ts.server.ServerHost
```
whereas the signature of the latter is
```ts
resolve(...paths: string[]): AbsoluteFsPath; // FileSystem on compiler-cli
```
The current implementation calls `path.join()` to concatenate all the input
paths and pass the result to `ts.server.ServerHost.resolvePath()`, but doing
so results in filenames like
```
/foo/bar/baz/foo/bar/baz/tsconfig.json
```
if both input paths are absolute.
`ts.server.ServerHost` should not be used to implement the
`resolve()` method expected by Angular's `FileSystem`.
We should use Node's `path.resolve()` instead, which will correctly collapse
the absolute paths.
Fix https://github.com/angular/vscode-ng-language-service/issues/1035
PR Close#40242
When resolving references, the Ivy compiler has a few strategies it could use.
For relative path, one of strategies is [`RelativePathStrategy`](
https://github.com/angular/angular/blob/master/packages/compiler-cli/src/
ngtsc/imports/README.md#relativepathstrategy). This strategy
relies on `compilerOptions.rootDir` and `compilerOptions.rootDirs` to perform
the resolution, but language service only passes `rootDirs` to the compiler,
and not `rootDir`.
In reality, `rootDir` is very different from `rootDirs` even though they
sound the same.
According to the official [TS documentation][1],
> `rootDir` specifies the root directory of input files. Only use to control
> the output directory structure with --outDir.
> `rootDirs` is a list of root folders whose combined content represent the
> structure of the project at runtime. See [Module Resolution documentation](
> https://www.typescriptlang.org/docs/handbook/
> module-resolution.html#virtual-directories-with-rootdirs)
> for more details.
For now, we keep the behavior between compiler and language service consistent,
but we will revisit the notion of `rootDir` and how it is used later.
Fixangular/vscode-ng-language-service#1039
[1]: https://www.typescriptlang.org/docs/handbook/compiler-options.html
PR Close#40243
Given the template
`<div (click)="doSomething($event)"></div>`
If you request references for the `$event`, the results include both `$event` and `(click)="doSomething($event)"`.
This happens because in the TCB, `$event` is passed to the `subscribe`/`addEventListener`
function as an argument. So when we ask typescript to give us the references, we
get the result from the usage in the subscribe body as well as the one passed in as an argument.
This commit adds an identifier to the `$event` parameter in the TCB so
that the result returned from `getReferencesAtPosition` can be
identified and filtered out.
fixes#40157
PR Close#40158
This commit fixes an issue in the ivy native language service
that caused the logic that finds a target node given a template
position to throw away the results. This happened because the
source span of a variable node in the shorthand structural
directive syntax (i.e. `*ngIf=`) included the entire binding.
The result was that we would add the variable node to the path and then
later detect that the cursor was outside the key and value spans and
throw away the whole result. In general, we do this because we do not
want to show information when the cursor is between a key/value
(`inputA=¦"123"`). However, when using the shorthand syntax, we run into
the situation where we can match an `AttributeBinding` as well as the
vaariable in `*ngIf="som¦eValue as myLocalVar"`. This commit updates the
visitor to retain enough information in the visit path to throw away
invalid targets but keep valid ones if there were multiple results on a
`t.Element` or `t.Template`.
PR Close#40239
Durring analysis we find template parse errors. This commit changes
where the type checking context stores the parse errors. Previously, we
stored them on the AnalysisOutput this commit changes the errors to be
stored on the TemplateData (which is a property on the shim). That way,
the template parse errors can be grouped by template.
Previously, if a template had a parse error, we poisoned the module and
would not procede to find typecheck errors. This change does not poison
modules whose template have typecheck errors, so that ngtsc can emit
typecheck errors for templates with parse errors.
Additionally, all template diagnostics are produced in the same place.
This allows requesting just the template template diagnostics or just
other types of errors.
PR Close#40026
This comit adds support for autocompletion of attributes that create
structural directives. Such completions differ from those of normal
attributes, as the structural directive syntax creates a synthetic
<ng-template> node which has different attributes from the main element.
PR Close#40032
This commit adds attribute completion to the Language Service. It completes
from 3 sources:
1. inputs/outputs of directives currently present on the element
2. inputs/outputs/attributes of directives in scope for the element, that
would become present if the input/output/attribute was added
3. DOM properties and attributes
We distinguish between completion of a property binding (`[foo|]`) and a
completion in an attribute context (`foo|`). For the latter, bindings to
the attribute are offered, as well as a property binding which adds the
square bracket notation.
To determine hypothetical matches (directives which would become present if
a binding is added), directives in scope are scanned and matched against a
hypothetical version of the element which has the attribute.
PR Close#40032
This commit expands the autocompletion capabilities of the language service
to include element tag names. It presents both DOM elements from the Angular
DOM schema as well as any components (or directives with element selectors)
that are in scope within the template as options for completion.
PR Close#40032
This commit extends the template targeting system, which determines the node
being referenced given a template position, to return additional context if
needed about the particular aspect of the node to which the position refers.
For example, a position pointing to an element node may be pointing either
to its tag name or to somewhere in the node body. This is the difference
between `<div|>` and `<div foo | bar>`.
PR Close#40032
The vim editor produces temporarily files that can end in both .swo and
.swp. This commits add .swp to the .gitignore so we don't accidentaly
commit temporary files.
PR Close#40094
Projects opened in the LS are often larger in scope than the compilation
units seen by the compiler when actually building. For example, in the LS
it's not uncommon for the project to include both application as well as
test files. This can create issues when the combination of files results
in errors that are not otherwise present - for example, if test files
have inline NgModules that re-declare components (a common Angular pattern).
Such code is valid when compiling the app only (test files are excluded, so
only one declaration is seen by the compiler) or when compiling tests only
(since tests run in JIT mode and are not seen by the AOT compiler), but when
both sets of files are mixed into a single compilation unit, the compiler
sees the double declaration as an error.
This commit attempts to mitigate the problem by forcing the compiler flag
`compileNonExportedClasses` to `false` in a LS context. When tests contain
duplicate declarations, often such declarations are inline in specs and not
exported from the top level, so this flag can be used to greatly improve the
IDE experience.
PR Close#40092
When `checkTypeOfPipes` is set to `false`, the configuration is meant to
ignore the signature of the pipe's `transform` method for diagnostics.
However, we still should produce some information about the pipe for the
`TemplateTypeChecker`. This change refactors the returned symbol for
pipes so that it also includes information about the pipe's class
instance as it appears in the TCB.
PR Close#39555
The TCB utility functions used to find nodes in the TCB are currently
configured to ignore results when an ignore marker is found. However,
these ignore markers are only meant to affect diagnostics requests. The
Language Service may have a need to find nodes with diagnostic ignore
markers. The most common example of this would be finding references for
generic directives. The reference appears to the generic directive's
class appears on the type ctor in the TCB, which is ignored for
diagnostic purposes.
These functions should only skip results when the request is in the
context of a larger request for _diagnostics_. In all other cases, we
should get matches, even if a diagnostic ignore marker is encountered.
PR Close#40071
This commit adds the ability to find references for a directive or component
from within a component template. That is, you can find component references
from the element tag `<my-c|omp></my-comp>` (where `|` is the cursor position)
as well as find references for directives that match a given attribute
`<div d|ir></div>`.
PR Close#40054
If we've already identified that we are within a `keySpan` of a node, we
exit the visitor logic early. It can be the case that we have two nodes
which technically match a given location when the end span of one node
touches the start of the keySpan for the candidate node. Because
our `isWithin` logic is inclusive on both ends, we can match both nodes.
This change exits the visitor logic once we've identified a node where
the position is within its `keySpan`.
PR Close#40047
The visitor has a check in it with the goal of preventing the structural directive
parent elements from matching when we have already found the candidate we want.
However, this code did not check to ensure that it was looking at the correct
type of node for this case and was evaluating this logic in places it shouldn't.
This special check can be more easily done by simply not traversing the
template children if we've already found a candidate on the template
node itself.
PR Close#40047
This commit adds support to the Language Service for autocompletion within
expression contexts. Specifically, this is auto completion of property reads
and method calls, both in normal and safe-navigational forms.
PR Close#39727
When `checkTypeOfOutputEvents` is `false`, we still need to produce the access
to the `EventEmitter` so the Language Service can still get the
type information about the field. That is, in a template `<div
(output)="handle($event)"`, we still want to be able to grab information
when the cursor is inside the "output" parens. The flag is intended only
to affect whether the compiler produces diagnostics for the inferred
type of the `$event`.
PR Close#39515
Rather than returning `null`, we can provide some useful information to the Language Service
by returning a symbol for the `addEventListener` function call when the consumer
of a binding as an element.
PR Close#39312
When the compiler option `checkTypeOfAttributes` is `false`, we should
still be able to produce type information from the
`TemplateTypeChecker`. The current behavior ignores all attributes that
map to directive inputs. This commit includes those attribute bindings
in the TCB but adds the "ignore for diagnostics" marker so they do not
produce errors. This way, consumers of the TTC (the Language Service)
can still get valid information about these attributes even when the
user has configured the compiler to not produce diagnostics/errors for them.
PR Close#39537
This commit adds support in the Ivy Language Service for autocompletion in a
global context - e.g. a {{foo|}} completion.
Support is added both for the primary function `getCompletionsAtPosition` as
well as the detail functions `getCompletionEntryDetails` and
`getCompletionEntrySymbol`. These latter operations are not used yet as an
upstream change to the extension is required to advertise and support this
capability.
PR Close#39250
In the past, the legacy (VE-based) language service would use a
`UrlResolver` instance to resolve file paths, primarily for compiler
resources like external templates. The problem with this is that the
UrlResolver is designed to resolve URLs in general, and so for a path
like `/a/b/#c`, `#c` is treated as hash/fragment rather than as part
of the path, which can lead to unexpected path resolution (f.x.,
`resolve('a/b/#c/d.ts', './d.html')` would produce `'a/b/d.html'` rather
than the expected `'a/b/#c/d.html'`).
This commit resolves the issue by using Node's `path` module to resolve
file paths directly, which aligns more with how resources are resolved
in the Ivy compiler.
The testing story here is not great, and the API for validating a file
path could be a little bit prettier/robust. However, since the VE-based
language service is going into more of a "maintenance mode" now that
there is a clear path for the Ivy-based LS moving forward, I think it is
okay not to spend too much time here.
Closes https://github.com/angular/vscode-ng-language-service/issues/892
Closes https://github.com/angular/vscode-ng-language-service/issues/1001
PR Close#39917
Create stubs for `findRenameLocations` for both VE and Ivy Language Service
implementations. This will prevent failed requests when it is implemented on the vscode plugin side.
PR Close#39919
When the compiler is invoked via ngc or the Angular CLI, its APIs are used
under the assumption that Angular analysis/diagnostics are only requested if
the program has no TypeScript-level errors. A result of this assumption is
that the incremental engine has not needed to resolve changes via its
dependency graph when the program contained broken imports, since broken
imports are a TypeScript error.
The Angular Language Service for Ivy is using the compiler as a backend, and
exercising its incremental compilation APIs without enforcing this
assumption. As a result, the Language Service has run into issues where
broken imports cause incremental compilation to fail and produce incorrect
results.
This commit introduces a mechanism within the compiler to keep track of
files for which dependency analysis has failed, and to always treat such
files as potentially affected by future incremental steps. This is tested
via the Language Service infrastructure to ensure that the compiler is doing
the right thing in the case of invalid imports.
PR Close#39923
To avoid overwhelming a user with secondary diagnostics that derive from a
"root cause" error, the compiler has the notion of a "poisoned" NgModule.
An NgModule becomes poisoned when its declaration contains semantic errors:
declarations which are not components or pipes, imports which are not other
NgModules, etc. An NgModule also becomes poisoned if it imports or exports
another poisoned NgModule.
Previously, the compiler tracked this poisoned status as an alternate state
for each scope. Either a correct scope could be produced, or the entire
scope would be set to a sentinel error value. This meant that the compiler
would not track any information about a scope that was determined to be in
error.
This method presents several issues:
1. The compiler is unable to support the language service and return results
when a component or its module scope is poisoned.
This is fine for compilation, since diagnostics will be produced showing the
error(s), but the language service needs to still work for incorrect code.
2. `getComponentScopes()` does not return components with a poisoned scope,
which interferes with resource tracking of incremental builds.
If the component isn't included in that list, then the NgModule for it will
not have its dependencies properly tracked, and this can cause future
incremental build steps to produce incorrect results.
This commit changes the tracking of poisoned module scopes to use a flag on
the scope itself, rather than a sentinel value that replaces the scope. This
means that the scope itself will still be tracked, even if it contains
semantic errors. A test is added to the language service which verifies that
poisoned scopes can still be used in template type-checking.
PR Close#39923