Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions tsc/internal/api/session_program_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,57 @@ func TestProgramSourceFileIncludesSupplementalFile(t *testing.T) {
assert.Assert(t, sourceFile != nil)
}

// A file name with a trailing slash names the same source file.
// ToFileName normalizes the name and removes the trailing slash.
func TestProgramSourceFileNameWithTrailingSlash(t *testing.T) {
t.Parallel()

const fileName = "/home/projects/p/a.ts"
projectSession, _ := projecttestutil.Setup(map[string]any{
fileName: `export const a: number = "1";`,
})
defer projectSession.Close()
session := NewLSPSession(projectSession, nil)
defer session.Close()
response, err := session.handleCreateSnapshot(context.Background(), &CreateSnapshotParams{
CreatePrograms: []*CreateSnapshotProgramParams{{
RootFiles: []DocumentIdentifier{{FileName: fileName}},
CompilerOptions: core.CompilerOptions{NoLib: core.TSTrue},
}},
})
assert.NilError(t, err)
file := DocumentIdentifier{FileName: fileName + "/"}

metadata, err := session.handleGetSourceFileMetadata(context.Background(), &GetSourceFileParams{
Snapshot: response.Snapshot,
Project: response.Projects[0].Handle,
File: file,
})
assert.NilError(t, err)
assert.Assert(t, metadata != nil)

// Position 13 is in the name `a`.
symbol, err := session.handleGetSymbolAtPosition(context.Background(), &GetSymbolAtPositionParams{
Snapshot: response.Snapshot,
Project: response.Projects[0].Handle,
File: file,
Position: 13,
})
assert.NilError(t, err)
assert.Assert(t, symbol != nil)
assert.Equal(t, symbol.Name, "a")

diagnostics, err := session.handleGetSemanticDiagnostics(context.Background(), &GetDiagnosticsParams{
Snapshot: response.Snapshot,
Project: response.Projects[0].Handle,
Files: []DocumentIdentifier{file},
})
assert.NilError(t, err)
assert.Equal(t, len(diagnostics), 1)
assert.Equal(t, diagnostics[0].Code, int32(2322))
assert.Equal(t, diagnostics[0].FileName.AsString(), fileName)
}

