Skip to content

Commit

Permalink
fixup! Prototyping JavaScript generation from LISP
Browse files Browse the repository at this point in the history
  • Loading branch information
tshemsedinov committed Dec 6, 2024
1 parent b4c514e commit 5b16a59
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 36 deletions.
43 changes: 29 additions & 14 deletions lib/expressions.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@ class NumberExpression {
return this.value;
}

toJavaScript() {
toExpression() {
return this.value;
}

toJavaScript() {
return `() => ${this.value}`;
}
}

class VariableExpression {
Expand All @@ -28,36 +32,47 @@ class VariableExpression {
return context[this.name];
}

toJavaScript(args) {
if (!args.includes(this.name)) {
args.push(this.name);
}
toExpression() {
return this.name;
}

toJavaScript() {
return `(${this.name}) => ${this.name}`;
}
}

class OperationExpression {
constructor(operator, operands) {
this.identifiers = new Set();
this.operator = operator;
this.operands = operands;
for (const operand of operands) {
if (operand instanceof VariableExpression) {
this.identifiers.add(operand.name);
} else if (operand instanceof OperationExpression) {
const names = this.identifiers.union(operand.identifiers);
this.identifiers = names;
}
}
}

interpret(context) {
const toValues = (operand) => operand.interpret(context);
const args = this.operands.map((x) => toValues(x));
const args = this.operands.map((x) => x.interpret(context));
const operator = OPERATORS[this.operator];
if (!operator) throw new Error(`Unknown operator: ${operator}`);
if (this.operator.length > 1) return operator(...args);
return args.reduce(operator);
}

toJavaScript(args) {
const params = args || [];
const sub = this.operands.map((x) => x.toJavaScript(params));
const expression = '(' + sub.join(this.operator) + ')';
if (args) return expression;
const header = '(' + params.join(', ') + ')';
return header + ' => ' + expression;
toExpression() {
const list = this.operands.map((x) => x.toExpression());
return '(' + list.join(this.operator) + ')';
}

toJavaScript() {
const parameters = Array.from(this.identifiers);
const header = '(' + parameters.join(', ') + ')';
return header + ' => ' + this.toExpression();
}
}

Expand Down
40 changes: 21 additions & 19 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 1 addition & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,7 @@
"eslint-config-metarhia": "^9.1.1",
"metatests": "^0.9.0",
"prettier": "^3.4.1",
"typescript": "^5.7.2"
},
"dependencies": {
"typescript": "^5.7.2",
"metavm": "^1.4.2"
}
}

0 comments on commit 5b16a59

Please sign in to comment.