Parsing and Evaluating a Meta-Language

With this functions I can parse/evaluate a simple meta-language that accepts commands on this format:

[@functionName]
[@functionName(parameter)]

The parsing engine automatically replace each command with its result (“” by default) over the evaluated string. Is of course possible, as well, to perform custom operations before to return the result.

//Metalanguage evaluation
//Syntax: [@<funcName>(<funcParam>)] or [@<funcName>]
function evaluateMetalanguage(html) {
    var mlRegExp = /\[\@(\w+)(\((.*?(?=\)\]))\))?\]/i;
    var mlMatch = mlRegExp.exec(html);
    while (mlMatch != null) {
        var match = mlMatch[0];
        var funcName = mlMatch[1];
        var funcParam = mlMatch.length > 3 ? mlMatch[3] : null;
        html = evaluateMLFunction(html, match, funcName, funcParam);
        mlMatch = mlRegExp.exec(html);
    }
    return html;
}
 
function evaluateMLFunction(html, match, funcName, funcParam) {
    var result = "";
    switch (funcName.toLowerCase()) {
        case "function1":
            result = "...";
            break;
        case "function2":
            performSomeOperation(funcParam);
            break;
    }
    return html.replace(match, result);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s