在Rascal中模式匹配AST节点 [英] Pattern matching AST nodes in Rascal

查看:101
本文介绍了在Rascal中模式匹配AST节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下AST定义:

data Exp =
    app(Exp fun, Exp body)
    | var(str name)
    | nat(int nat)
    | func(list[str] formal, Exp body)
    | cond(Exp cond, Exp then, list[tuple[Exp,Exp]] elifs, Exp otherwise)
    | let(list[str] vars, list[Exp] exps, Exp body)
    | seq(Exp lhs, Exp rhs)
    | mul(Exp lhs, Exp rhs)
    | div(Exp lhs, Exp rhs)
    | md(Exp lhs, Exp rhs)
    | add(Exp lhs, Exp rhs)
    | sub(Exp lhs, Exp rhs)
    | eq(Exp lhs, Exp rhs)
    | gt(Exp lhs, Exp rhs)
    | lt(Exp lhs, Exp rhs)
    | geq(Exp lhs, Exp rhs)
    | leq(Exp lhs, Exp rhs)
    ;

,并且我试图在switch语句中匹配树的节点,以便可以访问每个孩子。我尝试过的事情是:

and I am trying to match a node of the tree in a switch statement such that I have access to each child. The things I've tried are:

private str synthesise_f(Core::AST::Exp exp) {
    switch (exp) {
        case \Exp(_, _): {
            println("EXP_,_!");
        }
    }
}

private str synthesise_f(Core::AST::Exp exp) {
    switch (exp) {
        case /Exp(_, _): {
            println("EXP_,_!");
        }
    }
}

private str synthesise_f(Core::AST::Exp exp) {
    switch (exp) {
        case "Exp"(_, _): {
            println("EXP_,_!");
        }
    }
}


private str Synthesise_f(Core :: AST :: Exp exp){
case \adt():{
println( EXP_!);
}
}

and private str synthesise_f(Core::AST::Exp exp) { case \adt(,): { println("EXP_!"); } }

最后一个确实有效...但是无法让我访问该节点的子节点。如果我打印出在 switch 语句中使用的 exp ,我得到:

The last one does work...but doesn't give me access to the children of the node. If I print out the exp that is being used in the switch statement I get:

seq(var("x"),var("y"))

(删除评论和位置)

我想知道如何匹配这些节点,然后可以访问其子节点。

I'm wondering how I can match these nodes and then have access to their children.

谢谢!

推荐答案

嗯,我找到了解决方案。我要做的是创建一个基本案例节点(在本例中为 \str())节点,然后在任何其他通用类型上进行匹配。因此,这应该抓住基本情况,否则就意味着我必须可以处理其他类型的 Exp 。代码:

Well, I have found a solution. What I've done is created a base case node (in this case a \str()) node, then I match on any other generic type. So, this should catch either the base case and if not that means it must be some other type of Exp that I can then process. Code:

private str synthesise_f(Core::AST::Exp exp) {
    switch (exp) {
        case \var(_): {
            doSomethingWithStr();
        }
        case &T _(Exp e0): {
            doSomethingWith1Exp();
        }
        case &T _(Exp e0, Exp e1): {
            doSomethingWith2Exps();
        }
    }
    return ret;
}

这篇关于在Rascal中模式匹配AST节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