Artifact Content
Not logged in

Artifact d5ef45952651bda8bde2f762a41dc253341753f7


     1  /**
     2   * Authors: k.inaba
     3   * License: NYSL 0.9982 (http://www.kmonos.net/nysl/
     4   *
     5   * Entry point for Polemy interpreter.
     6   */
     7  
     8  import std.stdio;
     9  import std.algorithm;
    10  import polemy.value;
    11  import polemy.lex;
    12  import polemy.parse;
    13  import polemy.ast;
    14  import polemy.eval;
    15  
    16  /// Tenuki Read-Eval-Print-Loop
    17  class REPL
    18  {
    19  	Table ctx;
    20  	string buf;
    21  	Value  lastVal;
    22  	int lineno = 1;
    23  	int nextlineno = 1;
    24  	this() { ctx = createGlobalContext(); }
    25  	this(string filename) {
    26  		ctx = createGlobalContext();
    27  		eval(parseFile(filename), ctx, false, "@v");
    28  	}
    29  
    30  	bool tryRun( string s )
    31  	{
    32  		scope(failure)
    33  			{ buf = ""; lineno = nextlineno; }
    34  
    35  		buf ~= s;
    36  		nextlineno ++;
    37  		try 
    38  			{ lastVal = eval(parseString(buf, "<REPL>", lineno), ctx, false, "@v"); }
    39  		catch( UnexpectedEOF )
    40  			{ return false; } // wait
    41  		buf = "";
    42  		lineno = nextlineno;
    43  		return true;
    44  	}
    45  
    46  	bool singleInteraction()
    47  	{
    48  		writef(">> ", lineno);
    49  		string line = readln();
    50  		if( line.startsWith("exit") || line.startsWith("quit") )
    51  			return false;
    52  		try {
    53  			if( tryRun(line) )
    54  			{
    55  				// for debugging.
    56  				//try {
    57  				//	writeln(tableToAST("@v", cast(Table)lastVal));
    58  				//} catch(Throwable e) {
    59  				//	writeln(e);
    60  				//}
    61  				writeln(lastVal);
    62  			}
    63  		} catch(Throwable e) {
    64  			writeln(e);
    65  		}
    66  		return true;
    67  	}
    68  }
    69  
    70  /// Entry point. If args.length==1, invoke REPL.
    71  /// If args.length==3 && args[1]=="-l" read args[2] and invoke REPL.
    72  /// Otherwise interpret the argument as a filename.
    73  void main( string[] args )
    74  {
    75  	if( args.length <= 1 )
    76  	{
    77  		writeln("Welcome to Polemy 0.1.0");
    78  		for(auto r = new REPL; r.singleInteraction();) {}
    79  	}
    80  	else if( args.length>=3 && args[1]=="-l" )
    81  	{
    82  		writeln("Welcome to Polemy 0.1.0");
    83  		for(auto r = new REPL(args[2]); r.singleInteraction();) {}
    84  	}
    85  	else
    86  	{
    87  		evalFile(args[1]);
    88  	}
    89  }