Artifact Content
Not logged in

Artifact 81cf3e2a44d632391bc8befb1e80183ef0434748


/**
 * Authors: k.inaba
 * License: NYSL 0.9982 (http://www.kmonos.net/nysl/
 *
 * Entry point for Polemy interpreter.
 */

import std.stdio;
import std.algorithm;
import polemy.value;
import polemy.lex;
import polemy.parse;
import polemy.ast;
import polemy.eval;

class REPL
{
	Table ctx;
	string buf;
	Value  lastVal;
	int lineno = 1;
	int nextlineno = 1;
	this() { ctx = createGlobalContext(); }

	bool tryRun( string s )
	{
		nextlineno ++;
		buf ~= s;
		try {
			AST a = parseString(buf, "<REPL>", lineno);
			buf = "";
			lineno = nextlineno;
			lastVal = eval(a, ctx);
		} catch( LexException ) {
			// always EOF exception, so wait next
			return false;
		} catch( ParseException e ) {
			if( find(e.msg, "EOF")!="" ) // ultra ad-hoc
				return false;
			buf = "";
			lineno = nextlineno;
			throw e;
		}
		return true;
	}

	bool singleInteraction()
	{
		writef(">> ", lineno);
		string line = readln();
		if( line.startsWith("exit") || line.startsWith("quit") )
			return false;
		try {
			if( tryRun(line) )
				writeln(lastVal);
		} catch(Throwable e) {
			writeln(e);
		}
		return true;
	}
}

version(unittest) {
	bool success = false;
	static ~this(){ if(!success){writeln("(press enter to exit)"); readln();} }
}

void main( string[] args )
{
	version(unittest) success=true;

	if( args.length <= 1 )
	{
		writeln("Welcome to Polemy 0.1.0");
		for(auto r = new REPL; r.singleInteraction();) {}
	}
	else
	{
		evalFile(args[1]);
	}
}