Created
November 12, 2012 16:14
-
-
Save snipsnipsnip/4060228 to your computer and use it in GitHub Desktop.
ics.cs is a C# repl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
using Microsoft.CSharp; | |
using System.CodeDom.Compiler; | |
using System.Reflection; | |
using System.IO; | |
namespace ics | |
{ | |
class Program | |
{ | |
const string classname = "ClassNameWhichMustNotBeNamed"; | |
const string methodname = "MethodNameWhichMustNotBeNamed"; | |
static string template = | |
String.Format( | |
"using {{0}};public static class {0}{{{{ public static object {1}(List<string> useList, Dictionary<string, object> dict, object _) {{{{object ret=\n{{1}}; return ret; }}}} }}}}", | |
classname, methodname); | |
static void Main(string[] args) | |
{ | |
CSharpCodeProvider p = new CSharpCodeProvider(); | |
CompilerParameters param = new CompilerParameters(); | |
param.GenerateInMemory = true; | |
List<string> useList = new List<string>(); | |
Dictionary<string, object> dict = new Dictionary<string, object>(); | |
object last = null; | |
useList.Add("System"); | |
useList.Add("System.Collections.Generic"); | |
for (; ; ) | |
{ | |
Console.Write("> "); | |
string line = Console.ReadLine(); | |
if (line == null) break; | |
else if (line == "") continue; | |
if (line == "help") | |
{ | |
Console.WriteLine("手抜き C# インタプリタ"); | |
Console.WriteLine("エラー表示の左の数字は入力の桁数です"); | |
Console.WriteLine("定義済みの変数:\n _: 前回の返り値か例外\n useList: using節で使う名前空間のリスト\n dict: ご自由にお使いください"); | |
Console.WriteLine("tips:\n ・末尾のセミコロンは省略可\n ・void型の文はこうすると動く"); | |
Console.WriteLine(" > null; Console.WriteLine(\"fuga\")"); | |
continue; | |
} | |
string code = String.Format(template, String.Join(";using ", useList.ToArray()), line); | |
CompilerResults r = p.CompileAssemblyFromSource(param, code); | |
//System.Reflection.Assembly.LoadFile("maze.exe"); | |
if (r.NativeCompilerReturnValue != 0) | |
{ | |
foreach (CompilerError err in r.Errors) | |
{ | |
Console.WriteLine("{0}: {1}", err.Column, err.ErrorText); | |
} | |
} | |
else | |
{ | |
MethodInfo m = r.CompiledAssembly.GetType(classname).GetMethod(methodname); | |
try | |
{ | |
object result = m.Invoke(null, new object[] { useList, dict, last }); | |
if (result != null) | |
{ | |
Console.WriteLine(result); | |
last = result; | |
} | |
} | |
catch (TargetInvocationException e) | |
{ | |
Console.WriteLine("例外が飛びました (変数 _ に入っています)"); | |
last = e.InnerException; | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment