5.5 Coffee Assemblers


 
Building Parsers with Java
By Steven  John  Metsker

Table of Contents
Chapter  5.   Parsing Data Languages

    Content

The coffee grammar suggests the need for six assemblers, which define actions to take upon seeing a name, a former name , a roast, the /French qualifier, the country, and the price. Figure 5.2 shows the assemblers and other classes in the coffee package.

Figure 5.2. The coffee package. This package contains classes that collaborate to create a Coffee object from text.

graphics/05fig02.gif

Figure 5.3 shows where the assemblers plug in to the subparsers of the CoffeeParser class.

Figure 5.3. Coffee assembler placement. This table shows the assembler that each coffee subparser employs.

graphics/05fig03.gif

5.5.1 Coffee Assembler Code

The NameAssembler class is typical of the assemblers that build a Coffee object. This assembler pops a coffee's name from an assembly's stack and sets the assembly's target to be a new Coffee object with this name.

 package sjm.examples.coffee;  import sjm.parse.*; import sjm.parse.tokens.*; /**  * This assembler pops a coffee's name...  */ public class NameAssembler extends Assembler { public void workOn(Assembly a) {     Coffee c = new Coffee();     Token t = (Token) a.pop();     c.setName(t.sval().trim());     a.setTarget(c); } } 

For the most part, the coffee assemblers pop a token off the stack, extract the meaningful part of the token, and update the target Coffee object. The NameAssembler class has the special job of placing a new Coffee object as the assembly's target. One other point is that the assemblers that pop a string may have to trim blanks from the end of the string because the tokenizer allows blanks as characters inside a word.

Classes similar to NameAssembler assign the coffee's former name, roast, and country. An assembler for handling the /French qualifier does not pop anything; it just sets this attribute of the target coffee to be true . An assembler for the coffee's price is also similar, but it pops a token and not a number. This assembler takes care to set the coffee's price to the number value of the token, using the nval() method of Token .

With the assemblers in place, you can translate the grammar directly to code.


   
Top


Building Parsers with Java
Building Parsers With Javaв„ў
ISBN: 0201719622
EAN: 2147483647
Year: 2000
Pages: 169

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net