Skip to content
Closed
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
45 changes: 43 additions & 2 deletions cmd/tsgo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/execute"
"github.com/microsoft/typescript-go/internal/execute/tsc"
)

func main() {
Expand All @@ -25,8 +26,48 @@ func runMain() int {
return runAPI(args[1:])
}
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()

// Not signal.NotifyContext: we need to know which signal fired so we can exit by
// re-raising it, the way the JS tsc terminates under node's default handler.
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sigCh)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Written before cancel(), so a canceled CommandLine always finds the signal here.
canceledBy := make(chan os.Signal, 1)
go func() {
select {
case sig := <-sigCh:
canceledBy <- sig
cancel()
case <-ctx.Done():
}
}()

result := execute.CommandLine(ctx, newSystem(), args, nil)

if result.Status == tsc.ExitStatusCanceled {
// Terminate via the signal itself, for the conventional exit code (130 for
// SIGINT, 143 for SIGTERM) and the terminal reset an unhandled signal produces.
select {
case sig := <-canceledBy:
// Does not return if the signal is re-delivered; otherwise (e.g. Windows)
// fall through to the same exit code numerically.
reRaiseSignal(sig)
if signo := signalNumber(sig); signo != 0 {
return 128 + signo
}
default:
}
}
return int(result.Status)
}

// signalNumber returns the platform signal number for sig, or 0 if it has none.
func signalNumber(sig os.Signal) int {
if s, ok := sig.(syscall.Signal); ok {
return int(s)
}
return 0
}
10 changes: 10 additions & 0 deletions cmd/tsgo/reraisesignal_other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//go:build !unix

package main

import "os"

// reRaiseSignal is a no-op here: these platforms cannot re-deliver a termination
// signal to the current process (on Windows, os.Process.Signal rejects Interrupt).
func reRaiseSignal(sig os.Signal) {
}
22 changes: 22 additions & 0 deletions cmd/tsgo/reraisesignal_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//go:build unix

package main

import (
"os"
"os/signal"
"syscall"
)

