Artifact Content
Not logged in

Artifact 4d8d31e11afa4a19868efb288e0be5ea12d94bcd


     1  /**
     2   * Authors: k.inaba
     3   * License: NYSL 0.9982 (http://www.kmonos.net/nysl/)
     4   *
     5   * Read-Eval-Print-Loop
     6   */
     7  module polemy.repl;
     8  import polemy.failure;
     9  import polemy.layer;
    10  import polemy.eval;
    11  import polemy.runtime;
    12  import polemy.value;
    13  import polemy.valueconv;
    14  import std.stdio;
    15  import std.string;
    16  
    17  enum VersionNoMajor = 0; /// Version Number
    18  enum VersionNoMinor = 1; /// Version Number
    19  enum VersionNoRev   = 0; /// Version Number
    20  
    21  /// Read-Eval-Print-Loop
    22  
    23  class REPL
    24  {
    25  	/// Load the prelude environment
    26  	this(string[] args)
    27  	{
    28  		ev = new Evaluator;
    29  		ev.globalContext.set("argv", ValueLayer, d2polemy(args));
    30  		enrollRuntimeLibrary(ev);
    31  	}
    32  
    33  	/// Print the version number etc.
    34  	void greet()
    35  	{
    36  		writefln("Welcome to Polemy %d.%d.%d", VersionNoMajor, VersionNoMinor, VersionNoRev);
    37  	}
    38  
    39  	/// Run one file on the global scope
    40  	void runFile(string filename)
    41  	{
    42  		ev.evalFile(filename);
    43  	}
    44  
    45  	/// Repeat the singleInteraction
    46  	void replLoop()
    47  	{
    48  		while( singleInteraction() ) {}
    49  	}
    50  
    51  	/// Read one line from stdin, and do some reaction
    52  	bool singleInteraction()
    53  	{
    54  		writef(">> ", lineno);
    55  		string line = readln();
    56  		if( line.startsWith("exit") || line.startsWith("quit") )
    57  			return false;
    58  		try {
    59  			if( tryRun(line) )
    60  				writeln(lastVal);
    61  		} catch(Throwable e) {
    62  			writeln(e);
    63  		}
    64  		return true;
    65  	}
    66  
    67  private:
    68  	Evaluator ev;
    69  	Table ctx;
    70  	string buf;
    71  	Value  lastVal;
    72  	int lineno = 1;
    73  	int nextlineno = 1;
    74  
    75  	bool tryRun( string s )
    76  	{
    77  		scope(failure)
    78  			{ buf = ""; lineno = nextlineno; }
    79  
    80  		buf ~= s;
    81  		nextlineno ++;
    82  		try 
    83  			{ lastVal = ev.evalString(buf, "<REPL>", lineno); }
    84  		catch( UnexpectedEOF )
    85  			{ return false; } // wait
    86  		buf = "";
    87  		lineno = nextlineno;
    88  		return true;
    89  	}
    90  }