-
Notifications
You must be signed in to change notification settings - Fork 88
/
flexexample2.l
52 lines (37 loc) · 1.18 KB
/
flexexample2.l
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
%{
/* based on an example from http://matt.might.net/articles/standalone-lexers-with-lex/ */
#include <stdio.h>
#include <stdlib.h>
unsigned int code = 0 ; /* Bytes of code. */
unsigned int comm = 0 ; /* Bytes of comments. */
#define CODE {code += strlen(yytext);}
#define COMM {comm += strlen(yytext);}
%}
%option noyywrap
/* Exclusive start conditions */
%x INCOMMENT INSTRING
%%
/* this is proper yylex() code */
printf("Comment density calculator\n");
/* Switch to comments on '/*' */
<INITIAL>"/*" { COMM ; BEGIN(INCOMMENT) ; }
<INCOMMENT>"*/" { COMM ; BEGIN(INITIAL) ; }
<INCOMMENT>.|\n { COMM ; }
/* Switch to string mode on '"' */
<INITIAL>\" { CODE ; BEGIN(INSTRING) ; }
<INSTRING>\\\" { CODE ; } /* Escaped quote. */
<INSTRING>\" { CODE ; BEGIN(INITIAL) ; }
<INSTRING>.|\n { CODE ; }
<INITIAL>['](\\)?\"['] { CODE ; } /* Character quote. */
<INITIAL>.|\n { CODE ; }
<<EOF>> { return 0 ; }
%%
int main() {
yyFlexLexer().yylex() ; /* modified for C++ */
/* Prints code bytes, comment bytes, comment density. */
printf("%u %u %lf\n",
code,
comm,
(double)comm/(double)(code+comm)) ;
return EXIT_SUCCESS ;
}