compiler expression pattern match

发布时间 2023-06-06 20:04:46作者: xuyv

编译器中经常需要用到pattern match。

那么如何实现呢?

比较直观的方法是使用递归。

以pattern match: y= a * (b + c) 为例。

首先,将其解析成一个抽象语法树:* a + b c

其次,递归match:

match(y, pattern) => match(y, '* a + b c')

左边是待检测的string,右边的是pattern。

只要第一步符合,则进行下一步match:

match(y->root, '*')

match(y->left, 'a')

match(y->right, '+ b c')。

伪代码

def match(y, pattern):

  if(y->left == Null, y->right == Null) return y->root == pattern->root

  return match(y->left, pattern->left) && match(y->right, pattern->right)