Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use SWC to parse and transform code instead of Babel #1365

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ var ERROR = 2;
module.exports = {
env: {
'node': true,
'es2017': true
'es2020': true
},

extends: 'eslint:recommended',
Expand Down
68 changes: 37 additions & 31 deletions Alloy/commands/compile/ast/builtins-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@ var path = require('path'),
fs = require('fs'),
_ = require('lodash'),
logger = require('../../../logger'),
U = require('../../../utils');
U = require('../../../utils'),
{ Visitor } = require('@swc/core/Visitor');

var EXCLUDE = ['backbone', 'CFG', 'underscore'];
var BUILTINS_PATH = path.join(__dirname, '..', '..', '..', 'builtins');
var loaded = [];

function isRequire(n) {
return n.type === 'CallExpression' && n.callee.value == 'require';
}

function appendExtension(file, extension) {
extension = '.' + extension;
file = U.trim(file);
Expand Down Expand Up @@ -53,39 +58,40 @@ function loadMomentLanguages(config) {
}
}

module.exports = function (_ref) {
var types = _ref.types;
var rx = /^(\/?alloy)\/(.+)$/;
module.exports = class BuiltIns extends Visitor {
constructor(opts) {
super();
this.opts = opts;
this.regex = /^(\/?alloy)\/(.+)$/;

return {
visitor: {
CallExpression: function(p) {
var theString = p.node.arguments[0],
match;
if (p.node.callee.name === 'require' && // Is this a require call?
theString && types.isStringLiteral(theString) && // Is the 1st param a literal string?
(match = theString.value.match(rx)) !== null && // Is it an alloy module?
!_.includes(EXCLUDE, match[2]) && // Make sure it's not excluded.
!_.includes(loaded, match[2]) // Make sure we didn't find it already
) {
// Make sure it hasn't already been copied to Resources
var name = appendExtension(match[2], 'js');
if (fs.existsSync(path.join(this.opts.dir.resources, match[1], name))) {
return;
}
}
visitCallExpression(n) {
const string = n.arguments[0];
let match;
if (
isRequire(n) &&
string.expression.type === 'StringLiteral' &&
(match = string.expression.value.match(this.regex)) !== null
) {
if (!EXCLUDE.includes(match[2]) && !loaded.includes(match[2])) {
// Make sure it hasn't already been copied to Resources
var name = appendExtension(match[2], 'js');
if (fs.existsSync(path.join(this.opts.dir.resources, match[1], name))) {
return super.visitCallExpression(n);
}

// make sure the builtin exists
var source = path.join(BUILTINS_PATH, name);
var dest = path.join(this.opts.dir.resources, 'alloy', name);
loadBuiltin(source, name, dest);
// make sure the builtin exists
var source = path.join(BUILTINS_PATH, name);
var dest = path.join(this.opts.dir.resources, 'alloy', name);
loadBuiltin(source, name, dest);

if ('moment.js' === name) {
// if momentjs is required in the project, also load the
// localizations which may be used
loadMomentLanguages(this.opts);
}
if ('moment.js' === name) {
// if momentjs is required in the project, also load the
// localizations which may be used
loadMomentLanguages(this.opts);
}
}
}
};
};
return super.visitCallExpression(n);
}
};
120 changes: 43 additions & 77 deletions Alloy/commands/compile/ast/controller.js
Original file line number Diff line number Diff line change
@@ -1,96 +1,62 @@
var U = require('../../../utils'),
babylon = require('@babel/parser'),
types = require('@babel/types'),
generate = require('@babel/generator').default,
{ default: traverse, Hub, NodePath } = require('@babel/traverse');

var isBaseControllerExportExpression = types.buildMatchMemberExpression('exports.baseController');

const GENCODE_OPTIONS = {
retainLines: true
};
swc = require('@swc/core'),
{ Visitor } = require('@swc/core/Visitor');

exports.processController = function(code, file) {
var baseController = '',
moduleCodes = '',
newCode = '',
exportSpecifiers = [];
exportSpecifiers = [],
es6mods;

try {
var ast = babylon.parse(code, { sourceFilename: file, sourceType: 'unambiguous' });
const x = swc.parseSync(code);
const plugin = new ProcessController();
plugin.visitModule(x);
newCode = swc.printSync(x).code;
es6mods = plugin.moduleCodes;
} catch (e) {
U.dieWithCodeFrame('Error generating AST for "' + file + '". Unexpected token at line ' + e.loc.line + ' column ' + e.loc.column, e.loc, code);
}

const hub = new Hub();
hub.buildError = function (node, message, Error) {
const loc = node && node.loc;
const err = new Error(message);
return {
es6mods: es6mods,
base: baseController,
code: newCode
};
};

if (loc) {
err.loc = loc.start;
}
class ProcessController extends Visitor {
constructor() {
super();

return err;
};
const path = NodePath.get({
hub: hub,
parent: ast,
container: ast,
key: 'program'
}).setContext();
traverse(ast, {
enter: function(path) {
if (types.isAssignmentExpression(path.node) && isBaseControllerExportExpression(path.node.left)) {
// what's equivalent of print_to_string()? I replaced with simple value property assuming it's a string literal
baseController = '\'' + path.node.right.value + '\'';
}
},
this.moduleCodes = '';

ImportDeclaration: function(path) {
moduleCodes += generate(path.node, GENCODE_OPTIONS).code;
path.remove();
},
}

ExportNamedDeclaration: function(path) {
var node = path.node;
var specifiers = node.specifiers;
if (specifiers && specifiers.length !== 0) {
specifiers.forEach(function (specifier) {
if (specifier.local && specifier.local.name) {
exportSpecifiers.push(specifier.local.name);
}
});
}
moduleCodes += generate(node, GENCODE_OPTIONS).code;
path.remove();
}
}, path.scope);
visitAssignmentExpression(node) {
if (node.left.property.value === 'baseController') {
baseController = node.right.raw;
}
return super.visitAssignmentExpression(node);
}

if (exportSpecifiers.length > 0) {
traverse(ast, {
enter: function(path) {
var node = path.node,
name;
if (node.type === 'VariableDeclaration') {
name = node.declarations[0].id.name;
} else if (node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') {
name = node.id.name;
}
visitModuleItems(nodes) {
const transformed = [];
for (const node of nodes) {

if (exportSpecifiers.indexOf(name) !== -1) {
moduleCodes += generate(node, GENCODE_OPTIONS).code;
path.remove();
}
}
if (node.type !== 'ImportDeclaration' && node.type !== 'ExportDeclaration') {
transformed.push(node);
continue;
}
const mod = swc.printSync({
type:'Module',
body: [node],
span: node.span
});
this.moduleCodes += mod.code;
}

newCode = generate(ast, GENCODE_OPTIONS).code;
} catch (e) {
U.dieWithCodeFrame('Error generating AST for "' + file + '". Unexpected token at line ' + e.loc.line + ' column ' + e.loc.column, e.loc, code);
return transformed;
}

return {
es6mods: moduleCodes,
base: baseController,
code: newCode
};
};
}
Loading
Loading