RootScope and support for Built in function has been added

This commit is contained in:
Sameer Rahmani 2019-12-19 22:57:04 +00:00
parent 709346311a
commit 79312f29ff
19 changed files with 401 additions and 283 deletions

View File

@ -0,0 +1,34 @@
package serene.simple;
import java.util.HashMap;
import java.util.Map;
public abstract class BaseScope {
private final Map<String, Object> symbolsMapping = new HashMap<String, Object>();
private final BaseScope parent;
public BaseScope() {
this(null);
}
public BaseScope(BaseScope parent) {
this.parent = parent;
}
public Object lookupSymbol(String symbolName) {
if (this.symbolsMapping.containsKey(symbolName)) {
return this.symbolsMapping.get(symbolName);
}
else if (this.parent != null) {
return this.parent.lookupSymbol(symbolName);
}
else {
throw new RuntimeException(String.format("Variable '%s' is not defined in this scope.",
symbolName));
}
}
public void insertSymbol(String symbolName, Object symbolValue) {
this.symbolsMapping.put(symbolName, symbolValue);
}
}

View File

@ -1,15 +1,15 @@
package serene.simple; package serene.simple;
public class DefSpecialForm extends SpecialForm { public class DefSpecialForm extends SpecialForm {
public DefSpecialForm(ListNode<Node> listNode) { public DefSpecialForm(ListNode<Node> listNode) {
super(listNode); super(listNode);
} }
@Override @Override
public Object eval(Scope scope) { public Object eval(BaseScope scope) {
SymbolNode sym = (SymbolNode) this.node.rest().first(); SymbolNode sym = (SymbolNode) this.node.rest().first();
scope.insertSymbol(sym.name, scope.insertSymbol(sym.name,
this.node.rest().rest().first().eval(scope)); this.node.rest().rest().first().eval(scope));
return ListNode.EMPTY; return ListNode.EMPTY;
} }
} }

View File

