Posts Tagged ‘作業解答’

6
十一月

編譯器課程11/06作業二

   Posted by: admin    in 97(上)編譯器

ch3-02.l

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
%{
#include "y.tab.h"
%}
 
%%
sin     { return SIN;}
cos     { return COS;}
 
pi      { yylval.dval = 3.14159; return NUMBER; }
 
(([0-9]+)|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?)	{ 
             yylval.dval = atof(yytext); return NUMBER; }
 
[ \t]	;		/* ignore white space */
\n	return 0;	/* logical EOF */
.	return yytext[0];
%%

ch3-02.y

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
%{
#include <stdio.h>
#include <math.h>
%}
 
%union {
	double dval;
	int vblno;
}
 
%token <vblno> NAME
%token <dval> NUMBER
 
%token SIN COS
 
%left '-' '+'
%left '*' '/'
%nonassoc UMINUS
 
%type <dval> expression
 
%%
 
statement:	NAME '=' expression
	|	expression		{ printf("= %g \n", $1); }
	;
 
expression:	expression '+' expression { $$ = $1 + $3; }
	|	expression '-' expression { $$ = $1 - $3; }
	|	expression '*' expression { $$ = $1 * $3; }
	|	expression '/' expression
				{	if($3 == 0)
						yyerror("divide by zero");
					else
						$$ = $1 / $3;
				}
	|	'-' expression %prec UMINUS	{ $$ = -$2; }
	|	'(' expression ')'	{ $$ = $2; }
	|	NUMBER			{ $$ = $1; }
 
	| COS '(' expression ')' {$$ = cos($3);}
	| SIN '(' expression ')' {$$ = sin($3);}
 
	;
%%
 
main()
{
	yyparse();
}

bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark

Tags: , , ,

1
十一月

編譯器課程10/24作業一

   Posted by: admin    in 97(上)編譯器

作業lex程式碼ch2-09.l

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
%{
int comments, code, whiteSpace;
int numif, numwhile, numfunc;
%}
%s COMMENT
 
%%
^[ \t]*"/*"	{ BEGIN COMMENT; /* enter comment eating state */ }
^[ \t]*"/*".*"*/"[ \t]*\n {
		 comments++; /* self-contained comment */
		 }
<COMMENT>"*/"[ \t]*\n	{ BEGIN 0;  comments++;}
<COMMENT>"*/"		{ BEGIN 0; }
<COMMENT>\n	{ comments++; }
<COMMENT>.\n	{ comments++; }
^[ \t]*\n	{ whiteSpace++; }
 
if    {numif++;}
while {numwhile++;}
"(".*")" {numfunc++;}
 
.			; /* ignore everything else */
%%
main()
{
	yylex();
	printf("if: %d, while %d, func %d\n",	numif, numwhile, numfunc);
}

bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark

Tags: , , ,