Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a .NET interpreter (or how does Powershell work?)

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?

like image 939
edeboursetty Avatar asked Sep 10 '12 13:09

edeboursetty


2 Answers

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.

like image 50
Keith Hill Avatar answered Oct 11 '22 13:10

Keith Hill


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

like image 21
Mikael Eliasson Avatar answered Oct 11 '22 14:10

Mikael Eliasson