#include <iostream>
#include "lexer.h"
#define yylex aaslex
#define yy_scan_string aas_scan_string
#define yy_delete_buffer aas_delete_buffer
extern char* yylex(std::string& res);
int main()
{
std::string src =
"define(def1, 1 + 2)\n"
"define(def2,eax,1)\n"
"define(def3,0x22222)\n"
"define(def4,01 def3 02)\n"
"define(def5)\n"
"def3:\n"
"db 90 90 #90 def4 // db 指令 \n"
"mov def2\n\n"
"lea\teax [def1]\n"
;
YY_BUFFER_STATE state = yy_scan_string(src.data());
std::string res;
yylex(res);
yy_delete_buffer(state);
std::cout << res << "\n";
}
lexer.l:
%option noyywrap noline
%option prefix="aas"
%option header-file="lexer.h"
%{
#include <iostream>
#include <string>
#include <map>
#define YY_DECL char * yylex (std::string& res)
#define O(v) res += v
#define GET_DEFINE (defineMap.count(yytext) ? defineMap[yytext] : yytext)
// save dafines
std::string cur_define_key;
std::string cur_define_val;
std::map<std::string, std::string> defineMap;
%}
ID (?i:[a-z][a-z0-9]*)
%x define define_val
%%
<*>"//".* { /* eat comment */ }
"define(" { BEGIN(define); }
<define>{ID} { cur_define_key = yytext; }
<define>"," { BEGIN(define_val); cur_define_val = ""; }
<define_val>[ \t]+ { cur_define_val += yytext; }
<define_val>{ID} { cur_define_val += GET_DEFINE; }
<define_val>[^\)\n] { cur_define_val += yytext; }
<define_val>")" { /* define end */ defineMap[cur_define_key] = cur_define_val; BEGIN(0); }
<define>")" { printf("Error: 必须要有一个参数\n"); BEGIN(0); }
{ID} { O( GET_DEFINE ); }
\n { O(yytext); }
. { O(yytext); }
<<EOF>> {
std::cout << "===================================" << "\n";
for (auto i = defineMap.begin(); i != defineMap.end(); i++)
{
printf("key:%s, value:%s\n", i->first.data(), i->second.data());
}
std::cout << "===================================" << "\n";
defineMap.clear();
return NULL;
}
%%
print:
Error: 必须要有一个参数
===================================
key:def1, value: 1 + 2
key:def2, value:eax,1
key:def3, value:0x22222
key:def4, value:01 0x22222 02
===================================
0x22222:
db 90 90 #90 01 0x22222 02
mov eax,1
lea eax [ 1 + 2]