Skip to content

Sourcemaps: parentheses added by the printer have no location #211

Closed

Description

@leonidaz

When the printer decides an expression needs parentheses that the AST does not have, it writes ( and ) without a location. The ( therefore has no segment of its own, and a lookup at that column resolves to whatever was mapped before it.

class B extends function () {} {}
declare const a: string, b: number;
(a || b)();

prints

class B extends (function () {}) {}

declare const a: string, b: number;

(a || b)();

TypeScript reports both errors on the parenthesized span, so the range starts at the (:

diagnostic generated range segment at the (
TS2507 Type '() => void' is not a constructor function type (function () {}) at 1:16 none; the segments on that line are at columns 0, 6, 7, 17 (the wrapped node's start), 29, …
TS2349 This expression is not callable `(a

For the class case the nearest segment to the left is the end of B, so the diagnostic is drawn from the space before extends. A consumer that builds ranges from exact positions (tsrx does, through Volar) gets no mapping for the start at all and drops the diagnostic.

The parentheses come from maybe_wrap and from the inline wrap in the ClassDeclaration|ClassExpression visitor around superClass. In the second example the parentheses exist in the source, but Acorn drops them (preserveParens off) and the printer adds them back, so the same thing happens to authored parentheses.

Since #198 the root visitor maps every node's loc.start and loc.end, but the ( is written before the node is visited and the ) after, so both fall outside the node's mappings.

A fix that stays within #198's rule of not estimating positions: when writing a synthesized (, set the location to the wrapped node's loc.start first, and after writing ) set it to the node's loc.end. The parenthesized span then maps to the expression's own span, which is what the diagnostic is about. That covers maybe_wrap and the superClass site with a couple of lines each.

Separately, the superClass wrap is more conservative than the grammar requires: class B extends function () {} {} and class A extends maybe! {} are valid without parentheses (extends takes a LeftHandSideExpression), but both are wrapped because EXPRESSIONS_PRECEDENCE puts FunctionExpression and TSNonNullExpression below NewExpression. That is harmless for output but adds parentheses that then need mapping.

Reproduced on esrap 2.3.11 (main at 314ea21) with @sveltejs/acorn-typescript, via the script below (prints the generated code, then each TS diagnostic's range and the segments on its line).

script
import * as acorn from 'acorn';
import { tsPlugin } from '@sveltejs/acorn-typescript';
import { decode } from '@jridgewell/sourcemap-codec';
import ts from 'typescript';
import { print } from 'esrap';
import language from 'esrap/languages/ts';

const parser = acorn.Parser.extend(tsPlugin());
const source = `class B extends function () {} {}
declare const a: string, b: number;
(a || b)();
`;
const ast = parser.parse(source, { ecmaVersion: 'latest', sourceType: 'module', locations: true });
const { code, map } = print(ast, language({}));
console.log(code);
const lines = decode(map.mappings);
const to_pos = (text, o) => { const b = text.slice(0, o).split('\n'); return { line: b.length - 1, column: b.at(-1).length }; };
const ls = ts.createLanguageService({
	getScriptFileNames: () => ['gen.ts'], getScriptVersion: () => '1',
	getScriptSnapshot: (f) => f === 'gen.ts' ? ts.ScriptSnapshot.fromString(code) : ts.sys.fileExists(f) ? ts.ScriptSnapshot.fromString(ts.sys.readFile(f)) : undefined,
	getCurrentDirectory: () => process.cwd(), getCompilationSettings: () => ({ strict: true, lib: ['lib.es2022.d.ts'] }),
	getDefaultLibFileName: (o) => ts.getDefaultLibFilePath(o), fileExists: ts.sys.fileExists, readFile: ts.sys.readFile
});
for (const d of ls.getSemanticDiagnostics('gen.ts')) {
	const s = to_pos(code, d.start);
	const segs = (lines[s.line] ?? []).map((x) => `${x[0]}->${x[2] + 1}:${x[3]}`).join(' ');
	console.log(`TS${d.code} ${ts.flattenDiagnosticMessageText(d.messageText, ' ')}`);
	console.log(`  range ${JSON.stringify(code.slice(d.start, d.start + d.length))} starts at generated ${s.line + 1}:${s.column}; segments on that line (genCol->src): ${segs}`);
}

Activity

  1. added a commit that references this issue on Sep 24, 2026
    a0c2db4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions