@alu0101244488/ast-types
v1.1.1
Published
Package for the translation of the spread operator to older ecma standards
Downloads
5
Readme
AST-Types
Installation
For installation it is only required to use the next command:
npm install @alu0101244488/ast-types
You can see the npm package on the following link:
https://www.npmjs.com/package/@alu0101244488/ast-types
Usage as executable:
To execute you can use the following command where [inputFile]
is the file with the javasctipt code to compute and [outputFile]
is the file to print the corresponding code with the transformations applied. Note is that the -o [outputFile]
or --output [outputFile]
is optional and the resulting code will be displayed on terminal in any case (a test file is given to try).
cf [inputFile] -o [outputFile]
Other options suported are -h
or --help
, and -V
or --version
which shows all the corresponding information or the version of the package correspondingly.
Example of the execution. You can see more details about the result of the execution in the Examples section.
Usage from code:
The source file containis a function spreadOperatorTranspile()
which is exported. This function needs a string o code as a parameter. This string should contain a javascript code and depending if its a restElement or a spreadElement it acts accordingly.
Functions implemented to to apply the constant folding:
- constaSpreadOperatorTranspile()
/**
* @desc Function that translates the spread operator from
* the ecma6 standard to older standards by removing it
* and changing it with its correspondenting expression.
* @param {string} code input code
* @returns {string} resulting code
*/
function spreadOperatorTranspile (code) {
...
}
- replaceRestElement
/**
* @desc Auxiliary function to the sreadOperator function that
* in the case of an restElement node, remplaces it with
* its correspondenting code
* @param {node o path} node AST node of the ast to be modified
* @param {nodeo path} parent AST parent node needed to modify
*/
function replaceRestElement(node, parent) {
...
}
- replaceSpreadElement
/**
* @desc Auxiliary function to the sreadOperator function that
* in the case of an spreadElement node, remplaces it with
* its correspondenting code
* @param {node o path} node AST node of the ast to be modified
* @param {nodeo path} parent AST parent node needed to modify
*/
function replaceSpreadElement(node, parent) {
...
}
Deprecated verisions
Two versions were tried before. Both using the ast-types package. But it was easier to do this work using the estraverse package.
- deprecated version 1
This first version using the library can only translate the rest element from a function with two parameters, one of which is the rest element. It cannot read multiple sentences. It only reads function declarations statemets.
import { parse } from "espree";
import { NodePath } from "ast-types";
import { namedTypes as n, builders as b, visit } from "ast-types";
import recast from "recast";
import * as espree from "espree";
'use strict';
function spreadOperator(code) {
let programPath = new NodePath(parse(code, { ecmaVersion: 6, loc: false }));
let functionDeclaration = programPath.get("body", 0);
let paramsLength = functionDeclaration.value.params.length;
let varId = functionDeclaration.value.params[paramsLength - 1].argument.name;
let lineToAdd = `let ${varId} = Array.prototype.slice.call(arguments, 1);`;
let newNode = espree.parse(lineToAdd, {ecmaVersion: 6, loc: false}).body[0];
delete(functionDeclaration.value.params[paramsLength - 1]);
functionDeclaration.value.params = [functionDeclaration.value.params[0]];
functionDeclaration.value.body.body.unshift(newNode)
const resultCode = recast.print(programPath).code;
return resultCode;
}
- deprecated version 2
This second version as the irst one, can only translate rest elements.But in this case it visits all the nodes in the AST so it accepts multiple sentences and other things like nested functions declarations.
import { parse } from "espree";
import { NodePath } from "ast-types";
import { namedTypes as n, builders as b, visit } from "ast-types";
import recast from "recast";
import * as espree from "espree";
'use strict';
function spreadOperator(code) {
let ast = espree.parse(code, {ecmaVersion: 7, loc: false});
let sliceExpr = b.memberExpression(
b.memberExpression(
b.memberExpression(
b.identifier("Array"),
b.identifier("prototype"),
false
),
b.identifier("slice"),
false
),
b.identifier("call"),
false
);
visit(ast, {
visitFunction(path) {
const node = path.node;
this.traverse(path);
let lastArg = node.params.pop(); // Remove the 'rest' parameter
if (lastArg.type !== "RestElement") return;
// For the purposes of this example, we won't worry about functions
// with Expression bodies.
n.BlockStatement.assert(node.body);
// var rest = Array.prototype.slice.call(arguments, n);
const restVarDecl = b.variableDeclaration("var", [
b.variableDeclarator(
lastArg.argument,
b.callExpression(sliceExpr, [
b.identifier("arguments"),
b.literal(node.params.length)
])
)
]);
// Insert the statement 'var rest = Array.prototype.slice.call(arguments, n);'
// at the beginning of the body
path.get("body", "body").unshift(restVarDecl);
}
});
return recast.print(ast).code;
}
Examples
Here is an example of the execution of a very simple code where we to translate first a rest element from a function and then another exmple with the translation of an spread element in an array. These are the cases that this code can translate.
- Example for rest element:
Input file:
var y = 1;
function sum(x, y, z, ...rest) {
let b = x + y + z + rest[0];
return b * rest[1];
}
Output:
var y = 1;
function sum(x, y, z) {
var rest = Array.prototype.slice.call(arguments, 3);
let b = x + y + z + rest[0];
return b * rest[1];
}
- Example for spread element:
Input file:
let parts = ['shoulders', 'knees'];
let lyrics = ['head', ...parts, 'and', 'toes'];
Output:
let parts = [
'shoulders',
'knees'
];
let lyrics = [].concat(['head'], parts, ['and'], ['toes']);
Author
Aram Pérez Dios alu0101244488