cloc.l

来自「基于微软的 ASP.NET+C#开发的PETSHOP(网上宠物店)项目,在性能及」· L 代码 · 共 177 行

L
177
字号
%option batch never-interactive 8bit noreject noyymore noyywrap

%{
#define YY_DECL static int yylex(int start_state)

static int line_count= 0;
static bool line_has_content= false;

static void count_line();
static void eat_comment();
static void eat_string();
%}

ws			[ \a\b\f\r\t\v]+
comment		\/\*
remark		\/\/[^\n]*
qstring		\"((\\.)|[^\n\\"])*[\"\n]
sqlremark	\-\-[^\n]*
sqlstring	\'((\\.)|[^\n\\'])*[\'\n]
%x CODE SQL

%%

%{
	BEGIN start_state;
%}

"<%"		BEGIN CODE;

<CODE>{
{qstring}	eat_string();
{remark}	;
{comment}	eat_comment();

"%>"	{
			count_line();
			BEGIN INITIAL;
		}
}

<SQL>{
{sqlstring}	eat_string();
{sqlremark}	;
{comment}	eat_comment();
}

<*>{
{ws}	;
.		if(YYSTATE != INITIAL) line_has_content= true;
\n		if(YYSTATE != INITIAL) count_line();
}

%%

static void count_line()
{
	if(line_has_content)
	{
		line_has_content= false;
		line_count++;
	}
}

static void eat_comment()
{
	int ch;
	bool half= false;

	while(ch= yyinput(), ch != EOF)
	{
		if(half)
		{
			if(ch == '/')
				break;
			else if(ch != '*')
				half= false;
		}
		else
		{
			if(ch == '*')
				half= true;
		}
	}

	if(ch == EOF)
		fputs("warning:  unterminated comment\n", stderr);
}

static void eat_string()
{
	line_has_content= true;

	if(yytext[yyleng - 1] == '\n')
	{
		count_line();
		fputs("warning:  unterminated string literal\n", stderr);
	}
}

static void simple_count()
{
	int ch;

	while(ch= getc(yyin), ch != EOF)
	{
		if(ch == '\n')
			line_count++;
	}
}

static int usage(char const* prog)
{
	fprintf(stderr, "usage:  %s [-all | -code | -sql] [file]\n", prog);
	return 2;
}

int main(int argc, char* argv[])
{
	char const* prog= argv[0];
	bool count_all_lines= false;
	int start_state= INITIAL;

	if(argc > 1 && argv[1][0] == '-')
	{
		switch(argv[1][1])
		{
		case 'a':
			count_all_lines= true;
			break;

		case 'c':
			count_all_lines= false;
			start_state= CODE;
			break;

		case 's':
			count_all_lines= false;
			start_state= SQL;
			break;

		default:
			return usage(prog);
		}

		argc--;
		argv++;
	}

	switch(argc)
	{
	case 2:
		yyin= fopen(argv[1], "rt");
		if(yyin == NULL)
		{
			fprintf(stderr, "%s:  cannot open %s for reading\n", prog, argv[1]);
			return 1;
		}
		break;

	case 1:
		yyin= stdin;
		break;

	default:
		return usage(prog);
	}

	if(count_all_lines)
		simple_count();
	else
		yylex(start_state);

	printf("%d\n", line_count);

	return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?