Child pages
  • Calculator sample

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

put the calculator to work. Here is what using the calculator from a C# 

The development of the Nitra parser begins with creating a syntax module. The syntax module is a translation and encapsulation unit. The complete parser is composed of one or more syntax modules.

...

After you add the AST methods, you can put the calculator to work. Here is what using the calculator from a C# application looks like:

Code Block
languagec#
collapsetrue
using N2;
using System;

class Program
{
  static void Main()
  {
    var parserHost = new ParserHost();
    for(;;)
    {
      Console.Write("input>");
      var input = Console.ReadLine();

      // Exit if user inputs empty string
      if (string.IsNullOrWhiteSpace(input))
        return;

      // Parse the string with the starting rule
      var parseResult = Calc.Start(SourceSnapshot(input), parserHost);
      // Create materialized AST
      var ast = CalcAstWalkers.Start(parseResult);

      Console.WriteLine("Pretty print: " + ast);

      // If any errors occurred, output error messages
      foreach(var error in parseResult.GetErrors())
      {
        var lineCol = error.Location.StartLineColumn;
        Console.WriteLine("(" + lineCol.Line + "," + lineCol.Column + "): " + error.Message);
      }

      // Calculate the expression value using AST method and output value to console
      Console.WriteLine("Result: " + ast.Value());
    }
  }
}

...