@ -4,7 +4,7 @@ public class FalseNode extends Node {
public boolean isTruthy = false; public boolean isTruthy = false;
@Override @Override
public Object eval(Scope scope) { public Object eval(BaseScope scope) {
return Boolean.FALSE; return Boolean.FALSE;
} }

View File

@ -3,47 +3,47 @@ package serene.simple;
import java.util.function.Function; import java.util.function.Function;
public class FnSpecialForm extends SpecialForm { public class FnSpecialForm extends SpecialForm {
public FnSpecialForm(ListNode<Node> paramsAndBody) { public FnSpecialForm(ListNode<Node> paramsAndBody) {
super(paramsAndBody); super(paramsAndBody);
} }
@Override @Override
public Object eval(final Scope parentScope) { public Object eval(final BaseScope parentScope) {
final ListNode<Node> formalParams = (ListNode<Node>) this.node.rest().first(); final ListNode<Node> formalParams = (ListNode<Node>) this.node.rest().first();
final ListNode<Node> body = this.node.rest().rest(); final ListNode<Node> body = this.node.rest().rest();
return new Function<Object, Object>() { return new Function<Object, Object>() {
@Override @Override
public Object apply(Object arguments) { public Object apply(Object arguments) {
Object[] args = (Object[]) arguments; Object[] args = (Object[]) arguments;
Scope scope = new Scope(parentScope); Scope scope = new Scope(parentScope);
if (args.length != formalParams.length) { if (args.length != formalParams.length) {
throw new RuntimeException(String.format("Wrong number of arguments. Expected: %s, Got: %s.", throw new RuntimeException(String.format("Wrong number of arguments. Expected: %s, Got: %s.",
formalParams.length, formalParams.length,
args.length)); args.length));
} }
// Map parameter values to formal parameter names // Map parameter values to formal parameter names
int i = 0; int i = 0;
for (Node param : formalParams) { for (Node param : formalParams) {
SymbolNode paramSymbol = (SymbolNode) param; SymbolNode paramSymbol = (SymbolNode) param;
scope.insertSymbol(paramSymbol.name, args[i]); scope.insertSymbol(paramSymbol.name, args[i]);
i++; i++;
} }
// Evaluate body // Evaluate body
Object output = null; Object output = null;
for (Node node : body) { for (Node node : body) {
output = node.eval(scope); output = node.eval(scope);
} }
return output; return output;
} }
@Override @Override
public String toString() { public String toString() {
return "Function@" + System.identityHashCode(this); return "Function@" + System.identityHashCode(this);
} }
}; };
} }
} }

View File

@ -2,7 +2,7 @@ package serene.simple;
public class FunctionNode extends Node { public class FunctionNode extends Node {
@Override @Override
public Object eval(Scope scope) { public Object eval(BaseScope scope) {
return this; return this;
} }

View File

@ -2,24 +2,23 @@ package serene.simple;
public class IfSpecialForm extends SpecialForm { public class IfSpecialForm extends SpecialForm {
private Node pred;
private Node ifNode;
private Node elseNode;
private Node pred; public IfSpecialForm(ListNode<Node> l) {
private Node ifNode; super(l);
private Node elseNode; this.pred = l.rest().first();
this.ifNode = l.rest().rest().first();
this.elseNode = l.rest().rest().rest().first();
}
public IfSpecialForm(ListNode<Node> l) { @Override
super(l); public Object eval(final BaseScope scope) {
this.pred = l.rest().first(); Object result = this.pred.eval(scope);
this.ifNode = l.rest().rest().first(); if (result == null || (result instanceof Boolean && (Boolean) result == false)) {
this.elseNode = l.rest().rest().rest().first(); return this.elseNode.eval(scope);
}
@Override
public Object eval(final Scope scope) {
Object result = this.pred.eval(scope);
if (result == null || (result instanceof Boolean && (Boolean) result == false)) {
return this.elseNode.eval(scope);
}
return this.ifNode.eval(scope);
} }
return this.ifNode.eval(scope);
}
} }

View File

@ -4,107 +4,125 @@ import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.function.Function; import java.util.function.Function;
import serene.simple.builtin.AFn;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
public class ListNode<T extends Node> extends Node implements Iterable<T> { public class ListNode<T extends Node> extends Node implements Iterable<T> {
public static final ListNode<?> EMPTY = new ListNode<>(); public static final ListNode<?> EMPTY = new ListNode<>();
public final T first; public final T first;
public final ListNode<T> rest; public final ListNode<T> rest;
public final int length; public final int length;
public ListNode() { public ListNode() {
this.first = null; this.first = null;
this.rest = null; this.rest = null;
this.length = 0; this.length = 0;
}
public ListNode(T f, ListNode<T> r) {
this.first = f;
this.rest = r;
this.length = r.length + 1;
}
@SafeVarargs
public static <T extends Node> ListNode<T> list(T... objs) {
return list(asList(objs));
}
public static <T extends Node> ListNode<T> list(List<T> objs) {
ListNode<T> l = (ListNode<T>) EMPTY;
for (int i = objs.size() - 1; i >= 0; i--) {
l = l.cons(objs.get(i));
}
return l;
}
public ListNode<T> cons(T node) {
return new ListNode<T>(node, this);
}
@Override
public Object eval(BaseScope scope) {
Object f = this.first().eval(scope);
List<Object> args = new ArrayList<Object>();
for (T node : this.rest()) {
args.add(node.eval(scope));
} }
public ListNode(T f, ListNode<T> r) { if (f instanceof AFn) {
this.first = f; return evalBuiltin(scope, (AFn) f, args);
this.rest = r;
this.length = r.length + 1;
} }
else {
@SafeVarargs return evalFn(scope, (Function<Object, Object>) f, args);
public static <T extends Node> ListNode<T> list(T... objs) {
return list(asList(objs));
} }
}
public static <T extends Node> ListNode<T> list(List<T> objs) { public Object evalBuiltin(BaseScope scope, AFn fn, List<Object> args) {
ListNode<T> l = (ListNode<T>) EMPTY; fn.setArguments(args);
for (int i = objs.size() - 1; i >= 0; i--) { return fn.eval(scope);
l = l.cons(objs.get(i)); }
public Object evalFn(BaseScope scope, Function<Object, Object> fn, List<Object> args) {
return fn.apply(args.toArray());
}
public T first() {
if (this != EMPTY) {
return this.first;
}
return null;
}
public ListNode<T> rest() {
if (this != EMPTY) {
return this.rest;
}
return (ListNode<T>) EMPTY;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private ListNode<T> l = ListNode.this;
@Override
public boolean hasNext() {
return this.l != EMPTY;
}
@Override
public T next() {
if (this.l == EMPTY) {
return null;
} }
return l; T first = this.l.first;
this.l = this.l.rest;
return first;
}
@Override
public void remove() {
throw new SereneException("Iterator is immutable");
}
};
}
public String toString() {
if (this.length == 0) {
return "()";
} }
public ListNode<T> cons(T node) { String output = "(" + this.first();
return new ListNode<T>(node, this); for(Node x : this.rest()) {
output = output + " " + x.toString();
} }
@Override return output + ")";
public Object eval(Scope scope) { }
Function<Object, Object> f = (Function) this.first().eval(scope);
List<Object> args = new ArrayList<Object>();
for (T node : this.rest()) {
args.add(node.eval(scope));
}
return f.apply(args.toArray());
}
public T first() {
if (this != EMPTY) {
return this.first;
}
return null;
}
public ListNode<T> rest() {
if (this != EMPTY) {
return this.rest;
}
return (ListNode<T>) EMPTY;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private ListNode<T> l = ListNode.this;
@Override
public boolean hasNext() {
return this.l != EMPTY;
}
@Override
public T next() {
if (this.l == EMPTY) {
return null;
}
T first = this.l.first;
this.l = this.l.rest;
return first;
}
@Override
public void remove() {
throw new SereneException("Iterator is immutable");
}
};
}
public String toString() {
if (this.length == 0) {
return "()";
}
String output = "(" + this.first();
for(Node x : this.rest()) {
output = output + " " + x.toString();
}
return output + ")";
}
} }

View File

@ -10,62 +10,62 @@ import java.io.FileInputStream;
public class Main { public class Main {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
if (args.length == 0) { if (args.length == 0) {
startRepl(); startRepl();
return; return;
}
runSerene(args[0]);
} }
runSerene(args[0]);
}
private static void startRepl() throws IOException { private static void startRepl() throws IOException {
Scope rootScope = Scope.getRootScope(); BaseScope rootScope = new RootScope();
Console console = System.console(); Console console = System.console();
System.out.println("Serene 'simple' v0.1.0"); System.out.println("Serene 'simple' v0.1.0");
while(true) { while(true) {
String inputData = console.readLine("serene-> "); String inputData = console.readLine("serene-> ");
//String inputData = "(fn (x) x)"; //String inputData = "(fn (x) x)";
if (inputData == null) break; if (inputData == null) break;
ByteArrayInputStream inputStream = new ByteArrayInputStream(inputData.getBytes()); ByteArrayInputStream inputStream = new ByteArrayInputStream(inputData.getBytes());
try { try {
ListNode<Node> nodes = Reader.read(inputStream); ListNode<Node> nodes = Reader.read(inputStream);
Object result = ListNode.EMPTY; Object result = ListNode.EMPTY;
for (Node n : nodes) {
result = n.eval(rootScope);
}
if (result != ListNode.EMPTY) {
System.out.print(";; ");
if (result == null) {
System.out.println("nil");
}
else {
System.out.println(result.toString());
}
}
}
catch(Exception e) {
System.out.println("Error: ");
e.printStackTrace(System.out);
}
}
}
private static void runSerene(String filePath) throws IOException {
Scope rootScope = Scope.getRootScope();
ListNode<Node> nodes = Reader.read(new FileInputStream(filePath));
for (Node n : nodes) { for (Node n : nodes) {
n.eval(rootScope); result = n.eval(rootScope);
} }
if (result != ListNode.EMPTY) {
System.out.print(";; ");
if (result == null) {
System.out.println("nil");
}
else {
System.out.println(result.toString());
}
}
}
catch(Exception e) {
System.out.println("Error: ");
e.printStackTrace(System.out);
}
} }
}
private static void runSerene(String filePath) throws IOException {
BaseScope rootScope = new RootScope();
ListNode<Node> nodes = Reader.read(new FileInputStream(filePath));
for (Node n : nodes) {
n.eval(rootScope);
}
}
} }

