LEX rule, anyone???

Rich Salz rsalz at bbn.com
Wed Dec 6 02:32:25 AEST 1989


In <601 at vice2utc.chalmers.se> d5kwedb at dtek.chalmers.se (Kristian Wedberg) writes:
>A question from a friend of mine, P{r Eriksson:
>	Does anyone know how to write a LEX rule for C comments,
>	ie for everything between /* and */, nesting not allowed?

We go through this in comp.lang.c about once a year.  Almost everyone
gets it wrong.  The best thing to do is to define a lex rule that
catches "/*" and in the actions for that rule look for */ on your own.

The following code fragment comes from the Cronus type definition compiler:

/* State of our two automata. */
typedef enum _STATE {
    S_EAT, S_STAR, S_NORMAL, S_END
} STATE;

"/*"	        {
		    /* Comment. */
		    register STATE	 S;

		    for (S = S_NORMAL; S != S_END; )
			switch (input()) {
			case '/':
			    if (S == S_STAR) {
				S = S_END;
				break;
			    }
			    /* FALLTHROUGH */
			default:
			    S = S_NORMAL;
			    break;
			case '\0':
			    /* Warn about EOF inside comment? */
			    S = S_END;
			    break;
			case '*':
			    S = S_STAR;
			    break;
			}
		    /* NOTREACHED */
		}
-- 
Please send comp.sources.unix-related mail to rsalz at uunet.uu.net.
Use a domain-based address or give alternate paths, or you may lose out.



More information about the Comp.lang.c mailing list