v0.2.0a - Log works with one parameter. Hello world!

This commit is contained in:
ElementG9 2019-12-06 10:02:17 -07:00
parent c8195cef5a
commit b2a686c27c
3 changed files with 48 additions and 3 deletions

View File

@ -2,6 +2,7 @@
const args = process.argv.slice(2);
const tokenizer = require('../src/tokenizer.js');
const parser = require('../src/parser.js');
const code = require('../src/code.js');
if (typeof args[0] != 'undefined') {
// Execute from file.
@ -21,9 +22,14 @@ if (typeof args[0] != 'undefined') {
func(answer);
}
}
console.log('Welcome to Pivot v0.1.0 Alpha.');
console.log('Welcome to Pivot v0.2.0 Alpha.');
console.log('Type \'exit\' to exit.');
let data = {
log: "console.log"
};
repl('> ', (answer) => {
console.log(require('util').inspect(parser.parse(tokenizer.tokenize(answer)), { depth: null }));
let jsAnswer = code.translate(parser.parse(tokenizer.tokenize(answer)), data);
// console.log(require('util').inspect(jsAnswer, { depth: null }));
eval(jsAnswer);
});
}

38
src/code.js Normal file
View File

@ -0,0 +1,38 @@
/**
* @module code
* @file Runs the code / transpiles the code to JavaScript
* @author Garen Tyler <garentyler@gmail.com>
*/
/**
* @function translate
* @desc Translates the code to JS, given an AST
* @param {Token[]} ast The ast.
* @returns {String} The JS code.
* @public
*/
function translate(ast, data) {
let out = '';
for (let i = 0; i < ast.length; i++) {
if (ast[i].type == 'operator' && ast[i].subtype == 'function call') {
let temp = '';
if (!(Object.keys(data).indexOf(ast[i].operands[0].value) > -1))
throw new ReferenceError(`Undefined function ${ast[i].operands[0].value}`);
else temp += data[ast[i].operands[0].value];
temp += '(';
for (let j = 0; j < ast[i].operands[1].tokens.length; j++) {
if (j != 0)
temp += ', ';
if (ast[i].operands[1].tokens[j].type == 'string')
temp += `"${ast[i].operands[1].tokens[j].value}"`;
}
temp += ');'
out += temp;
}
}
return out;
}
module.exports = {
translate
};

View File

@ -208,7 +208,8 @@ function functionCall(ast) {
for (let i = 0; i < ast.length; i++) {
if (ast[i].type == 'group')
ast[i].tokens = functionCall(ast[i].tokens); // Recursively order the groups.
else if (ast[i].type == 'name' && ast[i].subtype == 'variable') { // Member access operator.
else if ((ast[i].type == 'name' && ast[i].subtype == 'variable') || // Normal function call
(ast[i].type == 'operator' && (ast[i].value == '.' || ast[i].value == 'member access'))) { // Function call in member access. Example: console.log()
if (typeof ast[i + 1] == 'undefined')
continue; // Nothing after the variable; skip this loop.
if (ast[i + 1].type == 'group' && ast[i + 1].subtype == 'parenthesis') {