Artifact Content
Not logged in

Artifact b6f89f38f0a1626d03407b97a2d9b2df3867472c


     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  				writeln(lastVal);
    55  		} catch(Throwable e) {
    56  			writeln(e);
    57  		}
    58  		return true;
    59  	}
    60  }
    61  
    62  /// Entry point. If args.length==1, invoke REPL.
    63  /// If args.length==3 && args[1]=="-l" read args[2] and invoke REPL.
    64  /// Otherwise interpret the argument as a filename.
    65  void main( string[] args )
    66  {
    67  	if( args.length <= 1 )
    68  	{
    69  		writeln("Welcome to Polemy 0.1.0");
    70  		for(auto r = new REPL; r.singleInteraction();) {}
    71  	}
    72  	else if( args.length>=3 && args[1]=="-l" )
    73  	{
    74  		writeln("Welcome to Polemy 0.1.0");
    75  		for(auto r = new REPL(args[2]); r.singleInteraction();) {}
    76  	}
    77  	else
    78  	{
    79  		evalFile(args[1]);
    80  	}
    81  }