Ирония: учебник по оценке узлов AST? - PullRequest
7 голосов
/ 14 февраля 2011

Я определил простую грамматику в Ирония и сгенерировал хороший компактный AST.

image

Now I'm trying to figure out how to evaluate it. Problem is, I can't find any tutorials on how to do this.

I've defined just 2 AST nodes:

class TagListNode : AstNode
{
    public override void Init(ParsingContext context, ParseTreeNode treeNode)
    {
        base.Init(context, treeNode);
        AsString = "TagList";
        foreach (var node in treeNode.ChildNodes)
            AddChild(null, node);
    }

    public override void EvaluateNode(Irony.Interpreter.EvaluationContext context, AstMode mode)
    {
        foreach (var node in ChildNodes)
            node.EvaluateNode(context, AstMode.Read);
    }
}

class TagBlockNode : AstNode
{
    public AstNode Content;

    public override void Init(ParsingContext context,ParseTreeNode treeNode)
    {
        base.Init(context, treeNode);
        AsString = treeNode.ChildNodes[0].FindTokenAndGetText();
        Content = AddChild(null, treeNode.ChildNodes[1]);
    }

    public override void EvaluateNode(EvaluationContext context, AstMode mode)
    {
        context.Write(string.Format("<{0}>", AsString));
        Content.EvaluateNode(context, AstMode.Read);
        context.Write(string.Format("</{0}>", AsString));
    }
}

This will generate the following output:

 3.14159265358979

Whereas the output I want is:


    
        page title
    
    
        header
        paragraph 1
        3.14159265358979
    
 

I don't think I'm supposed to be using Context.Write(). The samples show pushing stuff onto context.Data and popping them off... but I'm not quite sure how that works.

I'm guessing pi gets tacked on at the end because it's automatically pushed onto context.Data and then one element is popped off at the end?? I'm not really sure.

Some pointers or a link to a tutorial would be nice.

Also, how am I supposed to handle the different node types? Each "Tag" can have 4 different types of content: another tag, a string literal, a variable, or a number. Should I be writing things like if(node is StringLiteral) .... in the EvaluateNode method or what?


I've found этот , но они просто зацикливаются на AST и неEvaluateNode.

А затем этот , который заменяет единственное значение в стеке данных ... но на самом деле не объясняет, как этовыводится или что-то в этом роде.


Чтобы было ясно, я специально хочу знать, как переопределить методы EvaluateNode в Irony.Ast.AstNode, чтобы делать то, что я хочу.


Хорошо, я проследил этот фрагмент в конце этой строки:

    if (EvaluationContext.HasLastResult)
      EvaluationContext.Write(EvaluationContext.LastResult + Environment.NewLine);

Что включено в процедуру оценки по умолчанию .... возможно, это хорошо работает для приложения калькулятора, но не так много в моем.Пытаюсь выяснить, как обойти интерпретатор скриптов сейчас, но потом я не знаю, как установить глобальные переменные.

1 Ответ

0 голосов
/ 14 февраля 2011

Лучший способ перебрать структуру AST - реализовать шаблон посетителя .

Может быть, эта ссылка поможет вам.

...