View File

@ -4,7 +4,7 @@ public class NilNode extends Node {
public boolean isTruthy = false; public boolean isTruthy = false;
@Override @Override
public Object eval(Scope scope) { public Object eval(BaseScope scope) {
return null; return null;
} }

View File

@ -1,17 +1,17 @@
package serene.simple; package serene.simple;
public abstract class Node { public abstract class Node {
public boolean isTruthy = true; public boolean isTruthy = true;
public abstract Object eval(Scope scope); public abstract Object eval(BaseScope scope);
public boolean equals(Node n) { public boolean equals(Node n) {
return this == n; return this == n;
} }
@Override @Override
public String toString() { public String toString() {
String className = this.getClass().getName(); String className = this.getClass().getName();
return String.format("%s<%s>", className, System.identityHashCode(this)); return String.format("%s<%s>", className, System.identityHashCode(this));
} }
} }

View File

@ -8,7 +8,7 @@ public class NumberNode extends Node {
} }
@Override @Override
public Object eval(Scope scope) { public Object eval(BaseScope scope) {
return this.value; return this.value;
} }

View File

@ -1,21 +1,16 @@
package serene.simple; package serene.simple;
public class QuoteSpecialForm extends SpecialForm { public class QuoteSpecialForm extends SpecialForm {
public QuoteSpecialForm(ListNode<Node> node) throws SereneException {
super(node);
// public QuoteSpecialForm(Node node) { if (this.node.rest().length != 1) {
// this.x = node; throw new SereneException("quote expects only one arguement");
// }
public QuoteSpecialForm(ListNode<Node> node) throws SereneException {
super(node);
if (this.node.rest().length != 1) {
throw new SereneException("quote expects only one arguement");
}
} }
}
@Override @Override
public Object eval(final Scope scope) { public Object eval(final BaseScope scope) {
return this.node.rest().first(); return this.node.rest().first();
} }
} }

