简体   繁体   中英

Writing a very simple interpreter in c#

I am trying to make a simple script interpreter in my application. A valid script to use in my application will be something like:

#this is a comment
*IDN? #this is a comment after a valid command
:READ? #this was also a comment after a valid command
RST
#last line was a valid comment but with no comment!

Now after loading the script content inside an array of string I want to execute each line, if it does not start with # and also ignor # in the same line if it exsist:

    foreach(var command in commands)
    {
        if(!command.StartsWith("#"))
        {
            _handle.WriteString(command);
        }
    }

My code will take care of starting comments. But how to check for inline comments?

I got this idea, Will this code be IDIOT-PROOF ?

        foreach(var command in commands)
        {
            if(!command.StartsWith("#"))
            {
                if(command.IndexOf('#') != null)
                {
                    _handle.WriteString(command.Remove(command.IndexOf('#')));
                }
            else
                _handle.WriteString(command);
            }
        }

Rephrase your question - another way to phrase it is that you want to process the part of each line that appears before the first # sign. Which would be the first element of the array returned by String.Split :

foreach(var command in commands)
{
    var splits = command.Split('#');
    if(!String.IsNullOrEmpty(splits[0]))
    {
        _handle.WriteString(splits[0]);
    }
}

And this now deals with the # character, wherever it appears in the line.

you may want to take a look at Irony . It is a framework that can be used for parsing custom made "languages" like you are trying. You will be able to define a set of commands and syntax etc. Even though it is alpha state, for you purposes it should be stable enough.

Check this Irony tutorial for creating your own domain specific language.

Just get rid of everything after the # . This regex will strip off any whitespace before the comment as well. If there's anything left, it's probably a command.

using System.Text.RegularExpressions;

...

command = Regex.Replace(command, @"\s*#.*$", "");
if (command != "")
{
    // this is a command, not a comment line
    // and any comment has been stripped off
}

I say "probably" because only whitespace before a # is stripped off. You might consider Trim ming your string if whitespace causes problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM