decaffeinate-parser
Version:
A better AST for CoffeeScript, inspired by CoffeeScriptRedux.
71 lines (70 loc) • 3.26 kB
JavaScript
import { Arr, Assign, IdentifierLiteral, Obj, Splat, StringLiteral, StringWithInterpolations, Value } from 'decaffeinate-coffeescript2/lib/coffeescript/nodes';
import { CSXElement } from '../nodes';
import getLocation from '../util/getLocation';
import getTemplateLiteralComponents from '../util/getTemplateLiteralComponents';
import mapAny from './mapAny';
export default function mapCSX(context, node) {
var _a = getLocation(context, node), line = _a.line, column = _a.column, start = _a.start, end = _a.end, raw = _a.raw;
var _b = node.args, properties = _b[0], children = _b[1];
var mappedProperties = mapCSXProperties(context, properties);
var mappedChildren = mapCSXChildren(context, children);
return new CSXElement(line, column, start, end, raw, mappedProperties, mappedChildren);
}
function mapCSXProperties(context, properties) {
if (!(properties instanceof Value) || !(properties.base instanceof Arr)) {
throw new Error('Expected a value for the CSX properties arg.');
}
var values = properties.base.objects;
var resultProperties = [];
for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
var value = values_1[_i];
if (!(value instanceof Value)) {
throw new Error('Expected value for CSX property.');
}
if (value.base instanceof Obj) {
for (var _a = 0, _b = value.base.objects; _a < _b.length; _a++) {
var propertyAssignment = _b[_a];
if (propertyAssignment instanceof Splat) {
resultProperties.push(mapAny(context, propertyAssignment));
}
else if (propertyAssignment instanceof Assign) {
if (!(propertyAssignment.value instanceof Value)) {
throw new Error('Unexpected property assignment value.');
}
if (!(propertyAssignment.value.base instanceof StringLiteral)) {
resultProperties.push(mapAny(context, propertyAssignment.value));
}
}
else {
throw new Error('Unexpected property assignment object field in CSX.');
}
}
}
else if (value.base instanceof IdentifierLiteral) {
// Do nothing; we don't need to consider this as a node to transform.
}
else {
throw new Error('Unexpected property assignment in CSX.');
}
}
return resultProperties;
}
function mapCSXChildren(context, children) {
if (!children) {
return [];
}
if (!(children instanceof Value)) {
throw new Error('Expected a value for the CSX children arg.');
}
if (children.base instanceof StringLiteral) {
return [];
}
else if (!(children.base instanceof StringWithInterpolations)) {
throw new Error('Expected a valid CSX children arg.');
}
var childInterpolatedString = children.base.body.expressions[0];
var unmappedExpressions = getTemplateLiteralComponents(context, childInterpolatedString).unmappedExpressions;
return unmappedExpressions.map(function (child) {
return child ? mapAny(context, child) : null;
});
}