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

I am looking for a small interpreter for C # that I could load in some applications. Something that could trigger 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 thought that this could be achieved by creating a dictionary of all the variables and their types, and then compiling each of the lines as they arrived, and then execute the function, get the result and paste it into the variables dictionary.

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

Then I thought Powershell was doing what I needed. But how is this done? Can someone enlighten me on how Powershell works or what could be a good way to create a .Net interpreter?

+4
source share
3 answers

How about you place a PowerShell application in your application and let it translate? For instance:

 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, look at the interpreter pattern .

+4
source

Take a look at 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.

+3
source

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

Comment added as an answer as it seems more useful than I thought at first

+3
source

Source: https://habr.com/ru/post/1433365/


All Articles