检测flex中的注释

时间:2015-04-17 17:39:50

标签: c flex-lexer

我正在学习flex.I编写了一个简单的程序来检查给定文本文件的单词是否为动词并打印出来。我想检测输入文件中是否有任何单行或多行注释(如c和c ++样式注释),并将整个注释打印到输出。有没有办法做到这一点?我的示例代码如下:

%%

[\t]+

is   |

am   |

are  |

was  |

were {printf("%s: is a verb",yytext);}

[a-zA-Z]+ {printf("%s: is a verb",yytext);}

. |\n

%%

int main(int argc, char *argv[]){    
    yyin = fopen(argv[1], "r");    
    yylex();         
    fclose(yyin);
}

2 个答案:

答案 0 :(得分:2)

它有点复杂。我建议使用start conditions来处理评论。这是一个词法分析者,我很快为此加起来:

%option noyywrap
%x COMMENT_SINGLE
%x COMMENT_MULTI

%top{
/* for strndup */
#include <string.h>
}

%{
char* commentStart;
%}

%%

[\n\t\r ]+ { 
  /* ignore whitespace */ }

<INITIAL>"//" { 
  /* begin of single-line comment */ 
  commentStart = yytext; 
  BEGIN(COMMENT_SINGLE); 
}

<COMMENT_SINGLE>\n { 
  /* end of single-line comment */
  char* comment = strndup(commentStart, yytext - commentStart);
  printf("'%s': was a single-line comment\n", comment);
  free(comment); 
  BEGIN(INITIAL); 
}

<COMMENT_SINGLE>[^\n]+ { 
  /* suppress whatever is in the comment */
}

<INITIAL>"/*" { 
  /* begin of multi-line comment */
  commentStart = yytext; 
  BEGIN(COMMENT_MULTI); 
}

<COMMENT_MULTI>"*/" { 
  /* end of multi-line comment */
  char* comment = strndup(commentStart, yytext + 2 - commentStart);
  printf("'%s': was a multi-line comment\n", comment);
  free(comment); 
  BEGIN(INITIAL); 
}

<COMMENT_MULTI>. { 
  /* suppress whatever is in the comment */
} 

<COMMENT_MULTI>\n { 
  /* don't print newlines */
} 

is   |
am   |
are  |
was  |
were { 
  printf("'%s': is a verb\n", yytext); 
}

[a-zA-Z]+ { 
  printf("'%s': is not a verb\n", yytext); 
}

. { 
  /* don't print everything else */ 
}

%%

int main(int argc, char *argv[]){    
  yyin = fopen(argv[1], "r");    
  yylex();         
  fclose(yyin);
}

注意:词法分析器代码已经足够长,所以我省略了任何错误检查。

答案 1 :(得分:1)

单行评论
from rpy2.robjects import pandas2ri import rpy2.robjects as ro from rpy2.robjects.packages import importr pandas2ri.activate() gms = importr("gms.test") hmisc = importr('Hmisc') base = importr('base', robject_translations={'with': '_with'}) stats = importr('stats', robject_translations={'format_perc': '_format_perc'}) r_consult_case_control = pandas2ri.py2ri(consult_case_control) formula = stats.as_formula('es_score ~ n + raingarden + consult_case') formula.getenvironment()['es_score'] = r_consult_case_control.rx2('es_score') formula.getenvironment()['n'] = r_consult_case_control.rx2('n') formula.getenvironment()['raingarden'] = r_consult_case_control.rx2('raingarden') formula.getenvironment()['consult_case'] = r_consult_case_control.rx2('consult_case') # succeeds: base._with(r_consult_case_control, ro.r.summary(formula, FUN=gms.sf)) # fails with given error: base._with(consult_case_control, ro.r.summary(formula, fun=gms.sf))