UNPKG

decaffeinate-parser

Version:

A better AST for CoffeeScript, inspired by CoffeeScriptRedux.

44 lines (43 loc) 2.48 kB
"use strict"; exports.__esModule = true; var SourceType_1 = require("coffee-lex/dist/SourceType"); var nodes_1 = require("../nodes"); var getLocation_1 = require("../util/getLocation"); var mapAny_1 = require("./mapAny"); var mapPossiblyEmptyBlock_1 = require("./mapPossiblyEmptyBlock"); function mapSwitch(context, node) { var _a = getLocation_1["default"](context, node), line = _a.line, column = _a.column, start = _a.start, end = _a.end, raw = _a.raw; var expression = node.subject ? mapAny_1["default"](context, node.subject) : null; var cases = node.cases.map(function (_a) { var conditions = _a[0], body = _a[1]; if (!Array.isArray(conditions)) { conditions = [conditions]; } var switchConditions = conditions.map(function (condition) { return mapAny_1["default"](context, condition); }); var consequent = mapPossiblyEmptyBlock_1["default"](context, body); var whenToken = getWhenTokenBeforeOffset(context, switchConditions[0].start, start); var locationForIndex = context.linesAndColumns.locationForIndex(whenToken.start); if (!locationForIndex) { throw new Error("cannot map WHEN token start to line/column: " + whenToken.start); } var caseLine = locationForIndex.line, caseColumn = locationForIndex.column; var end = getLocation_1["default"](context, body).end; return new nodes_1.SwitchCase(caseLine + 1, caseColumn + 1, whenToken.start, end, context.source.slice(whenToken.start, end), switchConditions, consequent); }); return new nodes_1.Switch(line, column, start, end, raw, expression, cases, mapPossiblyEmptyBlock_1["default"](context, node.otherwise)); } exports["default"] = mapSwitch; function getWhenTokenBeforeOffset(context, offset, lowerBound) { var offsetTokenIndex = context.sourceTokens.indexOfTokenNearSourceIndex(offset); var lowerBoundTokenIndex = context.sourceTokens.indexOfTokenNearSourceIndex(lowerBound); var whenTokenIndex = context.sourceTokens.lastIndexOfTokenMatchingPredicate(function (token) { return token.type === SourceType_1["default"].WHEN; }, offsetTokenIndex, lowerBoundTokenIndex); if (whenTokenIndex) { var whenToken = context.sourceTokens.tokenAtIndex(whenTokenIndex); if (whenToken) { return whenToken; } } throw new Error("unable to find WHEN token before " + offset + " (lower bound: " + lowerBound + ")"); }