View File

@ -0,0 +1,42 @@
package serene.simple;
import java.util.HashMap;
import java.util.Map;
import serene.simple.builtin.AFn;
import serene.simple.builtin.PrintlnFn;
public class RootScope extends BaseScope {
private final BaseScope parent;
private final HashMap<String, Object> symbolsMapping = new HashMap<String, Object>() {{
put("println", new PrintlnFn());
}};
// "+", PlusFn,
// "-", MinusFn,
// "*", TimesFn,
// "/", ObelusFn,
// "mod", ModFn,
// "now", NowFn,
public RootScope() {
this.parent = null;
System.out.println(this.symbolsMapping.get("println"));
}
@Override
public Object lookupSymbol(String symbolName) {
if (this.symbolsMapping.containsKey(symbolName)) {
return this.symbolsMapping.get(symbolName);
}
else {
throw new RuntimeException(String.format("Variable '%s' is not defined in this scope.",
symbolName));
}
}
public void insertSymbol(String symbolName, Object symbolValue) {
this.symbolsMapping.put(symbolName, symbolValue);
}
}

View File

@ -1,38 +1,14 @@
package serene.simple; package serene.simple;
import java.util.HashMap;
public class Scope { public class Scope extends BaseScope{
private final HashMap<String, Object> symbolsMapping = new HashMap<String, Object>(); private final BaseScope parent;
private final Scope parent;
private static final Scope root = new Scope(null);
public Scope() { public Scope() {
this(null); this(new RootScope());
} }
public Scope(Scope parent) { public Scope(BaseScope parent) {
this.parent = parent; this.parent = parent;
} }
public Object lookupSymbol(String symbolName) {
if (this.symbolsMapping.containsKey(symbolName)) {
return this.symbolsMapping.get(symbolName);
}
else if (this.parent != null) {
return this.parent.lookupSymbol(symbolName);
}
else {
throw new RuntimeException(String.format("Variable '%s' is not defined in this scope.",
symbolName));
}
}
public void insertSymbol(String symbolName, Object symbolValue) {
this.symbolsMapping.put(symbolName, symbolValue);
}
public static Scope getRootScope() {
return Scope.root;
}
} }

