Search code examples
c#parsingexpressioneditorevaluator

Expression editor / parser / evaluator


I am trying to work on a C# project and I would like to allow the user to run code on the fly, by typing code into an editor. So with that in mind, I thought about writing some sort of scripting editor, parser and evaluator, but wanted to check with other people first, in case I am just reinventing the wheel?

So, my idea is/was to...

  1. Write a syntax highlighted editor that I can write code into, including the use of custom keywords.
  2. Add logic to the editor so that it will be able to format the content based on the text in the editor.
  3. Have a way of 'actioning' the text that has been entered.

For instance, if I enter the following...

if (Shape.IsACube())
{
  // Do some cube stuff
}
else if (Shape.Area(height, length, width) > 40)
{
  // Do some large area stuff
}

...then I would like to be able to run that code on the fly as though it was part of the application.

I hope all of that makes sense. Any thoughts?


Solution

  • Which grammar for your syntax you want to use? Your own or C# ? If you just want to compile some C# code in runtime - you can use something like CodeDOM. Highlighting can be achieved through C# Syntax Highlighter.

    If you want your own grammar with your terminals/non-terminals - you should use grammar makers like ANTLR4. This way you will understand how most compilers/interpretators works.

    The main idea is that you write Lexer (which responsible for tokenization of your input) and Parser (which is actualy just list of grammar rules, 'productions' in other words). It will give you full AST from which you can evaluate/highlight your text. Many language grammars already written before you in here including C# syntax (even ANTLR4 itself is presented). So you can just pick some and modify it for your needs.