Cobold
Cobold

Reputation: 2613

Could .NET be parsed and evaluated at runtime

I thought it would be fun if I could write vb.net or c# code at runtime and the interpreter would automatically parse it like python does it, so I made a little program, which would do something similar. Basically it looks like this:

InputArgs = Console.ReadLine()
ParseInput(InputArgs.Split(" "))

Private Sub ParseInput(Args as List(Of String), Optional TempArgs as List(Of String))
Dim arg as string = Args(0)
If arg = ".." then
 ...
elseif arg = ".." then
 ...
end if
End Sub

I know it's not a good system, but it show's the basics. So my question is: Is it possible to make vb.net or c# like python - interpreted at runtime?

Upvotes: 3

Views: 2475

Answers (6)

MarkJ
MarkJ

Reputation: 30398

Are you reinventing LinqPad?

LinqPad is a free ergonomic C#/VB/F# scratchpad that instantly executes any expression, statement block or program with rich output formatting. It's excellent.

If you really want to develop your own, have a look at some of the similar existing questions one two three four...

Upvotes: 1

sehe
sehe

Reputation: 392931

This already exists in a fair number of shapes and forms:

Mono.CSharp

Mono has the Mono.CSharp assembly, which you can reference to do whatever CSharp.exe (A C# 'interpreter' or interactive shell, if you will) can do:

void ReadEvalPrintLoopWith (ReadLiner readline)
{
    string expr = null;
    while (!InteractiveBase.QuitRequested){
            string input = readline (expr == null);
            if (input == null)
                return;

            if (input == "")
                continue;

            expr = expr == null ? input : expr + "\n" + input;

            expr = Evaluate (expr);
    } 
}

Needless to say this works on MS.Net too (of course, that's the point about portable .Net).

Full sources here on github - just as the rest of Mono, in fact.

DLR

Several DLR languages have been implemented, including but not limited to

It will allow you to evaluate python/ruby code on the fly in the .NET framework.

Roslyn

Microsoft has published Roslyn as a CTP (preview). It can basically do the same stuff as the Mono REPL (first item), and (much) more. But it is a preview still.

Upvotes: 5

Alexander Mavrinsky
Alexander Mavrinsky

Reputation: 465

Don't have much time to give you a proper answer, but here is eval code from one of my old projects:

        CSharpCodeProvider c = new CSharpCodeProvider();
        ICodeCompiler icc = c.CreateCompiler();
        CompilerParameters cp = new CompilerParameters();

        cp.ReferencedAssemblies.Add("system.dll");
        cp.ReferencedAssemblies.Add("system.xml.dll");
        cp.ReferencedAssemblies.Add("system.data.dll");
        cp.ReferencedAssemblies.Add("system.windows.forms.dll");
        cp.ReferencedAssemblies.Add("system.drawing.dll");

        cp.CompilerOptions = "/t:library";
        cp.GenerateInMemory = true;

        StringBuilder sb = new StringBuilder("");
        sb.Append("using System;\n");
        sb.Append("using System.Xml;\n");
        sb.Append("using System.Data;\n");
        sb.Append("using System.Data.SqlClient;\n");
        sb.Append("using System.Windows.Forms;\n");
        sb.Append("using System.Drawing;\n");

        sb.Append("namespace CSCodeEvaler{ \n");
        sb.Append("public class CSCodeEvaler{ " + csCode + "} }");

        CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
        if (cr.Errors.Count > 0)
        {
            MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText,
               "Error evaluating cs code", MessageBoxButtons.OK,
               MessageBoxIcon.Error);
            return null;
        }

        System.Reflection.Assembly a = cr.CompiledAssembly;
        object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");

        Type t = o.GetType();
        MethodInfo mi = t.GetMethod("Transform");

        return mi;

Original variant of this code was taken from: http://www.codeproject.com/KB/cs/evalcscode.aspx

It compiles some C# code (code should be in csCode variable), then tries to find Transform() method in it and returns its MethodInfo, so we can execute it.

But remember, every time you call this code, a new assembly will be loaded, so don't use it too often.

Also, as Prescott said - try Roslyn

Hope this will help. Sorry that haven't provided code example more specific to your question.

PS. If you want some interactive window, there are third party controls for this (use google to find, because I don't remember exact product names)

Upvotes: 1

Roy Dictus
Roy Dictus

Reputation: 33139

It can be, but it would be a lot of work.

One way would be to write a parser + interpreter yourself. To create the parser, you'd need a grammar definition of the input language, such as C#. The C# grammar is very complex, mind you.

Another way is to dynamically compile C# code. Here is an example of how to do that: http://www.voidspace.org.uk/ironpython/dynamically_compiling.shtml and http://blogs.msdn.com/b/saveenr/archive/2009/08/11/a-walkthrough-of-dynamically-compiling-c-code.aspx.

Good luck!

Upvotes: 2

SBoss
SBoss

Reputation: 9215

Not that I know.. But as a hack you could make a textarea which has a TextChanged event handler which calls the compiler program (not sure where it is).

Upvotes: 0

TomTom
TomTom

Reputation: 62093

So my question is: Is it possible to make vb.net or c# like python - interpreted at runtime?

Sure. Start writing an interpreter for it and then you can interpret it. Start with a nice syntax parser. Then go on from there.

Upvotes: -1

Related Questions