16.6 Sling Commands


 
Building Parsers with Java
By Steven  John  Metsker

Table of Contents
Chapter  16.   Parsing an Imperative Language

    Content

There are three commands in the Sling language: plot , assignment , and for . The for command is syntactically different from a Java for command, but its function is similar. The plot command and the assignment command need application-specific implementations in sjm.examples.sling .

16.6.1 AddFunctionCommand

This command encapsulates a user 's plot command. Internally, the Sling parser does not actually start drawing when it parses a plot command. Rather, the parser uses an assembler to place an AddFunctionCommand object on an assembly's stack. Figure 16.22 shows AddFunctionCommand .

Figure 16.22. The AddFunctionCommand class. An AddFunctionCommand object holds a SlingFunction object that it evaluates and adds to a collection when the command executes.

graphics/16fig22.gif

Consider the program

 for (r, 3, 5) {      plot sling(r, 1); } 

When the Sling parser encounters the plot command, it creates and stacks an AddFunctionCommand command that creates the function sling(r, 1) . When the parser completes its parse of the for command, it creates a ForCommand object whose body command is the AddFunctionCommand command.

After parsing, the mediator executes the ForCommand object, which in turn repeatedly executes the AddFunctionCommand command. When this command executes, it evaluates the function, creating a plottable function that does not contain variables .

The AddFunctionCommand object in the for loop executes three times and adds three plottable functions to a function collection. These functions are sling(3, 1) , sling(4, 1) , and sling(5, 1) .

16.6.2 AssignFunctionCommand

An AssignFunctionCommand object, when executed, evaluates a function and sets it as the value of a variable. Figure 16.23 shows AssignFunctionCommand .

Figure 16.23. The AssignFunctionCommand class. When an AssignFunctionCommand object executes, it evaluates its function and assigns this value to its variable.

graphics/16fig23.gif

Consider the Sling program

 for (base, 7, 10) {      r = base + 3*sin(7*2*pi*t);     plot sling(r, 3); } 

The Sling parser builds a ForCommand object representing this program. When this command executes, it executes its body four times. Each time the body executes, it evaluates

 base + 3*sin(7*2*pi*t) 

and assigns the value to the variable r . Each time the plot command executes, it evaluates its function, using the then-current value of r , so that four different functions accumulate. After the for loop executes, the mediator plots the four functions.


   
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