乐者为王

Do one thing, and do it well.

使用ANTLR构建PowerScript语法分析器(5)

基本表达式的语法规则构建完毕,那么表达式的语法规则构建就颇为简单了。使用ANTLR构建PowerScript语法分析器(4)中已经说过表达式是由运算元和运算符复合组成。所以在编写表达式语法规则前先要分析下PowerScript的运算符以及它们的优先级。

PowerScript支持四种类型的运算符,分别是:

  • 针对数字数据类型的算术运算符,执行算术计算;
  • 针对所有类型的关系运算符,比较数字,文本和布尔值;
  • 针对布尔类型的逻辑运算符,执行布尔值上的关系运算符
  • 针对字符串类型连接运算符,连接字符串和二进制大对象。

算术运算符

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
^ Exponentiation

关系运算符

Operator Meaning
= Equals
> Greater than
< Less than
<> Not equal
>= Greater than or equal
<= Less than or equal

逻辑运算符

Operator Meaning
NOT Logical negation
AND Logical and
OR Logical or

连接运算符

Operator Meaning
+ Concatenate

运算符优先级

Operator Purpose
( ) Grouping (see note below on overriding)
+, - Unary plus and unary minus (indicates positive or negative number)
^ Exponentiation
*, / Multiplication and division
+, - Addition and subtraction; string concatenation
=, >, <, <=, >=, <> Relational operators
NOT Negation
AND Logical and
OR Logical or

清楚运算符和优先级后,该如何表示这些表达式的语法关系呢?有个标准的分析表达式的递归定义可以套用,大部分表达式都遵循这个模式:

1
2
thisLevelExpression
    : nextHigherPrecedenceExpression (OPERATOR nextHigherPrecedenceExpression)*

现在我们就可以根据PowerScript的运算符优先级写出表达式的语法规则了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
expression
    : logical_or_expression
    ;

logical_or_expression
    : logical_and_expression ('or' logical_and_expression)*
    ;

logical_and_expression
    : logical_not_expression ('and' logical_not_expression)*
    ;

logical_not_expression
    : 'not'? relational_expression
    ;

relational_expression
    : additive_expression (('='|'>'|'<'|'<>'|'>='|'<=') additive_expression)*
    ;

additive_expression
    : multiplicative_expression (('+'|'-') multiplicative_expression)*
    ;

multiplicative_expression
    : exponentive_expression (('*'|'/') exponentive_expression)*
    ;

exponentive_expression
    : unary_expression ('^' unary_expression)*
    ;

unary_expression
    : ('+'|'-')? primary_expression
    ;

Comments