Skip to content

SourceMaps do not correctly map external source files line and col values #29300

@petebacondarwin

Description

@petebacondarwin

TypeScript Version: 3.2.2

The line in error is still in place on the master branch, so I expect this bug is still an issue on the latest TypeScript version.

Search Terms: sourcemaps, external file, emitPos, emitSourcePos, setSourceMapRange, invalid line col, synthesized nodes

Issue

While developing SourceMapped templates for the new Ivy renderer in Angular, I came across this problem.

We are using setSourceMapRange(node, sourceMapRange) to specify that synthesized nodes should map to spans in external template files. I.E. the sourceMapRange.source property is not the current SourceFile being transformed.

The code at
https://github.com/Microsoft/TypeScript/blob/4a0bc59f77265ea116be8d9c5f16bb5185663a8c/src/compiler/emitter.ts#L4392
is computing the line and character positions based on the currentSourceFile rather than on the sourceMapSource file.

function emitPos(pos: number) {
  if (sourceMapsDisabled || positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
    return;
  }

  const { line: sourceLine, character: sourceCharacter } = getLineAndCharacterOfPosition(currentSourceFile!, pos);
  sourceMapGenerator!.addMapping(
    writer.getLine(),
    writer.getColumn(),
    sourceMapSourceIndex,
    sourceLine,
    sourceCharacter,
    /*nameIndex*/ undefined);
}

I believe that the call should be:

getLineAndCharacterOfPosition(sourceMapSource, pos);

Expected behavior:

The mapped line and column, computed from the offset, should be relative to the external file.

Actual behavior:

The mapped line and column, computed from the offset, are relative to the current source file, rather than the external file.

Related Issues:

This functionality was originally created here #15935 to support the same use case in Angular.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptDomain: API: TransformsRelates to the public transform APIFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions