Concise interpreter mode-2

Source: Internet
Author: User

Concise interpreter mode-2

Concise interpreter mode (5.3) continued

This section describes a new expression language. User inputAlgebraic expressions, such as "(a * a + B) * (c-d )", The program calculates the correct result based on the priority and brackets.

1

A language can produce an infinite variety of sentences according to strictly defined rules. The rule of description language is calledGrammar/syntax. The syntax consists of four elements, which are represented as a triplet: G = {ST, SN, S, P }.

① The set ST of terminal. Terminator is the minimum grammar element of a language (Token/language symbol). In the previous example, The Terminator is a number and operator (with unlimited length. In this example, the Terminator is the letter Alphabet (which specifies that its Alphabet contains abcd) and the operator '*', '+', and ','-'. The separator space ('') or parentheses are not used as the Terminator.

Alph = {a | B | c | d} note that AB + c is invalid because there is no such letter as AB.

Op = {* | + | -}

② Set SN of non-terminal (nonterminal, syntax variable. Non-Terminator is usually used to represent expressions, functions, statements, and other syntax concepts. The non-terminator of this language only has Exp, indicating various expressions ).

③ Generate a set of P. The generative formula defines what is a valid Non-Terminator. The generative format is "α → β ". For example:

Exp → Alph | Alph op Alph | Exp op Exp

That is, a letter is an expression, and an operator is used to connect two letters as an expression. recursively, an operator is used to connect two expressions as an expression. For simplicity, spaces are not allowed in this language.

④ Start symbol S. S is the non-terminator used at the beginning of each valid sentence. You can use Exp.

2

You may have noticed that the calculation priority and parentheses are not included in the above syntax definition, because we would rather program to process users' original input than complicate the syntax definition.

This article defines the model of the interpreter according to multiplication and division,Write the class hierarchy of Exp Based on Huludao. The only thing to note is that the Exp-defined method

Public int interpret (Context c );

Contains the Context parameter, Context is like a bag, and all the data or functions required by Exp are put in it..

The Context stores the data or functions required by Exp. For example, you can enter an algebraic expression "a + B * c + d" to calculate the test score + average score + Attendance score.The data comes from the database. We can store the data using Context..

WhileThe user will input an algebraic expression, usually from the graphical interface. We simulate.


The class-level code of Exp is omitted.

Routine 7-4 Context is like a bag package intent. interpreter. calculator2; import java. util. HashMap; public class Context {private HashMap
 
  
VarList = new HashMap <> (); public void put (Character var, int value) {varList. put (var, value);} public int get (Character var) {return varList. get (var);} public Context () {initialize ();} // hardcoded private void initialize () {this. put ('A', 5); put ('B', 2); put ('C', 7); put ('D', 1 );}}
 

Constructing a syntax tree is the key to implementing the interpreter mode. [GoF] does not explain how to create an abstract syntax tree. Therefore, you do not need to know so much about the interpreter mode.


3

The program processes the user's original input, and converts the intermediate expression with the calculated priority and parentheses into a post-order expression that conforms to the preceding syntax, while the calculated priority uses a HashMap Save, the key is the operator, and the value is its priority. For the code, see

Forward-to-backward expression

You can put these static methods in Context or a toolkit.

4

Finally, build the syntax tree and write some test code.

Example 7 6 build the syntax tree package intent. interpreter. calculator2; import tool. god; import java. util. hashMap; import java. util. stack; public class Calculator {private String expression = (String) God. getValue ("expression"); private Context ctx; public static void main (String [] args) {Calculator calc = new Calculator (); Context ctx = new Context (); calc. setContext (ctx); System. out. println ("Algebra variable:" + "a =" + ctx. get ('A') + ", B =" + ctx. get ('B') + ", c =" + ctx. get ('C') + ", d =" + ctx. get ('D'); System. out. println ("Expression =" + calc. expression); System. out. println ("Result =" + calc. interpret ();} public void setContext (Context c) {ctx = c;} public int interpret () {String pfExpr = Context. revoke post (expression); Expr rootNode = buildTree (pfExpr); return rootNode. interpret (ctx);} private NonTerminalExp getNonTerminalExp (char op, Expr l, Expr r) {NonTerminalExp e = null; if (op = '+ ') {e = new AddExp (l, r);} else if (op = '-') {e = new SubtractExp (l, r );} else if (op = '*') {e = new MultiplyExp (l, r);} return e;} private Expr buildTree (String expr) {Stack
 
  
S = new Stack <> (); char [] cs = expr. trim (). toCharArray (); for (char x: cs) {if (! Context. isOperator (x) {s. push (new TerminalExp (x);} else {Expr r = (Expr) s. pop (); Expr l = (Expr) s. pop (); Expr now = getNonTerminalExp (x, l, r); s. push (now) ;}// end for return (Expr) s. pop ();}}
 
The code for constructing the syntax tree is not much different from the code in the previous section. A simple factory is used here.

Private/* static */NonTerminalExp getNonTerminalExp (char op, Expr l, Expr r)

If you dislike if-else, you can try the factory method. In addition, add the Division code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.