toSourceLocation method

SourceLocation toSourceLocation([
  1. int? position
])
inherited

Converts a position to SourceLocation. If the coordinate is the end position which is not actually in the source, it will return the end location which is not actually in the source too.

Implementation

SourceLocation toSourceLocation([int? position]) {
  final coordinate = _toCoordinate(position);

  if (coordinate == _endCoordinate) {
    return source.last.end;
  }

  final segment = source[coordinate.index];
  final text = segment.text.substring(0, coordinate.offset + 1);
  final lines = text.split(RegExp('(?<=\n)'));

  return SourceLocation(
    segment.start.offset + coordinate.offset,
    line: segment.start.line + lines.length - 1,
    column: lines.length == 1
        ? segment.start.column + lines.first.length - 1
        : lines.last.length - 1,
  );
}