Skip to content

Instantly share code, notes, and snippets.

@y-yu
Created August 22, 2013 03:14
Show Gist options
  • Save y-yu/6302817 to your computer and use it in GitHub Desktop.
Save y-yu/6302817 to your computer and use it in GitHub Desktop.
Rubyの改造(2)
%{
#include <stdio.h>
#include <string.h>
#include "relex.h"
//---------------------------------------------------------------------------
//#define YYDEBUG 1
//#define YYERROR_VERBOSE 1
//int yydebug = 1;
//---------------------------------------------------------------------------
void yyerror(char* str);
%}
%token TOKEN_ESCAPECHAR
%token TOKEN_CLASS
%token TOKEN_QUANTIFIER
%token TOKEN_LETTER
%token TOKEN_BEGINGROUP
%token TOKEN_ENDGROUP
%token TOKEN_ALT
%token TOKEN_END
%token TOKEN_ERR
%%
re : pattern TOKEN_END {
free($1);
YYACCEPT;
}
;
pattern : string pattern {
char *s = (char *)malloc(sizeof(char) * (strlen($1) + strlen($2)));
strcpy(s, $1);
strcat(s, $2);
printf("pattern -> %s%s\n", $1, $2);
free($1);
free($2);
$$ = s
}
| alternation { printf("alternation -> %s\n", $1); $$ = $1; }
| { $$ = strdup(""); }/* phi */
;
alternation : string TOKEN_ALT pattern {
char *s = (char *)malloc(sizeof(char) * (strlen($1) + strlen($3) +1));
strcpy(s, $1);
strcat(s, "|");
strcat(s, $3);
free($1);
free($3);
$$ = s;
}
;
string : character quantifier {
char *s = (char *)malloc(sizeof(char) * (strlen($1) + strlen($2)));
strcpy(s, $1);
strcat(s, $2);
free($1);
free($2);
$$ = s
}
;
quantifier : TOKEN_QUANTIFIER { printf("quantifier -> %s\n", $1); $$ = $1; }
| { $$ = strdup("");}/* phi */
;
character : TOKEN_CLASS { printf("class -> %s\n", $1); $$ = $1;}
| TOKEN_LETTER { printf("letter -> %s\n", $1); $$ = $1;}
| TOKEN_ESCAPECHAR { printf("escape -> %s\n", $1); $$ = $1;}
| group {
char *s = (char *)malloc(sizeof(char) * (strlen($1) + 2));
strcpy(s, "(");
strcat(s, $1);
strcat(s, ")");
free($1);
$$ = s;
printf("group -> %s\n", s);
}
;
group : TOKEN_BEGINGROUP pattern TOKEN_ENDGROUP {$$ = $2}
;
%%
void
yyerror (char* str)
{
printf("!! yyerror !! = %s\n", str);
}
void
re_parse (char *str)
{
init_yyc(&str);
yyparse();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment