Jas*_*son 14
重新定义YY_INPUT.这是一个工作示例,使用命令编译和运行
yacc -d parser.y
lex lexer.l
gcc -o myparser *.c
Run Code Online (Sandbox Code Playgroud)
输入从globalInputText读取.您可以修改此示例,以便全局输入文本是您想要的任何字符串,或者来自您想要的任何输入源.
parser.y:
%{
#include <stdio.h>
extern void yyerror(char* s);
extern int yylex();
extern int readInputForLexer(char* buffer,int *numBytesRead,int maxBytesToRead);
%}
%token FUNCTION_PLUS FUNCTION_MINUS NUMBER
%%
expression:
NUMBER FUNCTION_PLUS NUMBER { printf("got expression! Yay!\n"); }
;
%%
Run Code Online (Sandbox Code Playgroud)
lexer.l:
%{
#include "y.tab.h"
#include <stdio.h>
#undef YY_INPUT
#define YY_INPUT(b,r,s) readInputForLexer(b,&r,s)
%}
DIGIT [0-9]
%%
\+ { printf("got plus\n"); return FUNCTION_PLUS; }
\- { printf("got minus\n"); return FUNCTION_MINUS; }
{DIGIT}* { printf("got number\n"); return NUMBER; }
%%
void yyerror(char* s) {
printf("error\n");
}
int yywrap() {
return -1;
}
Run Code Online (Sandbox Code Playgroud)
myparser.c:
#include <stdio.h>
#include <string.h>
int yyparse();
int readInputForLexer( char *buffer, int *numBytesRead, int maxBytesToRead );
static int globalReadOffset;
// Text to read:
static const char *globalInputText = "3+4";
int main() {
globalReadOffset = 0;
yyparse();
return 0;
}
int readInputForLexer( char *buffer, int *numBytesRead, int maxBytesToRead ) {
int numBytesToRead = maxBytesToRead;
int bytesRemaining = strlen(globalInputText)-globalReadOffset;
int i;
if ( numBytesToRead > bytesRemaining ) { numBytesToRead = bytesRemaining; }
for ( i = 0; i < numBytesToRead; i++ ) {
buffer[i] = globalInputText[globalReadOffset+i];
}
*numBytesRead = numBytesToRead;
globalReadOffset += numBytesToRead;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果你使用真实lex
而不是flex
我相信你可以简单地定义自己的
int input(void);
Run Code Online (Sandbox Code Playgroud)
这可以从字符串或任何您想要的内容返回字符.
或者,我相信你可以将字符串写入文件,并在流上打开文件yyin
.我怀疑这适用于任何一种实现.
如果使用flex,我认为你重新定义了YY_INPUT()
宏,
归档时间: |
|
查看次数: |
10058 次 |
最近记录: |