`EFNoLeadingComments` suppresses synthesized leading comments in tsgo; Strada only suppresses source comments
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 2/5
- Tiempo estimado
- 1-3 horas
- Aptitud para principiantes
- 84/100
- Tipo de issue
- Error
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Stack tecnológico
- go, typescript
- Área
- compilers
Línea de trabajo
Comienza en internal/printer/printer.go con emitLeadingSyntheticCommentsOfNode y emitTrailingSyntheticCommentsOfNode, y luego ejecuta el ejemplo TestSyntheticLeadingCommentWithNoLeadingComments del issue. Compara la salida con el comportamiento del printer de Strada y añade cobertura específica para los comentarios sintéticos iniciales y finales con EFNoLeadingComments, EFNoTrailingComments y EFNoComments. La tarea estará terminada cuando se puedan suprimir los comentarios del código fuente sin suprimir los reemplazos sintetizados.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
🔎 Search Terms
NoLeadingComments, EFNoLeadingComments, synthesized comments, setSyntheticLeadingComments, emitLeadingSyntheticCommentsOfNode, printer, comment emit
🕗 Version & Regression Information
- This changed between TypeScript 6.0.3 and tsgo built from
mainatdf1a31e6d5. - The tsgo behavior has been there since synthesized comment emit was first ported, in microsoft/typescript-go#1599 (commit
809b2c09, "Const enum inlining and synthetic comment emit support").
⏯ Playground Link
None. This is only reachable through the transformer/printer API, so the repros below use the API directly.
💻 Code
Strada, run with Node against [email protected]:
const ts = require('typescript');
const f = ts.factory;
const sf = ts.createSourceFile('a.ts', '', ts.ScriptTarget.Latest);
const printer = ts.createPrinter();
const comment = {kind: ts.SyntaxKind.MultiLineCommentTrivia, text: '* synthesized ', hasTrailingNewLine: true, pos: -1, end: -1};
for (const [label, flags] of [['no flags', 0], ['NoLeadingComments', ts.EmitFlags.NoLeadingComments], ['NoComments', ts.EmitFlags.NoComments]]) {
const stmt = f.createExpressionStatement(f.createIdentifier('x'));
ts.setSyntheticLeadingComments(stmt, [comment]);
if (flags) ts.setEmitFlags(stmt, flags);
console.log(`--- ${label}\n` + printer.printNode(ts.EmitHint.Unspecified, stmt, sf));
}
tsgo, the same thing as a test in internal/printer:
func TestSyntheticLeadingCommentWithNoLeadingComments(t *testing.T) {
for _, c := range []struct {
name string
flags EmitFlags
}{{"no flags", 0}, {"EFNoLeadingComments", EFNoLeadingComments}, {"EFNoComments", EFNoComments}} {
sf := parser.ParseSourceFile(ast.SourceFileParseOptions{FileName: "/a.ts", Path: "/a.ts"}, "", core.ScriptKindTS)
ec := NewEmitContext()
stmt := ec.Factory.NewExpressionStatement(ec.Factory.NewIdentifier("x"))
ec.SetSyntheticLeadingComments(stmt, []SynthesizedComment{{Kind: ast.KindMultiLineCommentTrivia, Text: "* synthesized ", HasTrailingNewLine: true, Loc: core.UndefinedTextRange()}})
ec.SetEmitFlags(stmt, c.flags)
t.Logf("--- %s\n%s", c.name, NewPrinter(PrinterOptions{}, PrintHandlers{}, ec).Emit(stmt, sf))
}
}
🙁 Actual behavior
tsgo drops the synthesized comment as soon as EFNoLeadingComments is set:
--- no flags
/** synthesized */
x;
--- EFNoLeadingComments
x;
--- EFNoComments
x;
🙂 Expected behavior
Same as TypeScript 6.0.3, which keeps the synthesized comment in all three cases:
--- no flags
/** synthesized */
x;
--- NoLeadingComments
/** synthesized */
x;
--- NoComments
/** synthesized */
x;
Additional information about the issue
Where the two differ. In Strada, emitLeadingCommentsOfNode in src/compiler/emitter.ts uses NoLeadingComments (and a negative pos) only to decide whether to emit the comments found in the source text for the node's range. The synthesized comments are emitted after that check, unconditionally:
const skipLeadingComments = pos < 0 || (emitFlags & EmitFlags.NoLeadingComments) !== 0 || node.kind === SyntaxKind.JsxText;
// ...
if (!skipLeadingComments) {
emitLeadingComments(pos, /*isEmittedNode*/ node.kind !== SyntaxKind.NotEmittedStatement);
}
// ...
forEach(getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
In tsgo, the synthesized comments go through their own function, emitLeadingSyntheticCommentsOfNode in internal/printer/printer.go, which returns early on the flag:
func (p *Printer) emitLeadingSyntheticCommentsOfNode(node *ast.Node, emitFlags EmitFlags) {
if emitFlags&EFNoLeadingComments != 0 {
return
}
synth := p.emitContext.GetSyntheticLeadingComments(node)
// ...
Trailing comments have the same shape: Strada's emitTrailingCommentsOfNode emits getSyntheticTrailingComments(node) unconditionally, and tsgo's emitTrailingSyntheticCommentsOfNode returns early on EFNoTrailingComments. I measured only the leading case; the trailing one is from reading the code.
These lines came in with microsoft/typescript-go#1599, the PR that first added synthesized comment emit. I couldn't find any discussion of the flag in that PR, so this looks like it was introduced in the original port rather than chosen deliberately.
Why it matters. A transformer that rewrites a comment needs to hide the node's original source comment and print its replacement. In Strada, that means setting NoLeadingComments and attaching the replacement with setSyntheticLeadingComments. tsickle, which rewrites TypeScript JSDoc into Closure Compiler annotations, relies on this. In tsgo, EFNoLeadingComments also suppresses the synthesized replacement, so the pattern breaks: the transformer can hide both comments or neither. For our Go port of tsickle, this means decorated class members get printed with both the original JSDoc and the rewritten JSDoc. Closure Compiler rejects that output, so builds that pass with TypeScript 6.0.3 fail with tsgo.
Possible fix. Emit synthesized comments regardless of EFNoLeadingComments / EFNoTrailingComments, as Strada does, so the flags only control comments taken from the source text:
--- a/internal/printer/printer.go
+++ b/internal/printer/printer.go
func (p *Printer) emitLeadingSyntheticCommentsOfNode(node *ast.Node, emitFlags EmitFlags) {
- if emitFlags&EFNoLeadingComments != 0 {
- return
- }
synth := p.emitContext.GetSyntheticLeadingComments(node)
for _, c := range synth {
p.emitLeadingSynthesizedComment(c)
}
}
@@
func (p *Printer) emitTrailingSyntheticCommentsOfNode(node *ast.Node, emitFlags EmitFlags) {
- if emitFlags&EFNoTrailingComments != 0 {
- return
- }
synth := p.emitContext.GetSyntheticTrailingComments(node)
for _, c := range synth {
p.emitTrailingSynthesizedComment(c)
}
}
This leaves emitFlags unused in both functions. I kept the signatures unchanged to keep the diff small. I haven't run tsgo's test suite with this change, so I don't know whether anything in tsgo itself now depends on the current behavior.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.4k
- Merge medio
- 2 d 5 h
- PR fusionados (30 d)
- 116
Preparar el entorno
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de microsoft/TypeScript
-
Possible Improvement
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
microsoft/TypeScript#64278 · 1 comentario · 1 reacción ·
Los mantenedores suelen responder en 1 día
-
Docs
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
microsoft/TypeScript#64118 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Dificultad 1/5 Menos de una hora Aptitud para principiantes 88/100
microsoft/TypeScript#64094 ·
Los mantenedores suelen responder en 1 día
-
Docs
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
microsoft/TypeScript#63959 · 5 comentarios ·
Los mantenedores suelen responder en 1 día
-
Domain: lib.d.ts Help Wanted
Dificultad 1/5 Menos de una hora Aptitud para principiantes 91/100
microsoft/TypeScript#63722 · 4 comentarios · 1 reacción ·
Los mantenedores suelen responder en 1 día
Todos los issues de microsoft/TypeScript
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
Los mantenedores suelen responder en 1 día
-
Remove obsolete ipAllocationPolicy field from containernodepool-subnetworkref test dependencyAbierto
Dificultad 1/5 Menos de una hora Aptitud para principiantes 92/100
GoogleCloudPlatform/k8s-config-connector#13462 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
coder/coder#29955 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
OpenAI-compatible endpoint: response ids have only 999 possible values (chatcmpl-rand.Intn(999))Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
[deep-report] Document Pi engine's model: provider-prefix auth mechanism in engine comparison tableAbiertoautomation code-quality cookie documentation improvement quick-win task-mining
Dificultad 1/5 Menos de una hora Aptitud para principiantes 92/100
Los mantenedores suelen responder en 1 día