Introduction to ANTLR (another tool for language recognition). [Translation]

zhaozj2021-02-11  205

Expression evaluation

In practice, you need to pay for the expression directly when the mark comes in, which can add behavior in Parser:

Class Exprparser Extends Parser;

Expr returns [int value = 0]

{INT X;

: Value = MEXPR

(Plus x = mexpr {value = x;}

| Minus x = mexpr {value - = x;}

) *

;

MEXPR RETURNS [INT VALUE = 0]

{INT X;

: Value = atom (star x = atom {value * = x;}) *

;

Atom returns [int value = 0]

: I: int {value = integer.parseint (i.getText ());}

| Lparen value = expr rparen

;

LEXER is still the same, but you need to add a print statement in the main program:

Import Antlr. *;

Public class

Main

{

Public static void main (string [] args) throws exception {

ExprleXer Lexer = New ExprleXer (System.in);

Exprparser Parser = New Exprparser (Lexer);

INT x = parse.expr ();

System.out.println (x);

}

}

Now, once you run this program, you can get the results:

$ Java

Main

3 4 * 5

twenty three

$ Java

Main

(3 4) * 5

35

$

How to translate action with ANTLR

The action is typically placed typed in the generation of Parser, where the location corresponds to the position in the grammar.

The description of the return rules is as follows:

MEXPR RETURNS [INT VALUE = 0]

: ...

;

Translated into

Public int measure () {

INT value = 0;

...

Return Value;

}

If you add a description of the parameters, these parameters will be copied to the method declaration:

MEXPR [INT X] returns [int value = 0]

: ... {Value = x;}

;

generate

Public int measure (int x) {

INT value = 0;

...

Value = x;

Return Value;

}

Therefore, the complete translation of MEXPR and ATOM rules seems to be as follows:

Public int measure () {

INT value = 0;

INT X; // local variable def from rule mexpr

Value = atom ();

While (la (1) == star) {

Match (star);

x = atom ();

Value * = x;

}

Return Value;

}

Public int atom () {

INT value = 0;

Switch (la (1)) {// switch on lookahead token Type

Case Int:

Token i = lt (1); // make Label I Point to Next Lookahead token Object

Match (int);

Value = integer.parseint (i.getText ()); // compute int value of tokenbreak;

Case Lparen:

Match (lparen);

Value = expr (); // Return Whatver EXPR () Computes

Match (rparen);

Break;

DEFAULT:

// Error

}

Return Value;

}

转载请注明原文地址:https://www.9cbs.com/read-5876.html

New Post(0)