Commit Graph

231 Commits

Author SHA1 Message Date
Keen Yee Liau e1e1db3c01 fix(language-service): Paths on Windows should be normalized (#40492)
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
2021-01-20 08:46:03 -08:00
Keen Yee Liau 625d2c252b fix(language-service): diagnostic and definition should work for absolute url (#40406)
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
2021-01-13 09:05:04 -08:00
ayazhafiz 3b700985f0 fix(language-service): do not treat file URIs as general URLs (#39917)
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
2020-12-03 13:45:30 -08:00
Keen Yee Liau 2b84882ab0 fix(language-service): do not return external template that does not exist (#39898)
There is a bug in tsserver that causes it to crash when it tries to create
script info for an external template that does not exist.

I've submitted an upstream PR
https://github.com/microsoft/TypeScript/pull/41737 to fix this, but before
the commit lands in the stable release, we'll have to workaround the issue
in language service.

Close https://github.com/angular/vscode-ng-language-service/issues/1001

PR Close #39898
2020-12-03 07:15:17 -08:00
Alex Rickabaugh 643c96184c refactor(language-service): introduce DisplayParts abstraction for Ivy (#39505)
This commit refactors the QuickInfo abstraction shared between the VE and
Ivy services and used to implement hover tooltips (quick info), which was
extracted from the VE code in commit faa81dc. The new DisplayParts
abstraction is more general and can be used to extract information needed by
various LS functions (e.g. autocompletion).

This commit effectively reverts faa81dc, returning the original code to the
VE implementation as the Ivy code is now diverged.

PR Close #39505
2020-11-02 10:29:50 -08:00
Andrew Scott 563fb6cdbe feat(language-service): Implement go to definition for style and template urls (#39202)
This commit enables the Ivy Language Service to 'go to definition' of a
templateUrl or styleUrl, which would jump to the template/style file
itself.

PR Close #39202
2020-10-16 12:31:54 -07:00
Andrew Scott 5bda62c51d refactor(language-service): Return directive defs when input name is part of selector (#39243)
When an input name is part of the directive selector, it would be good to return the directive as well
when performing 'go to definition' or 'go to type definition'. As an example, this would allow
'go to type definition' for ngIf to take the user to the NgIf directive.
'Go to type definition' would otherwise return no results because the
input is a generic type. This would also be the case for all primitive
input types.

PR Close #39243
2020-10-15 14:17:24 -07:00
Andrew Scott a84976fdfc feat(language-service): Add getTypeDefinitionAtPosition (go to type definition) (#39145)
This commit adds the implementation for providing "go to type definition"
functionality in the Ivy Language Service.

PR Close #39145
2020-10-09 10:57:37 -07:00
Andrew Scott 904adb72d2 feat(language-service): add quick info for inline templates in ivy (#39060)
Adds implementation for `getQuickInfoAtPosition` to the Ivy Language
Service, which now returns `ts.QuickInfo` for inline templates.

PR Close #39060
2020-10-02 11:01:31 -07:00
Andrew Scott 8f66540152 test(language-service): Update AppComponent test project to include more fields (#39033)
In preparation for the Ivy Language service, add the same properties to AppComponent that appear in
TemplateReference so the inline template can be tested thoroughly.

PR Close #39033
2020-09-30 09:26:43 -04:00
Andrea Canciani daf8b7f100 feat(common): stricter types for DatePipe (#37447)
Make typing of DatePipe stricter to catch some misuses (such as passing
an Observable or an array) at compile time.

BREAKING CHANGE:
The signature of the `date` pipe now explicitly states which types are
accepted. This should only cause issues in corner cases, as any other
values would result in runtime exceptions.

PR Close #37447
2020-09-28 12:23:32 -04:00
Andrea Canciani 5f815c0565 fix(common): correct and simplify typing of AsyncPipe (#37447)
`AsyncPipe.transform` will never return `undefined`, even when passed
`undefined` in input, in contrast with what was declared in the
overloads.

Additionally the "actual" method signature can be updated to match the
most generic case, since the implementation does not rely on wrappers
anymore.

BREAKING CHANGE:
The async pipe no longer claims to return `undefined` for an input that
was typed as `undefined`. Note that the code actually returned `null` on
`undefined` inputs. In the unlikely case you were relying on this,
please fix the typing of the consumers of the pipe output.

PR Close #37447
2020-09-28 12:23:32 -04:00
Alan Agius 0fc44e0436 feat(compiler-cli): add support for TypeScript 4.0 (#38076)
With this change we add support for TypeScript 4.0

PR Close #38076
2020-08-24 13:06:59 -07:00
JoostK 874792dc43 feat(compiler): support unary operators for more accurate type checking (#37918)
Prior to this change, the unary + and - operators would be parsed as `x - 0`
and `0 - x` respectively. The runtime semantics of these expressions are
equivalent, however they may introduce inaccurate template type checking
errors as the literal type is lost, for example:

```ts
@Component({
  template: `<button [disabled]="isAdjacent(-1)"></button>`
})
export class Example {
  isAdjacent(direction: -1 | 1): boolean { return false; }
}
```

would incorrectly report a type-check error:

> error TS2345: Argument of type 'number' is not assignable to parameter
  of type '-1 | 1'.

Additionally, the translated expression for the unary + operator would be
considered as arithmetic expression with an incompatible left-hand side:

> error TS2362: The left-hand side of an arithmetic operation must be of
  type 'any', 'number', 'bigint' or an enum type.

To resolve this issues, the implicit transformation should be avoided.
This commit adds a new unary AST node to represent these expressions,
allowing for more accurate type-checking.

Fixes #20845
Fixes #36178

PR Close #37918
2020-08-21 12:25:53 -07:00
ivanwonder 10aba15154 fix(language-service): remove completion for string (#37983)
If the user inputs a string(e.g. `<div [ngClass]="'str~{cursor}'"></div>`), the completion is useless.

PR Close #37983
2020-07-13 14:16:56 -07:00
Keen Yee Liau ae5257cda6 fix(language-service): incorrect autocomplete results on unknown symbol (#37518)
This commit fixes a bug whereby the language service would incorrectly
return HTML elements if autocomplete is requested for an unknown symbol.
This is because we walk through every possible scenario, and fallback to
element autocomplete if none of the scenarios match.

The fix here is to return results from interpolation if we know for sure
we are in a bound text. This means we will now return an empty results if
there is no suggestions.

This commit also refactors the code a little to make it easier to
understand.

PR Close #37518
2020-06-26 14:51:32 -07:00
Keen Yee Liau c942662d79 fix(language-service): reinstate getExternalFiles() (#37750)
`getExternalFiles()` is an API that could optionally be provided by a tsserver plugin
to notify the server of any additional files that should belong to a particular project.

This API was removed in https://github.com/angular/angular/pull/34260 mainly
due to performance reasons.

However, with the introduction of "solution-style" tsconfig in typescript 3.9,
the Angular extension could no longer reliably detect the owning Project solely
based on the ancestor tsconfig.json. In order to support this use case, we have
to reinstate `getExternalFiles()`.

Fixes https://github.com/angular/vscode-ng-language-service/issues/824

PR Close #37750
2020-06-26 09:57:08 -07:00
ivanwonder e99bcbb4d4 fix(language-service): wrong completions in conditional operator (#37505)
In `a ? b.~{cursor}`, the LS will provide the symbols in the scope of the current template, because the `path.tail` is `falseExp` whose value is `EmptyExpr`, and the span of `falseExp` is wider than the `trueExp`, so the value of `path` should be narrowed.

PR Close #37505
2020-06-15 09:41:25 -07:00
Keen Yee Liau cc552dd702 feat(language-service): Remove HTML entities autocompletion (#37515)
This commit removes the autocompletion feature for HTML entities.
HTML entites are things like `&amp;`, `&lt;` etc.

There are a few reasons for the decision:

1. It is outside the core functionality of Angular LS
2. The implementation relies on regex, which incurs performance cost
3. There isn't much value if users do not already know which entity
   they want to use
4. The list that we provide is not exhaustive

PR Close #37515
2020-06-10 11:50:54 -07:00
Ayaz Hafiz 55979fe0ae feat(language-service): TS references from template items (#37437)
Keen and I were talking about what it would take to support getting
references at a position in the current language service, since it's
unclear when more investment in the Ivy LS will be available. Getting TS
references from a template is trivial -- we simply need to get the
definition of a symbol, which is already handled by the language
service, and ask the TS language service to give us the references for
that definition.

This doesn't handle references in templates, but that could be done in a
subsequent pass.

Part of https://github.com/angular/vscode-ng-language-service/issues/29

PR Close #37437
2020-06-08 17:23:49 -07:00
Keen Yee Liau 6280cf95b4 fix(language-service): Improve signature selection by finding exact match (#37494)
The function signature selection algorithm is totally naive. It'd
unconditionally pick the first signature if there are multiple
overloads. This commit improves the algorithm by returning an exact
match if one exists.

PR Close #37494
2020-06-08 17:23:12 -07:00
Keen Yee Liau 650974e1b3 test(language-service): Remove all markers from test project (#37475)
This commit removes all markers from the inline template in
`AppComponent` and external template in `TemplateReference`.

Test scenarios should be colocated with the test cases themselves.
Besides, many existing cases are invalid. For example, if we want to
test autocomplete for HTML element, the existing test case is like:
```
<~{cursor} h1>
```
This doesn't make much sense, becasue the language service already sees
the `h1` tag in the template. The correct test case should be:
```
<~{cursor
```
IMO, this reflects the real-world use case better.

This commit also uncovers a bug in the way HTML entities autocompletion
is done. There's an off-by-one error in which a cursor that immediately
trails the ampersand character fails to trigger HTML entities
autocompletion.

PR Close #37475
2020-06-08 10:25:42 -07:00
Ayaz Hafiz c4f4675ebf fix(language-service): Recover from error in analyzing Ng Modules (#37108)
In place of failing to return analyzed Ng Modules when the analyzer
fails, return the previously-analyzed Ng Modules (which may be empty)
and log an error.

Closes https://github.com/angular/vscode-ng-language-service/issues/777

PR Close #37108
2020-06-03 15:56:19 -07:00
Joey Perrott d1ea1f4c7f build: update license headers to reference Google LLC (#37205)
Update the license headers throughout the repository to reference Google LLC
rather than Google Inc, for the required license headers.

PR Close #37205
2020-05-26 14:26:58 -04:00
Keen Yee Liau a73d2a7688 test(language-service): Remove unused code in test project (#37122)
This commit removes the `bootstrap()` function in the test project since
its presence has no effect on the behavior of language service.

Also removes the explicit cast when instantiating `CounterDirectiveContext`,
and let type inference takes care of that.

PR Close #37122
2020-05-18 16:19:56 -07:00
Alan Agius 508c555ce2 test: update language service module resolution cache (#36989)
With this change we update the expect of the `module resolution cache` were in the second count with cache the `fileExists` is called less then 700 times.

PR Close #36989
2020-05-14 10:50:30 -07:00
Keen Yee Liau b58bd2bb91 test(language-service): external template update should not invalidate program (#36989)
In TypeScript 3.9, the compiler is able to re-use (i.e. not invalidate)
the previous program if only external templates (i.e. no TS files) have
changed.

PR Close #36989
2020-05-14 10:50:27 -07:00
Keen Yee Liau 40025f55ad refactor(language-service): move TS utils to separate file (#36984)
This commit refactors TS-only utility functions to a separate file so
that they could be shared with Ivy language service.
A separate ts_library rule is created so that there is no dependency on
`compiler` and `compiler-cli` to make the compilation fast and
light-weight.
The method `getPropertyAssignmentFromValue` is modified slightly to
improve the ergonomics of the function.

PR Close #36984
2020-05-11 11:07:50 -07:00
Ayaz Hafiz eb34aa551a feat(compiler): add name spans for property reads and method calls (#36826)
ASTs for property read and method calls contain information about
the entire span of the expression, including its receiver. Use cases
like a language service and compile error messages may be more
interested in the span of the direct identifier for which the
expression is constructed (i.e. an accessed property). To support this,
this commit adds a `nameSpan` property on

- `PropertyRead`s
- `SafePropertyRead`s
- `PropertyWrite`s
- `MethodCall`s
- `SafeMethodCall`s

The `nameSpan` property already existed for `BindingPipe`s.

This commit also updates usages of these expressions' `sourceSpan`s in
Ngtsc and the langauge service to use `nameSpan`s where appropriate.

PR Close #36826
2020-05-08 14:42:42 -07:00
Keen Yee Liau b3713a112f test(language-service): Add method to override inline template (#36890)
This commit adds a method `overrideInlineTemplate` to the
`MockTypescriptHost`. This allows us to override an inline template
in a Component without changing the TypeScript parts. This methods works
in a similar way as `MockTypescriptHost.override()`, which is used for
overriding external template.

PR Close #36890
2020-05-04 12:50:47 -07:00
Keen Yee Liau 58ea040570 test(language-service): add new mock host for testing ivy (#36879)
This commit adds a new mock host for testing the ivy language service.

Unlike the existing mock_host which mocks the LanguageServiceHost, the
Ivy mock host mocks just the filesystem interface, aka ts.ServerHost.

This is because Ivy language service requires an actual Project to
perform operations like adding synthetic typecheck files to the project,
and by extension, to the ts.Program. These requirements make the existing
mock host unsuitable to be reused.

This new testing structure also improves test performance, because the
old mock host copies (it actually creates symlinks, but still that's
relatively expensive due to the sheer number of files involved) all
@angular/* packages along with the typescript package to a temporary
node_modules directory. This is done every time setup() is called.
Instead, this new mock host just loads them from a pre-determined path
in Bazel runfiles.

PR Close #36879
2020-05-04 12:47:15 -07:00
Keen Yee Liau 12fcc7cafe build(language-service): make test project a filegroup (#36865)
This commit makes the test project a filegroup so that it could be
shared with the Ivy tests.
Also removed `project/foo.ts` since it is no longer used.

PR Close #36865
2020-05-01 10:02:34 -07:00
Keen Yee Liau 62ba0acfb5 test(language-service): do not invalidate @angular/core (#36845)
Fix typo and add test cases for https://github.com/angular/angular/pull/36783

PR closes https://github.com/angular/vscode-ng-language-service/issues/713

PR Close #36845
2020-04-29 14:27:33 -07:00
Ayaz Hafiz 8be0972836 fix(language-service): properly evaluate types in comparable expressions (#36529)
This commit fixes how the language service evaluates the compatibility
of types to work with arbitrary union types. As a result, compatibility
checks are now more strict and can catch similarities or differences
more clearly.

```
number|string == string|null  // OK
number|string == number       // OK
number|string == null         // not comparable
number == string              // not comparable
```

Using Ivy as a backend should provide these diagnoses for free, but we
can backfill them for now.

Closes https://github.com/angular/vscode-ng-language-service/issues/723

PR Close #36529
2020-04-16 16:07:47 -04:00
Ayaz Hafiz 5e80e7e216 refactor(language-service): clean up and exports and consolidate types (#36533)
PR Close #36533
2020-04-14 10:17:43 -07:00
Keen Yee Liau e485236502 test(language-service): Inline test cases in parsing-cases.ts (#36495)
This commit removes individual components from parsing-cases.ts and
colocate them with the actual tests. This makes the tests more readable.

PR Close #36495
2020-04-08 12:11:04 -07:00
JiaLiPassion ef4736d052 build: update jasmine to 3.5 (#34625)
1. update jasmine to 3.5
2. update @types/jasmine to 3.5
3. update @types/jasminewd2 to 2.0.8

Also fix several cases, the new jasmine 3 will help to create test cases correctly,
such as in the `jasmine 2.x` version, the following case will pass

```
expect(1 == 2);
```

But in jsamine 3, the case will need to be

```
expect(1 == 2).toBeTrue();
```

PR Close #34625
2020-04-08 12:10:34 -07:00
ivanwonder 81195a238b fix(language-service): use the `HtmlAst` to get the span of HTML tag (#36371)
The HTML tag may include `-` (e.g. `app-root`), so use the `HtmlAst` to get the span.

PR Close #36371
2020-04-07 15:10:33 -07:00
Keen Yee Liau 7f28845f58 test(language-service): remove ng-for-cases.ts (#36470)
This commit removes ng-for-cases.ts and moves all test cases to
inline expressions in TEST_TEMPLATE.

PR Close #36470
2020-04-07 11:34:38 -07:00
Keen Yee Liau 1dd0b6cc18 test(language-service): remove ng-if-cases.ts (#36470)
This commit removes ng-if-cases.ts and moves all test cases to inline
expressions in TEST_TEMPLATE.

PR Close #36470
2020-04-07 11:34:38 -07:00
Keen Yee Liau e145fa13b1 test(language-service): delete expression-cases.ts (#36468)
This commit deletes `expression-cases.ts` and moves the test cases to
inline expressions in TEST_TEMPLATE.

PR Close #36468
2020-04-07 10:20:27 -07:00
Keen Yee Liau eb8c6c7eff test(language-service): Move pipe tests to TEST_TEMPLATE (#36407)
This commit simplifies the completion tests for pipes by moving them to TEST_TEMPLATE.

PR Close #36407
2020-04-06 15:32:33 -07:00
Keen Yee Liau 1140bbc25c refactor(language-service): reformat using clang-format (#36426)
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
2020-04-06 09:29:42 -07:00
Ayaz Hafiz fe2b6923ba fix(language-service): infer type of elements of array-like objects (#36312)
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
2020-04-01 13:24:53 -07:00
ayazhafiz df890d7629 fix(compiler): record correct end of expression (#34690)
This commit fixes a bug with the expression parser wherein the end index
of an expression node was recorded as the start index of the next token,
not the end index of the current token.

Closes #33477
Closes https://github.com/angular/vscode-ng-language-service/issues/433

PR Close #34690
2020-03-20 10:19:02 -07:00
ayazhafiz acc483e2eb feat(language-service): improve non-callable error message (#35271)
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
2020-03-17 09:28:59 -07:00
Keen Yee Liau 31bec8ce61 feat(compiler): Propagate source span and value span to Variable AST (#36047)
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
2020-03-16 10:52:57 -07:00
ayazhafiz 18b1bd4415 fix(language-service): infer $implicit value for ngIf template contexts (#35941)
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
2020-03-11 14:52:27 -04:00
Keen Yee Liau 06779cfe24 feat(compiler): Add sourceSpan and keySpan to TemplateBinding (#35897)
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
2020-03-11 14:51:56 -04:00
Alex Rickabaugh 95c729f5d1 build: typescript 3.8 support (#35864)
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
2020-03-10 17:51:20 -04:00