UNPKG

decaffeinate-parser

Version:

A better AST for CoffeeScript, inspired by CoffeeScriptRedux.

59 lines (58 loc) 2.28 kB
import { SourceType } from 'coffee-lex'; import { inspect } from 'util'; export default function getLocation(context, node) { var loc = node.locationData; var start = context.linesAndColumns.indexForLocation({ line: loc.first_line, column: loc.first_column }); var last = context.linesAndColumns.indexForLocation({ line: loc.last_line, column: loc.last_column }); if (start === null || last === null) { throw new Error("unable to determine range for location: " + inspect(loc) + "}"); } var line = loc.first_line + 1; var column = loc.first_column + 1; var end = last + 1; // Shrink to be within the size of the source. if (start < 0) { start = 0; } if (end > context.source.length) { end = context.source.length; } var firstTokenOfNode = requireToken(firstSemanticTokenAfter(context, start), node); var lastTokenOfNode = requireToken(firstSemanticTokenBefore(context, end), node); start = firstTokenOfNode.start; end = lastTokenOfNode.end; var raw = context.source.slice(start, end); return { line: line, column: column, start: start, end: end, raw: raw }; } export function firstSemanticTokenAfter(context, index) { var tokenIndex = context.sourceTokens.indexOfTokenMatchingPredicate(function (token) { return (token.start >= index && token.type !== SourceType.NEWLINE && token.type !== SourceType.COMMENT); }, context.sourceTokens.indexOfTokenNearSourceIndex(index)); return tokenIndex === null ? null : context.sourceTokens.tokenAtIndex(tokenIndex); } export function firstSemanticTokenBefore(context, index) { var tokenIndex = context.sourceTokens.lastIndexOfTokenMatchingPredicate(function (token) { return (token.end <= index && token.type !== SourceType.NEWLINE && token.type !== SourceType.COMMENT); }, context.sourceTokens.indexOfTokenNearSourceIndex(index)); return tokenIndex === null ? null : context.sourceTokens.tokenAtIndex(tokenIndex); } function requireToken(token, node) { if (token === null) { throw new Error("unable to find token for node: " + inspect(node)); } return token; }