Using Lex (and Yacc) on a string.

Pat Broderick ptb at ittc.wec.com
Sat Aug 11 00:41:51 AEST 1990


In article <1990Aug10.012927.5558 at basho.uucp>, john at basho.uucp (John Lacey) writes:
> Normally, of course, one wants a scanner (and a parser) to work from 
> a file, perhaps stdin.  Sigh.  Well, I want one that works from a string.
> ...

Recently I had occasion to do something similar.  What we did was
roughly as follows:

   - strings to be parsed are maintained in memory 
   - to parse a string a global pointer known to lex is set to point at
     the beginning of the string
   - the input() macro was redefined in terms of this pointer (standard
     uses getc(yyin))

The things needed might look something like:

LEX:

# define input() (((yytchar=yysptr>yysbuf?U(*--yysptr):getc(yyin))==10?(yylineno++,yytchar):yytchar)==EOF?0:yytchar)   /* standard defn from lex */

# define input() (((yytchar=yysptr>yysbuf?U(*--yysptr):(*yynyy++))==10?(yylineno++,yytchar):yytchar)==EOF?0:yytchar)                   ^^^^^^^^^^

					/* modified defn to use string */

extern char *yynyy;			/* will pt to start of string */


Function invoking parser:

char *yynyy;			/* globally visible */

....

    yynyy = start_of_string;
    yyparse();


This works fine for us, hope it helps.
-- 
Patrick T. Broderick           |ptb at ittc.wec.com |
                               |uunet!ittc!ptb   |
                               |(412)733-6265    |



More information about the Comp.unix.questions mailing list