XeL DNA Ccay is a calculator again.

Source: Internet
Author: User
Tags printf

%{
#include "Parser.h"
%}

%%

"+" {
return PLUS;
}

"-" {
return minus;
}

"/" {
return DIV;
}

"*" {
return MULT;
}

"(" {
return l_par;
}

")" {
return r_par;
}

[0-9]+ {
Yylval = Atoi (Yytext);

return INTEGER;
}

"/n" {
return NL;
}

. ;
%%

----------------------------------------------------------------------------------------------------------- ---------------------------------------- 

%{
int tempCount1 =-1;
int tempCount2 =-1;
int tempCount3 =-1;
int tempCount4 =-1;
int tempCount5 =-1;
int tempCount6 =-1;
int tempCount7 =-1;
%}
%token PLUS
%token minus
%token DIV
%token MULT
%token L_par
%token R_par
%token INTEGER
%token NL

%%

Calc
: Calc expression NL {printf ("%d/n", $ $);}
| Expression NL {printf ("%d/n", $ $);}
;

Expression
: term {$$ = $;}
|  Expression PLUS Term {tempCount6 = $ + $; $$ = $ + $; }
| Expression minus term {tempCount7 = $-$ $; $$ = $-$;}
;

Term
: Factor {$$ = $;}
|   Term MULT Factor {tempCount4 = $ * $ $; $$ = $ * $ $; }
| Term DIV Factor {TEMPCOUNT5 =$1/$ $; $$ = $/$;}
;

Factor
: L_par expression R_par {tempCount1 = $; $$ = $;}
| INTEGER {tempCount2 = $; $$ = $;}
| Minus factor {tempCount3 =-$2; $$ =-$2;}

%%

int Yyerror (char *str) {
printf ("%s/n", str);
}

Input (4-1)

TempCount2 = 2

TempCount2 = 4

TempCount2 = 1

TEMPCOUNT7 = 3

TempCount1 = 3

TEMPCOUNT4 = 6

Read into 2→ multiplication sign →integer (factor) match

Factor (term) → Read into the left width → read into the 4→ read and subtract

INTEGER (factor) match →factor (term) →term (expression)

Read into the 1→ read into the right width →integer (factor) match →factor (term)

L_par expression r_par match →term MULT factor match →term (expression)

----------------------------------

You can define terminator and non-terminator types,

%token PLUS
%token minus
%token DIV
%token MULT
%token L_par
%token R_par
%token <value> integers
%token NL

%type <node> Calc
%type <node> Expression
%type <node> Term
%type <node> Factor

%union{
int value;
CNode *node;
};

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.