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