Repository navigation
Strongly type file paths - #64159
Strongly type file paths#64159
Conversation
| type CompilerHost interface { | ||
| FS() vfs.FS | ||
| DefaultLibraryPath() string | ||
| GetCurrentDirectory() string |
There was a problem hiding this comment.
It's pretty amazing that we don't need this at all.
There was a problem hiding this comment.
🟡 Changes recommended
Path normalization, relative auto-import rebasing, and case-insensitive watcher invalidation have unresolved correctness defects.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Introduces strongly typed rooted paths and canonical path keys throughout the compiler, language server, VFS, and unstable TypeScript API.
Changes:
- Adds typed-path primitives,
CaseSensitivity, conversion helpers, and lint enforcement. - Propagates typed paths through resolution, emit, watching, LSP, and API boundaries.
- Adds regression tests and updates generated baselines.
File summaries
| File group | Description |
|---|---|
tsc/internal/tspath/* |
Defines typed paths and path operations. |
tsc/internal/{compiler,module,checker,ast,binder,parser,printer,sourcemap,transformers}/* |
Migrates compiler internals. |
tsc/internal/{ls,lsp,project,contentmapper}/* |
Migrates language-service boundaries. |
tsc/internal/{vfs,execute,transpile,bundled}/* |
Migrates filesystem and execution paths. |
tsc/internal/{testutil,testrunner,fourslash,format}/* |
Updates test infrastructure and cases. |
tsc/testdata/tests/cases/compiler/* |
Adds path regression scenarios. |
tsc/testdata/baselines/reference/* |
Updates expected compiler and LSP output. |
packages/typescript/src/* |
Exposes typed paths in the unstable API. |
packages/typescript/test/* |
Updates JavaScript API tests and benchmarks. |
tools/customlint/* |
Enforces typed-path invariants. |
tools/{gen-proto,scripts/tsc}/*, Herebyfile.mjs |
Updates generators and generated enums. |
tsc/cmd/tsc/* |
Converts process-level path boundaries. |
Review details
- Files reviewed: 169/449 changed files
- Comments generated: 3
- Review effort level: Balanced
💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.
e4c4ac8 to
cffbf0c
Compare
74c07a3 to
c11f029
Compare
There was a problem hiding this comment.
🟡 Changes recommended
CommonDirectoryOfFiles treats case-equivalent drive roots as unrelated, potentially corrupting common-source and emit-path computation.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
- Files reviewed: 164/668 changed files
- Comments generated: 1
- Review effort level: Balanced
c11f029 to
6f16b34
Compare
6f16b34 to
cfa8dbe
Compare
067147e to
ec2f191
Compare
| GetMTime(fileName tspath.RootedFilePath) time.Time | ||
| SetMTime(fileName tspath.RootedFilePath, mTime time.Time) error |
There was a problem hiding this comment.
Sort of wonder why we have these like this; the only methods left
ec2f191 to
ff268d3
Compare
dea245b to
541e689
Compare
c284087 to
d68173c
Compare
|
(not that the conflict-free state is going to survive the stuff already enabled to auto-merge) |
Replace ambiguous string path contracts with a typed lattice for rooted files, rooted directories, normalized relative paths, and canonical path keys. Keep canonical identity as a one-way sink while retaining presentation spelling wherever diagnostics, watches, symlinks, or protocol responses need it. Carry those invariants through compiler inputs and outputs, module resolution, project snapshots, language-service hosts, VFS operations, source maps, LSP conversion, and the JavaScript API. Separate raw compiler option wire values from finalized rooted options, and centralize explicit normalization, rooting, and case-sensitivity boundaries. Keep absent and empty sourceRoot values equivalent when decoding source maps. This preserves published map compatibility without weakening rooted-file invariants or selecting sources by file existence. Preserve the host casing policy when aggregating watcher directories. Presentation spelling must not prevent case-insensitive paths from sharing a watch, and case-sensitive paths must remain distinct. This commit consolidates the exploratory migration into one reviewable rewrite after the independently portable fixes. It also adapts those fixes to the typed representation and retains the two newer main changes, including auto-import completion retries and tuple completion filtering. Category: Typed-path migration
Keep path branding internal to finalized compiler state while allowing API callers to continue supplying ordinary strings. Normalize those values at API boundaries using generated compiler-option path metadata.
Path validation in the timed loop obscures filesystem performance. Prepare typed paths once so benchmark results exclude constructor work.
The path-type migration unintentionally changed the test filesystem from case-insensitive to case-sensitive. Keep coverage of canonicalized file identities and guard the test filesystem policy.
Custom diagnostic hosts should continue accepting ordinary directory strings, including spellings that need normalization. Cover this API boundary and remove the stale branded-directory imports.
Relative realpath callback results are resolved by the server against the queried path's directory. Normalizing them without a base in the async client rejects valid results and differs from the sync client.
Valid filenames such as .ts, ..ts, and ...ts lose their normalized path structure when their extensions are removed. Treating those incomplete prefixes as rooted paths can panic or misidentify their directory. Keep incomplete filename prefixes separate so resolution, output naming, and renaming preserve literal filenames without weakening rooted-path invariants.
d68173c to
d075c87
Compare
| @@ -17,11 +19,75 @@ const ( | |||
| CommandLineOptionTypeEnum CommandLineOptionKind = "enum" // map | |||
| ) | |||
|
|
|||
| type CommandLineOptionPathKind uint8 | |||
There was a problem hiding this comment.
This predates generated compiler options code; I will do a follow-up seeing if I can drop this.
… them microsoft#64159's typed file paths A merge, not a rebase, so every adamic commit cohere has pinned (2197f1e, e65aa4a, 740c377) stays reachable and adamic only fast-forwards. Conflicts, resolved once here: - compiler/program.go, GetSourceFileFromReference: upstream's typed origin.FileName().Directory(). ResolveFile, with our ExtraExtensions (the sourceExtensions patch) for the supported extensions. - compiler/program.go, GetSourceFile: upstream's version, and our path index (e65aa4a) leaves with it. Upstream now resolves both of the index's hot callers, the checker's import resolution and the checker pool's import adjacency, through GetSourceFileForResolvedModule(resolved), which reads the module's ResolvedPath and canonicalizes nothing. So filesByFileName, sourceFileByFileName and filesbyfilename_test.go are removed, as cohere's #w8qbnp6 ruled. - outputpaths/outputpaths.go, GetOutputJSFileNameWorker: typed, and X.a gains .js (AppendSuffix) only for a file that isn't content-mapped, since upstream's TestOutputFileNamesPreserveEmptyAndDotStems pins a content-mapped file's output as its own name. - tsoptions/tsconfigparsing.go, getFileNames: typed basePath, fs and CompilerOptions, enumerating our extraExtensions. - compiler/sourceextensions_test.go follows the typed API. The other patches merged cleanly: the reverse-mapped private members fix (8d550c8), sourceExtensions (2197f1e) and the variance fix (740c377). Checked: go build and go vet. go test ./... passes but internal/astnav, which fails identically on upstream main here (it runs node against an uninstalled typescript), and fswatch's TestSubscribeSubdirDeleteWithFiles, which fails on e65aa4a too, in a package identical to upstream's. The testrunner passes. Co-Authored-By: Ahra <ahra@ahra.ai> Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…159) Port the api behavior of microsoft/TypeScript#64159 (ed4807212), Go N' fed0bf24149f (behavior only, bump D plan section 3): - initialize answers caseSensitivity (Go tspath.CaseSensitivity, 0 or 1), not useCaseSensitiveFileNames (api/proto.go:273). - DocumentIdentifier (proto.go:299): an empty file name, an object with no uri, a duplicate uri and a uri that is not a non-empty string are errors; other members are skipped whole. ToFileName roots a file name against a directory (proto.go:353); ToAbsoluteFileName is gone into it. Program lookups root against the program's base directory (program_base_directory, Go Program.BaseDirectory, program.go:150). - ProjectResponse.configFileName is omitted for a project that is not configured (proto.go:1032, :1076). - A node handle and a decoded source file need a canonical path key, and the decoded file name must be rooted and normalized (session.go resolveNodeHandle, encoder/decoder.go:270). - A relative callback realpath answer is rooted against the path's directory (callbackfs.go:298); tsgo api roots --cwd against the system current directory (cmd/tsc/api.go:62); profile directories and files are rooted against the session's current directory (session.go:1376, :1388, :1395). - Markers (rule R5) on toPath, useCaseSensitiveFileNames and the requestFileSystem renames. Not ported here (needs other lanes): - CompilerOptionsInput: RawCompilerOptions.Finalize for createPrograms, reconfigurePrograms and transpile (proto.go:457, :465, :823; session.go) and TestCompilerOptionsInput need config 3's finalize_raw_compiler_options. - ResolvedModule.ResolvedPath in static resolutions and the resolver's BaseDirectory (module_resolution.go) need config item 4.1 and #64519. Tests: TestDecodeSourceFileRejectsInvalidFileName (decoder_test.go:73), the 6 new TestDocumentIdentifierUnmarshalJSON cases (proto_test.go:30; "empty object" is now an error), and the configFileName checks of TestCreateProgram (session_createprogram_test.go:76) and the request file system test. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Ports the program-core (compiler) behavior of ts#64159 (microsoft/TypeScript#64159). Go lines are at fed0bf24149f. - Include reasons: a relative file name is relative to the given directory (fileInclude.go:148 relativeTo; the key holds it), and explain_files takes it (program.go:2144; tsc passes the system current directory, execute/tsc/emit.go:156). Another root gives the absolute name (R4). A root file name is used as listed (fileInclude.go:173, :268). program::explain_files keeps its signature (the host's current directory, which is the system's in tsc); explain_files_relative_to takes the directory. - The package.json in "File is CommonJS/ESM module because ..." is PackageJsonDirectory.ResolveFile("package.json"), so one in the root is "/package.json", not "//package.json" (includeprocessor.go:168). - "A file cannot have a reference to itself" (TS1006) is checked on the resolved file in resolveTripleslashPathReference (fileloader.go:747), so an extensionless self reference is an error too. - GetLibFileFromReference finds the lib file by name (program.go:2187); N looked the bare name up as a path and found nothing. - TS5011: the computed common source directory uses the base directory (program.go:1245, R1) and compares as rooted text (R3). - NewProgram::base_directory (program.go:150, R1). Probes against the Go N' oracle (selfref, ts5011, explain, jsonout and 4 mapRoot sets) give the same output. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This is a wacky change I've wanted to try out for a while and finally started screwing around with with copilot.
Right now (and in Strada), we have just two kinds of paths:
string- 🤷Path- an OS dependent string used for map keys, lowercased on case insensitive systemsOur use of
stringpaths led to us slappingnormalizeSlashes,normalizePath, etc everywhere, as we often were unsure (or pessimistic) whether or not a path had its slashes normalized to/, had redundant components removed, trailing slashes removed, not relative, etc. This is extra bad because on Linux, macOS, etc, paths are basically guaranteed to meet all of the criteria, but we'd try and normalize them anyway.This PR changes this by introducing named/branded types for paths which assert properties about those paths. This is not a new concept; I believe yarn's FS package has this, and I'm sure others do.
As a hierarchy:
string- No guarantees.RootedPath- The path is absolute, has normalized slashes, no trailing/.RootedFilePath- ARootedPath, but indicates that the path is supposed to point at a file.RootedDirectoryPath- ARootedPath, but indicates that the path is supposed to point at a directory.PathKey- Same as the oldPath, but renamed for clarity.This is a big refactor that requires changing a lot of code, but leads to some pretty important properties.
Paths are converted at the boundaries, e.g. paths provided via config files, CLI, from the OS, the editor, etc. Once converted, you always know exactly what format a path is in and therefore never need to normalize again.
Paths are always rooted. The "current working directory" does not need to be plumbed around as much anymore, since most uses were simply to root paths we were unsure about.
Since paths are always rooted,
ComparePathsOptions's current dir field is no longer needed! This means comparing paths only requiresUseCaseSensitiveFileNames. This applies also to all of our oldtoPathconversions, since we only ever need to canonicalize rooted paths. So, I created a newCaseSensitivityenum, and then all of the plumbing forComparePathsOptions, its working dir, etc, also get to go away.The impact of this is measurable; I instrumented main vs my branch to count how many of the normalizing operations go away and it's a lot:
Old compiler fixture
maintyped-pathsCombinePathsNormalizePathNormalizeSlashesVS Code
srcmaintyped-pathsCombinePathsNormalizePathNormalizeSlashesThat's millions of normalizations that no longer need to happen. In terms of runtime, it's not a lot of savings, even on Windows, but I did also measure about a 7% speedup in program load of the old compiler, which is nice.
In the course of this PR, copilot found 15 bugs. 8 of which were unrelated but noticed as the files were being read, but 7 of which were related to typed paths. 4 of those bugs were also present in Strada!
Additionally, the strong typing here caught 3 different bugs that have been around in main for a while, places where we had mixed up paths, rooted them relative to the wrong directory, etc. Those are denoted in my (awful) git history as being things to port to main, which I may still do.
In addition to just the types themselves, a new lint rule bans manually hacking on the paths; all operations should go through methods on the paths themselves. No concat, splitting, conversions, yourself.
The downside here is just churning the API and introducing these concepts to downstream API users. But the strong typing itself I think is worth it, and doing a lot less work is a bonus too. We probably won't have a change to do something like this for a while.
I'm also going to say that this fixes #44174 just since this eliminates nearly all normalization; we might still do a quick check at the boundaries, but other than that, we never normalize gain.