microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
99.3k stars 12.31k forks source link

feature request: public the TransformationContext.addDiagnostic and read them in the compiler and transpileModule #36733

Open Jack-Works opened 4 years ago

Jack-Works commented 4 years ago

Search Terms

custom transformer diagnostic

Suggestion

mark the method addDiagnostic in TransformationContext as public and read the diagnostic result in the compiler

Use Cases

I'm writing a custom transformer. In some cases, the transform will fail but I don't want to throw an Error. I want to add my error to the diagnostics.

Examples

I have tried to call the addDiagnostic by as any

function createDiagnosticForNodeInSourceFile(
    ts: ts,
    sourceFile: SourceFile,
    node: Node,
    message: DiagnosticMessage,
    arg0?: string | number,
    arg1?: string | number,
    arg2?: string | number,
    arg3?: string | number,
): DiagnosticWithLocation | undefined {
    return (ts as any).createDiagnosticForNodeInSourceFile?.(sourceFile, node, message, arg0, arg1, arg2, arg3)
}
function appendDiagnosticMessageForNode(context: TransformationContext, diag: DiagnosticWithLocation | undefined) {
    if (!diag) return false
    const _context = internalTransformationContext(context)
    if (!_context.addDiagnostic) return false
    _context.addDiagnostic(diag)
    return true

    function internalTransformationContext(
        context: TransformationContext,
    ): TransformationContext & { addDiagnostic?(diag: DiagnosticWithLocation): void } {
        return context as any
    }
}

But that doesn't work. After digging into the source code, I found that it seems like the diagnostics only read in the dts generating.

Checklist

My suggestion meets these guidelines:

RyanCavanaugh commented 4 years ago

@rbuckton what are your thoughts?

timocov commented 4 years ago

I'd like to see this in public as well. In my transformer there are cases where I'm 100% sure that the error is possible and I need to notify about that somehow.

Any updates on this?

timocov commented 4 years ago

@rbuckton @RyanCavanaugh just a friendly ping (it seems that there is no answer since last Ryan's question, soooo...)

timocov commented 1 year ago

Probably after #54276 it would worth to re-visit this ticket? 😂 cc @jakebailey (sorry for pining)