func TestProgramStatisticsUseAPIChecker(t *testing.T) {
t.Parallel()

Expand Down
11 changes: 11 additions & 0 deletions tsc/internal/execute/tsctests/sys.go
Original file line number Diff line number Diff line change
Expand Up @@ -613,6 +613,17 @@ func (s *TestSys) replaceFileText(path string, oldText string, newText string) {
s.writeFileNoError(path, content)
}

// replaceFileTextNoMiss is like replaceFileText, but it panics if the file does
// not contain oldText. Use it when an edit that changes nothing makes the test
// pass for the wrong reason.
func (s *TestSys) replaceFileTextNoMiss(path string, oldText string, newText string) {
content := s.readFileNoError(path)
if !strings.Contains(content, oldText) {
panic(fmt.Sprintf("Text %q not found in %s", oldText, path))
}
s.writeFileNoError(path, strings.Replace(content, oldText, newText, 1))
}

func (s *TestSys) replaceFileTextAll(path string, oldText string, newText string) {
content := s.readFileNoError(path)
content = strings.ReplaceAll(content, oldText, newText)
Expand Down
72 changes: 72 additions & 0 deletions tsc/internal/execute/tsctests/tsc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,20 @@ func TestTscCommandline(t *testing.T) {
},
commandLineArgs: []string{"-p", "/home/src/workspaces/project"},
},
{
subScenario: "Parse -p with path to subfolder that has only declaration files and outDir",
files: FileMap{
"/home/src/workspaces/project/sub/a.d.ts": `declare const x: number;`,
"/home/src/workspaces/project/sub/tsconfig.json": `{ "compilerOptions": { "outDir": "../out" } }`,
},
commandLineArgs: []string{"-p", "sub"},
edits: []*tscEdit{
{
caption: "build with -b",
commandLineArgs: []string{"-b", "sub"},
},
},
},
{
subScenario: "Parse -p with empty tsconfig file",
files: FileMap{
Expand Down Expand Up @@ -392,6 +406,17 @@ func TestTscMissingFiles(t *testing.T) {
},
commandLineArgs: []string{"-p", "./tsconfig.json"},
},
{
subScenario: "rooted file names in tsconfig do not exist",
files: FileMap{
"/home/src/workspaces/project/tsconfig.json": stringtestutil.Dedent(
`{
"files": ["/x/", "C:"]
}`,
),
},
commandLineArgs: []string{"-p", "./tsconfig.json"},
},
{
subScenario: "extensionless file in tsconfig exists",
files: FileMap{
Expand Down Expand Up @@ -1730,6 +1755,53 @@ func TestTscIncremental(t *testing.T) {
},
},
},
{
subScenario: "tsbuildinfo has tuple of wrong length",
files: FileMap{
"/home/src/workspaces/project/a.ts": `import { b } from "./b"; export const a = b + 1;`,
"/home/src/workspaces/project/b.ts": "export const b = 2;",
"/home/src/workspaces/project/tsconfig.json": "{}",
},
commandLineArgs: []string{"-i"},
edits: []*tscEdit{
{
caption: "referencedMap entry with one element",
edit: func(sys *TestSys) {
// The non incremental build has no tsbuildinfo to change
if !sys.forIncrementalCorrectness {
sys.replaceFileTextNoMiss("/home/src/workspaces/project/tsconfig.tsbuildinfo", `"referencedMap":[[3,1]]`, `"referencedMap":[[3]]`)
}
},
},
{
caption: "referencedMap entry with three elements",
edit: func(sys *TestSys) {
// The non incremental build has no tsbuildinfo to change
if !sys.forIncrementalCorrectness {
sys.replaceFileTextNoMiss("/home/src/workspaces/project/tsconfig.tsbuildinfo", `"referencedMap":[[3,1]]`, `"referencedMap":[[3,1,2]]`)
}
},
},
{
caption: "root entry with three elements",
edit: func(sys *TestSys) {
// The non incremental build has no tsbuildinfo to change
if !sys.forIncrementalCorrectness {
sys.replaceFileTextNoMiss("/home/src/workspaces/project/tsconfig.tsbuildinfo", `"root":[[2,3]]`, `"root":[[1,2,3]]`)
}
},
},
{
caption: "root entry with no elements",
edit: func(sys *TestSys) {
// The non incremental build has no tsbuildinfo to change
if !sys.forIncrementalCorrectness {
sys.replaceFileTextNoMiss("/home/src/workspaces/project/tsconfig.tsbuildinfo", `"root":[[2,3]]`, `"root":[[]]`)
}
},
},
},
},
{
subScenario: "when global file is added, the signatures are updated",
files: FileMap{
Expand Down
7 changes: 7 additions & 0 deletions tsc/internal/execute/tsctests/tscbuild_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,13 @@ func TestBuildConfigFileErrors(t *testing.T) {
files: FileMap{},
commandLineArgs: []string{"--b", "bogus.json"},
},
{
subScenario: "reports no inputs found",
files: FileMap{
"/home/src/workspaces/project/tsconfig.json": `{ "include": ["missing.ts"] }`,
},
commandLineArgs: []string{"--b"},
},
{
subScenario: "reports syntax errors in config file",
files: FileMap{
Expand Down
42 changes: 42 additions & 0 deletions tsc/internal/fourslash/tests/renameFilePackageJson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import (
"testing"

"github.com/microsoft/TypeScript/tsc/internal/fourslash"
"github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto"
"github.com/microsoft/TypeScript/tsc/internal/testutil"
"github.com/microsoft/TypeScript/tsc/internal/tspath"
"gotest.tools/v3/assert"
)

func TestRenameFilePackageJson(t *testing.T) {
Expand Down Expand Up @@ -51,3 +53,43 @@ import { value } from ".//*rename*/%s.js";`, fileName, tspath.RemoveFileExtensio
})
}
}

func TestRenameFileNewNameIsNormalized(t *testing.T) {
t.Parallel()

// The new URI of the file rename is a normalized path. It has no "." segment,
// no ".." segment, and no empty segment.
for _, test := range []struct {
name string
newName string
newURI lsproto.DocumentUri
}{
{name: "dot segment", newName: "./b", newURI: "file:///src/b.ts"},
{name: "dot dot segment", newName: "x/../b", newURI: "file:///src/b.ts"},
{name: "empty segment", newName: "x//b", newURI: "file:///src/x/b.ts"},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
defer testutil.RecoverAndFail(t, "Panic on fourslash test")
const content = `// @Filename: /src/a.ts
export {};
// @Filename: /src/main.ts
import ".//*rename*/a";`

f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
defer done()
f.GoToMarker(t, "rename")
result := f.RenameAtCaret(t, test.newName)
if result.WorkspaceEdit == nil || result.WorkspaceEdit.DocumentChanges == nil {
t.Fatal("rename returned no document changes")
}
for _, change := range *result.WorkspaceEdit.DocumentChanges {
if change.RenameFile != nil {
assert.Equal(t, change.RenameFile.NewUri, test.newURI)
return
}
}
t.Fatal("rename returned no file rename")
})
}
}
1 change: 1 addition & 0 deletions tsc/internal/ls/lsconv/converters_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func TestDocumentURIToFileName(t *testing.T) {
{"file://server/share/file.ts", "//server/share/file.ts"},
{"file:///d%3A/work/ts932/lib/utils.ts", "d:/work/ts932/lib/utils.ts"},
{"file:///D%3A/work/ts932/lib/utils.ts", "D:/work/ts932/lib/utils.ts"},
{"file:///d%3A", "d:/"},
{"file:///d%3A/work/ts932/app/%28test%29/comp/comp-test.tsx", "d:/work/ts932/app/(test)/comp/comp-test.tsx"},
{"file:///path/to/file.ts#section", "/path/to/file.ts"},
{"file:///c:/test/me", "c:/test/me"},
Expand Down
51 changes: 51 additions & 0 deletions tsc/internal/module/resolver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,57 @@ func TestResolveDynamicDottedDirectory(t *testing.T) {
}
}

func TestResolveDynamicTypeRoot(t *testing.T) {
t.Parallel()

// In a type root under a dynamic URI, the file encoding and the directory
// encoding of the name differ. The file encoding keeps ".d.ts" outside the
// escape. The directory lookup uses the directory encoding.
const (
sourceFile = "^/~ts-uri~/custom/ts-nul-authority/a.ts"
typeRoot = "^/~ts-uri~/custom/ts-nul-authority/types"
name = "~ts-uri-escape~thing.d.ts"
fileTargetFile = typeRoot + "/~ts-uri-escape~7e74732d7572692d6573636170657e7468696e67~.d.ts"
directoryTargetFile = typeRoot + "/~ts-uri-escape~7e74732d7572692d6573636170657e7468696e672e642e7473~/index.d.ts"
)
for _, test := range []struct {
name string
targetFile tspath.RootedFilePath
module bool
}{
{name: "type reference to directory", targetFile: directoryTargetFile},
{name: "type reference to file", targetFile: fileTargetFile},
{name: "module to directory", targetFile: directoryTargetFile, module: true},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
fs := vfstest.FromMap(map[string]string{
sourceFile: "",
test.targetFile.AsString(): "declare const value: number;",
}, tspath.CaseSensitive)
host := &resolutionTestInputs{fs: fs, cwd: "^/~ts-uri~/custom/ts-nul-authority/"}
opts := &core.CompilerOptions{
ModuleResolution: core.ModuleResolutionKindBundler,
TypeRoots: []tspath.RootedDirectoryPath{typeRoot},
}

resolver := NewResolver(ResolverOptions{Host: host, CompilerOptions: opts})
var resolvedFileName tspath.RootedFilePath
if test.module {
// The module lookup falls back to the type roots.
resolved, _, _ := resolver.ResolveModuleName(name, sourceFile, core.ModuleKindCommonJS, nil)
resolvedFileName = resolved.ResolvedFileName
} else {
resolved, _ := resolver.ResolveTypeReferenceDirective(name, sourceFile, core.ResolutionModeNone, nil)
resolvedFileName = resolved.ResolvedFileName
}
if resolvedFileName != test.targetFile {
t.Errorf("resolved file = %q, expected %q", resolvedFileName, test.targetFile)
}
})
}
}

func TestResolvedModuleCarriesCaseInsensitivePath(t *testing.T) {
t.Parallel()

Expand Down
13 changes: 13 additions & 0 deletions tsc/internal/outputpaths/outputpaths_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,19 @@ func TestGetBuildInfoFileNameAcrossRoots(t *testing.T) {
configFilePath: "c:/src/project/...json",
expected: "c:/out/...tsbuildinfo",
},
{
name: "drive-like filename stem without rootDir",
outDir: "c:/out",
configFilePath: "c:/src/project/c:.json",
expected: "c:/out/c:.tsbuildinfo",
},
{
name: "drive-like filename stem in rootDir",
rootDir: "c:/src",
outDir: "c:/out",
configFilePath: "c:/src/c:.json",
expected: "c:/out/c:.tsbuildinfo",
},
{
name: "empty filename stem without outDir",
configFilePath: "c:/src/project/.json",
Expand Down
1 change: 1 addition & 0 deletions tsc/internal/tsoptions/extensionsiblings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ func TestGetFileNamesExtensionPriority(t *testing.T) {
{files: []string{"A.ts", "a.d.ts"}, include: []string{"**/*"}, expected: []string{"/p/A.ts", "/p/a.d.ts"}},
{files: []string{"a.d.ts", "a.ts"}, include: []string{"**/*"}, literals: []string{"a.d.ts"}, expected: []string{"/p/a.d.ts", "/p/a.ts"}},
{files: []string{"a.ts", "a.d.ts"}, include: []string{"**/*"}, literals: []string{"a.ts"}, expected: []string{"/p/a.ts"}},
{files: []string{"a.ts", "a.d.ts"}, include: []string{"*.d.ts"}, literals: []string{"a.ts"}, expected: []string{"/p/a.ts"}},
}
for _, c := range cases {
got, want := runGetFileNames(c.files, c.include, c.literals, c.allowJs, c.insens, nil, pattern, basePath)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/src/main.ts(2,14): error TS2883: The inferred type of 'v' cannot be named without a reference to 'L' from '../node_modules/pkg/dist/foo'. This is likely not portable. A type annotation is necessary.


==== /src/main.ts (1 errors) ====
import { make } from "dep";
export const v = make();
~
!!! error TS2883: The inferred type of 'v' cannot be named without a reference to 'L' from '../node_modules/pkg/dist/foo'. This is likely not portable. A type annotation is necessary.

==== /node_modules/pkg/package.json (0 errors) ====
{ "name": "pkg", "exports": { "./*": "./dist/*/" } }

==== /node_modules/pkg/dist/foo.d.ts (0 errors) ====
export interface L { x: number }

==== /node_modules/dep/package.json (0 errors) ====
{ "name": "dep" }

==== /node_modules/dep/index.d.ts (0 errors) ====
import type { L } from "../pkg/dist/foo";
export declare function make(): L;

Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//// [tests/cases/compiler/declarationEmitExportsPatternTargetTrailingSlash.ts] ////

//// [package.json]
{ "name": "pkg", "exports": { "./*": "./dist/*/" } }

//// [foo.d.ts]
export interface L { x: number }

//// [package.json]
{ "name": "dep" }

//// [index.d.ts]
import type { L } from "../pkg/dist/foo";
export declare function make(): L;

//// [main.ts]
import { make } from "dep";
export const v = make();


//// [main.js]
import { make } from "dep";
export const v = make();
Loading