5

I am looking at creating a small interpreter for C# that I could load in some applications. Something that could be able to run things like this:

 > var arr = new[] { 1.5,2.0 };
                                 arr = { 1.5, 2.0 }
 > var sum = arr.Sum();
                                 sum = 3.5

And so I was thinking this could be achieved by creating a dictionary of all the variables and their types and then compile each of the row as they come, and then execute the function, get the result and stick it in the dictionary of variables.

However, it seems to me that this may be actually quite difficult to build and possibly very inefficient.

Then I thought that Powershell was doing what I needed. But how is it done? Can anyone enlighten me as to how Powershell works or what a good way would be to build a .Net interpreter?

2
  • 2
    somthing like this ? Or perhaps roslyn Commented Sep 10, 2012 at 13:21
  • @Daniel: Yes! Something like this looks pretty cool! Commented Sep 10, 2012 at 13:26

3 Answers 3

5

How about you host the PowerShell engine in your application and let it do the interpreting for you? For example:

private static void Main(string[] args)
{
  // Call the PowerShell.Create() method to create an 
  // empty pipeline.
  PowerShell ps = PowerShell.Create();

  // Call the PowerShell.AddScript(string) method to add 
  // some PowerShell script to execute.
  ps.AddScript("$arr = 1.5,2.0"); # Execute each line read from prompt

  // Call the PowerShell.Invoke() method to run the 
  // commands of the pipeline.
  foreach (PSObject result in ps.Invoke())
  {
    Console.WriteLine(result.ToString());
  } 
} 

If your goal is to learn how to build an interpreter, have a look at the interpreter pattern.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the tip, I looked through the Powershell dll. That code is indeed massive, and they have their very own parsing mechanism that doesn't go through any kind of IL compiling / assembly loading. It's all done through dynamic parsing and dynamic invokes.
3

Look at either Roslyn http://msdn.microsoft.com/en-US/roslyn or Mono Compiler http://www.mono-project.com/CSharp_Compiler . Both should be able to do what you are looking for

Comments

3

Somthing like this? Or perhaps Roslyn(http://msdn.microsoft.com/en-gb/roslyn)

Added comment as answer, as it seems more useful than I first thought

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.