How to use the semantic actions to generate the symbol tables in ANTLR4

当 Parser 处理输入的代码的时候不仅要判断是否语法和句法都正确,还可以执行一些有用的操作,这些操作就叫做 Semantic actions。其实也就是一段代码,一般嵌入在在语法文件的规则里面。那么当 parser 应用这个规则的时候就会执行你设置的这段代码。换个角度理解,semantic actions 其实就是“触发器”,触发条件就是 parser 应用了对应的规则。

摩尔投票法


今天又做到了 Leetcode 169. 多数元素 这一道题. 我依稀记得最优的解法叫做什么摩尔投票法. 但是我对它的印象竟然只有这个名字本身了 Orz. 对于这个算法本身倒是忘得一干二净. 于是我打算系统性地学习一下这个算法的原理, 并将它总结出来写成这篇博客. 不知道在哪里看到的一句话 :

Lab14 题解 (UCB CS61A@2021 Fall)


Write a function that prunes a Tree t mutatively. t and its branches always have zero or two branches. For the trees with two branches, reduce the number of branches from two to one by keeping the branch that has the smaller label value. Do nothing with trees with zero branches.

Prune the tree in a direction of your choosing (top down or bottom up). The result should be a linear tree.

Hw10 题解 (UCB CS61A@2021 Fall)


In this question, you will add support for grouping and piping.

Recall that grouping allows for an entire regular expression to be treated as a single unit, and piping allows for a pattern to match an expression on either side. Combined, these will let us create patterns which match multiple strings!

Define the group and pipe expressions in your grammar.

  1. A group consists of any regex expression surrounded by parentheses (()).
  2. A pipe operator consists of a regex expression, followed by a pipe (|) character, and lastly followed by another regex expression.

For example, r"apples" would match exactly the phrase “apples” in an input. If we wanted our pattern from before to match “oranges” as well, we could expand our rstring to do so using groupings and pipes: r"(apples)|(oranges)".

Lab12 题解 (UCB CS61A@2021 Fall)


Write a regular expression that parses strings written in the 61A Calculator language and returns any expressions which have two numeric operands, leaving out the parentheses around them.

写一个符合 (operand operator1 operator2) 格式的正则表达式. 这个是比较简单的, 因为这里的运算符只有 +, -, *, /. 我们用 [] 括起来就可以, 但是要注意**- 需要用 \ 转义**