View File

@ -2,37 +2,37 @@ package serene.simple;
public class SpecialForm extends Node { public class SpecialForm extends Node {
private static final SymbolNode DEF = new SymbolNode("def"); private static final SymbolNode DEF = new SymbolNode("def");
private static final SymbolNode FN = new SymbolNode("fn"); private static final SymbolNode FN = new SymbolNode("fn");
private static final SymbolNode IF = new SymbolNode("if"); private static final SymbolNode IF = new SymbolNode("if");
private static final SymbolNode QUOTE = new SymbolNode("quote"); private static final SymbolNode QUOTE = new SymbolNode("quote");
public ListNode<Node> node; public ListNode<Node> node;
public SpecialForm() {} public SpecialForm() {}
public SpecialForm(ListNode<Node> node) { public SpecialForm(ListNode<Node> node) {
this.node = node; this.node = node;
}
public static Node check(ListNode<Node> l) throws SereneException {
if (l == ListNode.EMPTY) {
return l;
} else if (l.first().equals(DEF)) {
return new DefSpecialForm(l);
} else if (l.first().equals(FN)) {
return new FnSpecialForm(l);
} else if (l.first().equals(IF)) {
return new IfSpecialForm(l);
} else if (l.first().equals(QUOTE)) {
return new QuoteSpecialForm(l);
} }
public static Node check(ListNode<Node> l) throws SereneException { return l;
if (l == ListNode.EMPTY) { }
return l;
} else if (l.first().equals(DEF)) {
return new DefSpecialForm(l);
} else if (l.first().equals(FN)) {
return new FnSpecialForm(l);
} else if (l.first().equals(IF)) {
return new IfSpecialForm(l);
} else if (l.first().equals(QUOTE)) {
return new QuoteSpecialForm(l);
}
return l; @Override
} public Object eval(BaseScope scope) throws SereneException {
throw new SereneException("Can't use SpecialForm directly");
@Override }
public Object eval(Scope scope) throws SereneException {
throw new SereneException("Can't use SpecialForm directly");
}
} }

View File

@ -22,7 +22,7 @@ public class SymbolNode extends Node {
} }
@Override @Override
public Object eval(Scope scope) { public Object eval(BaseScope scope) {
return scope.lookupSymbol(this.name); return scope.lookupSymbol(this.name);
} }

View File

@ -2,7 +2,7 @@ package serene.simple;
public class TrueNode extends Node { public class TrueNode extends Node {
@Override @Override
public Object eval(Scope scope) { public Object eval(BaseScope scope) {
return true; return true;
} }

View File

@ -0,0 +1,31 @@
package serene.simple.builtin;
import java.util.Collections;
import java.util.List;
import serene.simple.Node;
public abstract class AFn extends Node {
private List<Object> args;
public void setArguments() {
this.args = Collections.EMPTY_LIST;
}
public void setArguments(List<Object> args) {
this.args = args;
}
public List<Object> arguments() {
return this.args;
}
public abstract String fnName();
@Override
public String toString() {
return String.format("BuiltinFn<%s>", this.fnName());
}
}

View File

@ -0,0 +1,23 @@
package serene.simple.builtin;
import serene.simple.BaseScope;
public class PrintlnFn extends AFn {
public String fnName() {
return "println";
};
public Object eval(BaseScope scope) {
String output = "";
for(Object x: this.arguments()) {
output = String.format(
"%s %s", output,
(String) x.toString());
}
System.out.println(output);
return null;
}
}