// reRaiseSignal restores the default disposition for sig and re-delivers it to this
// process, terminating us via the signal itself. It returns only if that fails.
func reRaiseSignal(sig os.Signal) {
s, ok := sig.(syscall.Signal)
if !ok {
return
}
signal.Reset(s)
if proc, err := os.FindProcess(os.Getpid()); err == nil {
_ = proc.Signal(s)
}
}
9 changes: 9 additions & 0 deletions internal/compiler/checkerpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,10 @@ func (p *checkerPool) GetGlobalDiagnostics() []*ast.Diagnostic {
p.createCheckers()
globalDiagnostics := make([][]*ast.Diagnostic, len(p.checkers))
p.forEachCheckerParallel(func(idx int, checker *checker.Checker) {
// A canceled checker panics in checkNotCanceled if asked for diagnostics.
if checker.WasCanceled() {
return
}
globalDiagnostics[idx] = checker.GetGlobalDiagnostics()
})
return SortAndDeduplicateDiagnostics(slices.Concat(globalDiagnostics...))
Expand All @@ -155,6 +159,11 @@ func (p *checkerPool) forEachCheckerGroupDo(ctx context.Context, files []*ast.So
p.locks[checkerIdx].Lock()
defer p.locks[checkerIdx].Unlock()
for i, file := range files {
// Feeding another file to a checker that canceled mid-check panics in
// checkNotCanceled.
if ctx.Err() != nil {
break
}
if checker := p.checkers[checkerIdx]; checker == p.fileAssociations[file] {
cb(checker, i, file)
}
Expand Down
93 changes: 93 additions & 0 deletions internal/compiler/checkerpool_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package compiler_test

import (
"context"
"strings"
"sync/atomic"
"testing"

"github.com/microsoft/typescript-go/internal/bundled"
"github.com/microsoft/typescript-go/internal/compiler"
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/tsoptions"
"github.com/microsoft/typescript-go/internal/vfs/vfstest"
)

// cancelAfterNPolls cancels itself after Err has been polled pollThreshold times,
// then stays canceled, so cancellation lands after checking has begun.
type cancelAfterNPolls struct {
context.Context
pollThreshold int32
polls atomic.Int32
tripped atomic.Bool
done chan struct{}
}

func newCancelAfterNPolls(pollThreshold int32) *cancelAfterNPolls {
return &cancelAfterNPolls{Context: context.Background(), pollThreshold: pollThreshold, done: make(chan struct{})}
}

func (c *cancelAfterNPolls) Err() error {
if c.tripped.Load() {
return context.Canceled
}
if c.polls.Add(1) > c.pollThreshold {
if c.tripped.CompareAndSwap(false, true) {
close(c.done)
}
return context.Canceled
}
return nil
}

func (c *cancelAfterNPolls) Done() <-chan struct{} { return c.done }

// TestGetGlobalDiagnosticsAfterCancellation pins the checker-pool behavior that
// GetGlobalDiagnostics skips a checker canceled mid-check rather than reusing it
// (which panics in checkNotCanceled). This guards every caller, including
// emitBuildInfo's error-state probe, which has no cancellation check of its own.
func TestGetGlobalDiagnosticsAfterCancellation(t *testing.T) {
t.Parallel()

if !bundled.Embedded {
t.Skip("bundled files are not embedded")
}

fs := bundled.WrapFS(vfstest.FromMap[any](nil, false /*useCaseSensitiveFileNames*/))

// Many statements with type errors across a few files: global diagnostics exist,
// and the checker polls often so cancellation lands mid-check.
var src strings.Builder
for i := range 50 {
src.WriteString("export const v")
src.WriteString(strings.Repeat("x", i+1))
src.WriteString(`: number = "not a number";` + "\n")
}
for _, name := range []string{"/src/a.ts", "/src/b.ts", "/src/c.ts"} {
_ = fs.WriteFile(name, src.String())
}

// One checker, so the mid-check cancellation marks the same checker that the
// subsequent GetGlobalDiagnostics will visit.
oneChecker := 1
program := compiler.NewProgram(compiler.ProgramOptions{
Config: &tsoptions.ParsedCommandLine{
ParsedConfig: &core.ParsedOptions{
FileNames: []string{"/src/a.ts", "/src/b.ts", "/src/c.ts"},
CompilerOptions: &core.CompilerOptions{Strict: core.TSTrue, Checkers: &oneChecker},
},
},
Host: compiler.NewCompilerHost("/src", fs, bundled.LibPath(), nil, nil),
})

ctx := newCancelAfterNPolls(5)

// Drive checking only to leave the checker canceled; the result is discarded.
_ = program.GetSemanticDiagnostics(ctx, nil)
if !ctx.tripped.Load() {
t.Fatal("expected cancellation to trip during checking, but it never did")
}

// The real assertion: this must not panic on the canceled checker.
_ = program.GetGlobalDiagnostics(ctx)
}
10 changes: 10 additions & 0 deletions internal/compiler/program.go
Original file line number Diff line number Diff line change
Expand Up @@ -1761,6 +1761,11 @@ func HandleNoEmitOnError(ctx context.Context, program ProgramLike, files []*ast.
if !program.Options().NoEmitOnError.IsTrue() {
return nil // No emit on error is not set, so we can proceed with emitting
}
if ctx.Err() != nil {
// The emit is abandoned anyway, and re-running diagnostics on an
// already-canceled checker panics in checkNotCanceled.
return nil
}

diagnostics := GetDiagnosticsOfAnyProgram(
ctx,
Expand Down Expand Up @@ -1815,6 +1820,11 @@ func GetDiagnosticsOfAnyProgram(

if len(allDiagnostics) == configFileParsingDiagnosticsLength {
allDiagnostics = appendDiagnosticsForAllFiles(allDiagnostics, getSemanticDiagnostics)
// The calls below reuse the now-canceled checkers, which panics in
// checkNotCanceled; the diagnostics are discarded anyway.
if ctx.Err() != nil {
return allDiagnostics
}
// Ask for the global diagnostics again (they were empty above); we may have found new during checking, e.g. missing globals.
allDiagnostics = append(allDiagnostics, program.GetGlobalDiagnostics(ctx)...)
}
Expand Down
51 changes: 39 additions & 12 deletions internal/execute/build/buildtask.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package build

import (
"context"
"fmt"
"slices"
"strings"
Expand Down Expand Up @@ -73,10 +74,16 @@ type BuildTask struct {
dirty bool
}

func (t *BuildTask) waitOnUpstream() {
// Returns true when upstream is done, false when canceled.
func (t *BuildTask) waitOnUpstream(ctx context.Context) bool {
for _, upstream := range t.upStream {
<-upstream.task.done
select {
case <-upstream.task.done:
case <-ctx.Done():
return false
}
}
return true
}

func (t *BuildTask) unblockDownstream() {
Expand Down Expand Up @@ -120,15 +127,18 @@ func (t *BuildTask) report(orchestrator *Orchestrator, configPath tspath.Path, b
close(t.reportDone)
}

func (t *BuildTask) buildProject(orchestrator *Orchestrator, path tspath.Path) {
// Wait on upstream tasks to complete
t.waitOnUpstream()
if t.pending.Load() {
func (t *BuildTask) buildProject(ctx context.Context, orchestrator *Orchestrator, path tspath.Path) {
// The ctx.Err() check is not redundant: waitOnUpstream only observes the context
// while it has upstream to wait on, so a task with none (e.g. an up-to-date root)
// would take the no-build success path and swallow the interrupt.
if ctx.Err() != nil || !t.waitOnUpstream(ctx) {
t.result.exitStatus = tsc.ExitStatusCanceled
} else if t.pending.Load() {
t.status = t.getUpToDateStatus(orchestrator, path)
t.reportUpToDateStatus(orchestrator)
if !t.handleStatusThatDoesntRequireBuild(orchestrator) {
t.compileAndEmit(orchestrator, path)
t.updateDownstream(orchestrator, path)
t.compileAndEmit(ctx, orchestrator, path)
t.updateDownstream(ctx, orchestrator, path)
} else {
if t.resolved != nil {
for _, diagnostic := range t.resolved.GetConfigFileParsingDiagnostics() {
Expand All @@ -151,7 +161,11 @@ func (t *BuildTask) buildProject(orchestrator *Orchestrator, path tspath.Path) {
t.unblockDownstream()
}

func (t *BuildTask) updateDownstream(orchestrator *Orchestrator, path tspath.Path) {
func (t *BuildTask) updateDownstream(ctx context.Context, orchestrator *Orchestrator, path tspath.Path) {
// A canceled build has partial results; downstream tasks must not consume them.
if ctx.Err() != nil {
return
}
if t.isInitialCycle {
return
}
Expand Down Expand Up @@ -187,7 +201,7 @@ func (t *BuildTask) updateDownstream(orchestrator *Orchestrator, path tspath.Pat
}
}

func (t *BuildTask) compileAndEmit(orchestrator *Orchestrator, path tspath.Path) {
func (t *BuildTask) compileAndEmit(ctx context.Context, orchestrator *Orchestrator, path tspath.Path) {
t.errors = nil
if orchestrator.opts.Command.BuildOptions.Verbose.IsTrue() {
t.result.reportStatus(ast.NewCompilerDiagnostic(diagnostics.Building_project_0, orchestrator.relativeFileName(t.config)))
Expand Down Expand Up @@ -216,7 +230,7 @@ func (t *BuildTask) compileAndEmit(orchestrator *Orchestrator, path tspath.Path)
t.result.program = incremental.NewProgram(program, oldProgram, orchestrator.host, orchestrator.opts.Sys.Now, orchestrator.opts.Testing != nil)
compileTimes.ChangesComputeTime = orchestrator.opts.Sys.Now().Sub(changesComputeStart)

result, statistics := tsc.EmitAndReportStatistics(tsc.EmitInput{
result, statistics := tsc.EmitAndReportStatistics(ctx, tsc.EmitInput{
Sys: orchestrator.opts.Sys,
ProgramLike: t.result.program,
Program: program,
Expand All @@ -233,6 +247,10 @@ func (t *BuildTask) compileAndEmit(orchestrator *Orchestrator, path tspath.Path)
})
t.result.exitStatus = result.Status
t.result.statistics = statistics
if result.Status == tsc.ExitStatusCanceled {
// EmitResult is nil when canceled; the code below would dereference it.
return
}
t.packageJsons = t.result.program.PackageJsonLookupPaths()
if (!program.Options().NoEmitOnError.IsTrue() || len(result.Diagnostics) == 0) &&
(len(result.EmitResult.EmittedFiles) > 0 || t.status.kind != upToDateStatusTypeOutOfDateBuildInfoWithErrors) {
Expand Down Expand Up @@ -714,7 +732,7 @@ func (t *BuildTask) updateTimeStamps(orchestrator *Orchestrator, emittedFiles []
updateTimeStamp(t.resolved.GetBuildInfoFileName())
}

func (t *BuildTask) cleanProject(orchestrator *Orchestrator, path tspath.Path) {
func (t *BuildTask) cleanProject(ctx context.Context, orchestrator *Orchestrator, path tspath.Path) {
if t.resolved == nil {
t.reportDiagnostic(ast.NewCompilerDiagnostic(diagnostics.File_0_not_found, t.config))
t.result.exitStatus = tsc.ExitStatusDiagnosticsPresent_OutputsSkipped
Expand All @@ -723,8 +741,17 @@ func (t *BuildTask) cleanProject(orchestrator *Orchestrator, path tspath.Path) {

inputs := collections.NewSetFromItems(core.Map(t.resolved.FileNames(), orchestrator.toPath)...)
for outputFile := range t.resolved.GetOutputFileNames() {
// Stop mid-clean rather than exiting with success, so the CLI re-raises.
if ctx.Err() != nil {
t.result.exitStatus = tsc.ExitStatusCanceled
return
}
t.cleanProjectOutput(orchestrator, outputFile, inputs)
}
if ctx.Err() != nil {
t.result.exitStatus = tsc.ExitStatusCanceled
return
}
t.cleanProjectOutput(orchestrator, t.resolved.GetBuildInfoFileName(), inputs)
}

Expand Down
6 changes: 3 additions & 3 deletions internal/execute/build/graph_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ func (b *buildOrderTestCase) run(t *testing.T) {
Sys: sys,
Command: buildCommand,
})
orchestrator.GenerateGraph(nil)
orchestrator.GenerateGraph(t.Context(), nil)
buildOrder := core.Map(orchestrator.Order(), b.projectName)
assert.DeepEqual(t, buildOrder, b.expected)
verifyDeps(orchestrator, buildOrder, false)
Expand All @@ -136,7 +136,7 @@ func (b *buildOrderTestCase) run(t *testing.T) {
}
}

orchestrator.GenerateGraphReusingOldTasks()
orchestrator.GenerateGraphReusingOldTasks(t.Context())
buildOrder2 := core.Map(orchestrator.Order(), b.projectName)
assert.DeepEqual(t, buildOrder2, b.expected)

Expand All @@ -146,7 +146,7 @@ func (b *buildOrderTestCase) run(t *testing.T) {
Sys: sys,
Command: buildCommandWatch,
})
orchestrator.GenerateGraph(nil)
orchestrator.GenerateGraph(t.Context(), nil)
buildOrder3 := core.Map(orchestrator.Order(), b.projectName)
verifyDeps(orchestrator, buildOrder3, true)
})
Expand Down
Loading