2013-10-10 87 views
0

我在這個Bison程序中遇到了麻煩。它必須通過將它們乘以2^n來接收具有諸如「101.101」的句點的1和0的字符串。例如:將語義規則應用到野牛

"101.101" = (1*2^2)+(0*2^1)+(1*2^0)+(1*2^-1)+(0*2^-2)+(1*2^-3)=5.625 

該點告訴pow何時正面或負面。我有以下語義動作:

S→ L.R 
S→ L 
L → L1 B 
L → B 
R → R1 B 
R → B 
B→ 0 
B → 1 
Sematic Rules 
L.pos=0;R.pos=-1;S.val=L.val+R.val 
L.pos=0;S.val=L.val; 
L1.pos = L.pos + 1; B.pos = L.pos; L.val = L1.val + B.val; 
B.pos = L.pos; L.val = B.val; 
R1.pos = R.pos - 1; B.pos = R.pos; L.val = L1.val + B.val; 
B.pos = R.pos; L.val = B.val; 
B.val=0; 
B.val = 1*2B.pos; 

我的問題是,我不知道如何像.VAL和.POS添加變量野牛文件,然後執行C代碼編程。

野牛

%{ 
#include <string.h> 
#include <stdio.h> 
#include<stdlib.h> 
void yyerror (char *string); 
int down =0; 

%} 
%token r1 
%token l1 
%token DOT 
%token ZERO 
%token ONE 

%% 

s: l DOT r 
| l 
; 

l: l1 b 
| b 
; 

r: r1 b 
|b 
; 

b: ONE 
| ZERO 
| error 
; 

%% 
#include "lex.yy.c" 

void yyerror (char *string){ 
    printf ("%s",string); 
} 

main(){ 
    yyparse(); 
} 

萊克斯文件

%{ 
#include <stdio.h> 
#include <math.h> 
#include "y.tab.h" 
%} 
BINARY [0-1] 
%% 
"1" {return ONE;} 
"0" {return ZERO;} 
"." {return DOT;} 
%% 

回答

1

我寫了這個,這不是你想要的是什麼,但它顯示瞭如何給在YACC規則類型,以及如何把C代碼到規則。

The C code is in braces { } 
$$ means "this rule" 
$1 means "argument 1" 
$2 means "argument 2" 

So the rule 
    r : r b  
and the code 
    { $$ = $1 << 1 | $2; } 
means 
    r = r << 1 | b 

的YACC文件是:

%{ 
#include <string.h> 
#include <stdio.h> 
#include <stdlib.h> 
void yyerror (char *string); 
int down =0; 

%} 

%union { // %union is needed to tell yacc about the types your rules will return 
    unsigned val; // rules with type "val" will return unsigned 
}; 


%token DOT 
%token ZERO 
%token ONE 

%type <val> l r b; // rules l, r, and b are of type val 

%% 

s : l DOT r { printf("l.r = 0x%x.0x%x\n", $1, $3); } 
    | l  { printf("l = 0x%x\n", $1); } 
    ; 

l : l b  { $$ = $1 << 1 | $2; } // l = l << 1 | b 
    | b  { $$ = $1; } // l = b 
    ; 

r : r b  { $$ = $1 << 1 | $2; } // r = r << 1 | b 
    | b  { $$ = $1; } // r = b 
    ; 

b : ONE  { $$ = 1; } // b = 0 
    | ZERO   { $$ = 0; } // b = 1 
    // | error 
    ; 

%% 
//#include "lex.yy.c" 

void yyerror (char *string){ 
    printf ("%s",string); 
} 

int yywrap() { return 1; } 

int main(){ 
    yyparse(); 
    return 0; 
} 

法文件

%{ 
#include <stdio.h> 
#include "y.tab.h" 
%} 
%% 
"1" {return ONE;} 
"0" {return ZERO;} 
"." {return DOT;} 
%% 

注意,法文件包括 「y.tab.h」。

[Charlies-MacBook-Pro:~] crb% cat i 
011.110 
[Charlies-MacBook-Pro:~] crb% x < i 
l.r = 0x3.0x6 

您可以更改代碼,做你的算術但是你想:這是由命令

yacc -d file.y 

跑步是這樣的,當程序被命名爲「X」創建的。或者你可以在「s」規則中做一個函數調用,並在那裏倒入第1位和第 位。

+0

打我吧:)我只是做一個,但值類型爲'struct {int val; int pos;};'使OP更好一點。但繼續... – rici

+0

無論哪種方式,聽起來像你的更好。我很懶。我不擅長解釋東西。您可以將l和r當成雙打。也許從這兩個答案OP將能夠弄清楚。 –