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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With