1 /*	$NetBSD: scanner.l,v 1.1.1.1 2009/10/26 00:29:25 christos Exp $	*/
2 
3 /*
4  * This file is part of flex.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * Neither the name of the University nor the names of its contributors
17  * may be used to endorse or promote products derived from this software
18  * without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
22  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE.
24  */
25 
26 %{
27 /* A template scanner file to build "scanner.c".
28    Run as:
29           test-lineno-r    # report flex's yylineno
30           test-lineno-r 1  # report count_newlines(stdin)
31 */
32 
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include "config.h"
36 
37 %}
38 
39 %option 8bit outfile="scanner.c" prefix="test"
40 %option nounput nomain noyywrap yylineno reentrant
41 %option warn
42 
43 WORD [[:alpha:]]+
44 DIGIT [[:digit:]]
45 
46 %%
47     /* The goal here is to test the yylineno processing by:
48        - providing some rules than CAN match newlines and
49          other rules that can NOT match newlines,
50        - matching several newlines in one rule,
51        - directly modifying yylineno.
52     */
53 
54 "yylineno++"          yylineno++;
55 "yylineno--"          yylineno--;
56 [[:blank:]]+
57 {WORD}
58 {DIGIT}+(\n{DIGIT}+)*
59 \n
60 .
61 <<EOF>>  { printf("%d\n", yylineno);
62            yyterminate();
63          }
64 
65 %%
66 
67 /* returns number of '\n' characters in input, plus one.
68    This is what flex does, essentially. */
69 
70 static int
71 count_newlines (FILE* in)
72 {
73     int n=1,c;
74     while ((c=fgetc(in)) != EOF)
75         if( c == '\n')
76             n++;
77     return n;
78 }
79 
80 int main ( int argc, char** argv );
81 
82 int
83 main (argc, argv)
84     int argc;
85     char ** argv;
86 {
87     if( argc > 1 )
88         printf("%d\n", count_newlines(stdin));
89 
90     else{
91         yyscan_t s;
92         yylex_init(&s);
93         yyset_in(stdin,s);
94         yyset_out(stdout,s);
95         yylex(s);
96         yylex_destroy(s);
97     }
98     return 0;
99 }
100