본문 바로가기

Programming/LEX & YACC

간단한 렉스 프로그램 ( Flex & C++ )

아직 C++ 이 익숙하지 않아서 문법이 기억이 안나는건 C로 처리했다. ( new 안쓰고 malloc을 썼다든지.. )

공백과 ' '  기준으로 토큰을 나눤서 vector에 저장하고 그 vertor를 리턴하는 함수를 이용 하는 코드

main은 테스트용으로 Tokenize함수를 외부에서 불러와 쓸 수있따.

%{
#include <vector>
#include <string>
#include <iostream>
#include <vector>

#undef YY_INPUT
#define YY_INPUT(b, r, ms) ( r = my_yyinput(b, ms) )
#ifndef min
#define min(a, b) ((a > b) ? b : a)
#endif

using namespace std;

vector<string>& Tokenize(char* pString);

int my_yyinput(char* buf, int max_size);
char* yyinputptr;
char* yyinputlim;
char* temp;
vector<string> gTokenVector;
%}

%%

[^ \t\n]*'[^'\n]*'[^ \t\n]* {
    int i,j=0;  
    temp = (char*)malloc(sizeof(char)*yyleng); 
    for(i=0 ; i < yyleng ; i++)
    {
     if( yytext[i] != '\'' )
      temp[j++] = yytext[i];
    }   
    temp[j] = '\0';
    gTokenVector.push_back(temp); 
        free(temp);
       }

[^ \t\n]+  { gTokenVector.push_back(yytext);  }

      

\n 
[ \t] ;

 

%%

int yywrap(void)
{
 return 1;
}

int my_yyinput(char* buf, int max_size)
{
 int     n;

 n = min(max_size, yyinputlim - yyinputptr);
 if (n > 0)
 {
  memcpy(buf, yyinputptr, n);
  yyinputptr += n;
 }
 return n;
}

vector<string>&  Tokenize(char *pString)
{
        yyinputptr = pString;
        yyinputlim = pString + strlen(pString);

   yylex();

   return gTokenVector;
}

int  main()
{
 vector< string > aaa;
 aaa = Tokenize("SELECT from abc WHEREb = 'banana'");

 for( int i = 0 ; i < aaa.size() ; i++ )
 {
  cout << aaa[i] << endl;
 }

 return 0;
}