Lab 1A Installing the Javacc Eclipse Plug-In

Total Page:16

File Type:pdf, Size:1020Kb

Lab 1A Installing the Javacc Eclipse Plug-In

COMP501 Laboratory Assignments Fall 2012

Table of Contents

Labs submitted on time are graded on a scale 0..10. Late labs lose 2 points for each week or part of week they are late with an absolute cutoff after 3 weeks.

Lab 1A Installing the JavaCC eclipse plug-in

1. This lab uses JavaCC as an eclipse plug-in. 2. Get the plug-in from http://eclipse-javacc.sourceforge.net/ 3. Make sure your installed versions of the Java .jdk and eclipse are compatible with the plug- in. Upgrade them if not. 4. Follow the instructions at http://eclipse-javacc.sourceforge.net/ for setting up a Java project using JavaCC. 5. Download the simple calculator examples. 6. Try out JavaCC with the simple calculator example: Calc1i.jj 7. Copy Calc1i.jj to a temp folder, such as C:\Temp\Mw . 8. In your DOS window, cd C:\Temp\Mw 9. type: JavaCC Calc1i.jj 10. This creates several .java files 11. to compile, you can use javac as in Javac *.java to compile all java files in your folder 12. To run, type: java Calc1i, then enter an arithmetic expression to evaluate. 13. To view the .jj and .java files, you can use eclipse, Visual Studio, or any text editor. 14. You do not have to submit this lab

Lab 1B (optional) install JavaCC

Purpose: To install JavaCC if you don’t want to use the eclipse plug-in and practice using it with simple calculator examples.

1. Install JavaCC (if not already there).

o Download from The Java Compiler Compiler home page. Use the most recent stable version (currently 4.0).

o To install, unzip and extract all files including folder names to C: . The files will be installed in C:\javacc-4.1. For convenience in setting environment variables I advise changing the folder name to JavaCC.

2. Change the PATH and CLASSPATH to include java, javac and javacc as below.

Professor M Werner 1 01/18/18 COMP501 Laboratory Assignments Fall 2012

3. The first step is to use Explore to find out where these programs are located. For example in my computer javacc is located in C:\JavaCC\bin, and javac in C:\j2sdk1.4.2_15\bin.

4. One approach is to edit the PATH and CLASSPATH environmental variables. To do this, open the control panel, click on system, choose the advanced tab click on environment variables. Modify (or add) user variables named PATH and CLASSPATH.

PATH should lead to the sdk bin folder, and CLASSPATH to the javacc lib folder.

These values may work:

CLASSPATH: C:\j2sdk1.4.2_15\lib;C:\JavaCC\bin\lib;.;C:\... //note: must include .;

PATH: C:\j2sdk1.4.2_15\bin;C:\JavaCC\bin;C:\....

Another approach is to change it within your DOS command window, as with

set PATH= C:\j2sdk1.4.2_15\bin;C:\JavaCC\bin;%PATH%

set CLASSPATH C:\j2sdk1.4.2_15\lib;C:\JavaCC\bin\lib;.;

Open a DOS Command Prompt. Try typing javacc and javac to make sure the system can find and launch these programs. You should get some usage messages.

Professor M Werner 2 01/18/18 COMP501 Laboratory Assignments Fall 2012

5. Download the simple calculator examples.

6. Try out JavaCC with the simple calculator example: Calc1i.jj

7. Copy Calc1i.jj to a temp folder, such as C:\Temp\Mw .

8. In your DOS window, cd C:\Temp\Mw

9. type: JavaCC Calc1i.jj

10. This creates several .java files

11. to compile, you can use javac as in Javac *.java to compile all java files in your folder

12. To run, type: java Calc1i, then enter an arithmetic expression to evaluate.

13. To view the .jj and .java files, you can use eclipse, Visual Studio, or any text editor.

14. You do not need to submit this lab.

Lab 2 Using JavaCC with actual languages due Oct 5

Purpose: To gain facility with using JavaCC with actual languages.

Project:  Build a parser for Java 1.5  Add actions to count various things such as o Class definitions o Method definitions

Test by running the parser to scan in a java source file and print out the counts.

1. Get a version of a Java .jj file. You could use the one from Blackboard titled Java 1.5 Grammar .jjt file (Slightly modified). I had to doctor this file to get it to work. Specifically I commented out certain unsigned bitwise shift operators. So your parser won't work for any java program that uses them. Maybe one of you can figure out a way to get them back in. I couldn't. 2. Start a new java project in eclipse and a new JavaCC template using the options .jjt and static=false. 3. Replace MyNewGrammar.jjt with the one from Blackboard. 4. Open the file in an editor to get a sense of how it works. 5. Save the file. This will generate the java and class files. There should be no errors. 6. You will need to adjust the CLASSPATH environment variable to search the current folder. You do this in Windows by going to the control panel, drilling down to the System advanced settings and editing the CLASSPATH. Keep everything that is there and preceed by “.;”. 7. Open a command prompt. 8. Check the CLASSPATH by typing “set”. On my computer I got: CLASSPATH=.;C:\j2sdk1.4.2_15\lib;C:\Program Files\Java\jre6\lib

Professor M Werner 3 01/18/18 COMP501 Laboratory Assignments Fall 2012

9. Navigate to the .bin folder of you project. 10. Run by typing: java JavaParser . i.e. on my computer I got: C:\eclipse\workspace\Java_Grammar1_5\bin>java JavaParser ../src/Token.java Java Parser Version 1.1: Reading from file ../src/Token.java . . . Java Parser Version 1.1: Java program parsed successfully. 11. Modify the .jj file to add actions when certain non-terminals are parsed 12. For starts, just add some println statements as in:

C:\eclipse\workspace\Java_Grammar1_5\bin>java JavaParser ../src/Token.java Java Parser Version 1.1: Reading from file ../src/Token.java . . . I parsed a MethodDeclarator for getValue I parsed a constructor declaration for Token I parsed a constructor declaration for Token I parsed a constructor declaration for Token I parsed a MethodDeclarator for toString I parsed a MethodDeclarator for newToken I parsed a MethodDeclarator for newToken Java Parser Version 1.1: Java program parsed successfully.

8. Add static counters to the JavaParser class, increment them when various things are found, and print the counts at the end.

Submit only the .jj file and a screen shot of the resultant counts.

Lab 3Building a Parser and Evaluator for a Mini-Language due Oct 7

WitEval is a simple mini-language developed at Wentworth Institute of Technology.

A sample expression in WitEval is:

[alpha = 2.5, beta = 10, gamma = -0.1 | alpha * alpha + alpha * beta + 13, 2 * (gamma + 1)]

The expression consists of 2 parts separated by a vertical line.

The first part declares and initializes variables. Variable names follow the same rules as in Java or C. Numeric literals are assumed to be of type float whether they have a decimal point or not.

The second part contains a list of arithmetic expressions to be evaluated. The usual operators, namely + - / * are available, as well as parentheses for grouping.

White space is ignored.

When the WitEval expression above is run through the WitEval interpreter, two answers are printed out; namely 44.25, 1.8.

1) Write a grammar in EBNF for the WitEval language.

Professor M Werner 4 01/18/18 COMP501 Laboratory Assignments Fall 2012

2) Translate your grammar into a .jj file

3) Build a parser with JavaCC. Try it on a sample WitEval input.

4) As in Lab 2, add some actions to the .jj file so as to print out variable names and their values when variables are defined and initialized.

Lab 4 Building WitEval to evaluate expressions due Oct 14

This is a continuation of Lab 3. You are to enhance the parser in Lab 3 to:  Store variables and their values in a symbol table as they are encountered in the initialization part.  Build an evaluator for WitEval expressions.

Symbol Table: Add a member variable of type Hashtable to the parser class. Initialize it to a new Hashtable. When a variable definition is encountered put the name (as key) and its value (wrapped as a Float) in the hash table. To retrieve the value use get with the variable name as key. This example may help.

This example creates a hashtable of numbers. It uses the names of the numbers as keys: Hashtable numbers = new Hashtable(); numbers.put("one", new Float(1)); numbers.put("two", new Float(2)); numbers.put("three", new Float(3));

To retrieve a number, use the following code: Float n = (Float)numbers.get("two");

Evaluator: When a WitVal expression is complete you need to return its value.

 Before building the evaluator make sure your WitEval grammar is correct and you can build a JavaCC program that parses any WitEval expression.  The LHS of a WitEval expression initializes variables to values. When you parse one of these initializations you need to get the variable name and its initial value. Store the value in the symbol table using the name.  The RHS of a WitEval expression has a list of expressions to evaluate. Expressions are made up of terms, terms of factors, factors may be float values, id’s,, etc.  The productions for expressions, terms, etc. should return a float representing their value.  The value of an id is found by looking it up in the symbol table (and casting it to a Float).  When the value of an expression is found it is printed out. Lab 4b Adding Functions to WitEval (optional for extra credit 4 pts)

The WitEval language has been extended to support functions. A function is basically a named WitEval expression, restricted to have only one output. Its initialization part permits a mix of local variable declarations and parameter declarations. Each function has its own name space.

Professor M Werner 5 01/18/18 COMP501 Laboratory Assignments Fall 2012

Here is a sample WitEval expression that declares and uses a function. The function is named area. It is declared in the initialization part. It has a local variable named pi and a parameter named radius. All parameter passing is by value. The >> operator identifies radius as a parameter. The evaluation part of the area function returns pi * radius * radius.

The area function is called twice in the evaluation part of the program, the first time with r1 as the actual parameter, the second time with r2. The results are summed. Multiple parameters are separated by commas.

[r1 = 10, r2 = 7.5, area[pi = 3.14, >> radius | pi * radius * radius] | area [ r1] + area [ r2]]

The lab assignment is to rework labs 3 and 4 to support functions. For variable storage use a stack of hashtables. When a function is called a new hashtable is constructed and pushed on the stack. When it returns the hashtable is popped.

Lab 5 due Oct 21 Regular expressions, fsa’s and code

Follow this example:

1) Write a regular expression for strings over the alphabet {a,b} that end in “ab”

(a|b)*ab

2) Draw an nfa that matches your regular expression. Label the states: b a

A a B b C a

3) Transform to a DFA

b a

{A} a {A,B} b {A,C} a b

4) Relabel the states

Professor M Werner 6 01/18/18 COMP501 Laboratory Assignments Fall 2012

b a

1 a 2 b 3 a b 5) Write a lex() function that matches your automaton. There is a single word in the input buffer. lex() returns true if it ends up in a final state when all the letters in the word have been consumed, false otherwise.

/* lexical analyzer */ char buffer; boolean getChar(); //gets the next input character into buffer //returns false if eof, otherwise returns true boolean lex(){ //returns true if input string is in the language int state = 1; //start state while(getChar()){ switch(state){ case 1: if(buffer=='a'){ state = 2; } break; case 2: if(buffer=='b'){ state = 3; } break; case 3: state = 1; } } return state==3; //i.e. if eof is reached in a final state return true }

Your assignment: Do all the above for the language consisting of strings containing “aa” followed immediately or later on by “bb”. i.e. the string “abaaabababbabab”

Lab 5b Using Lex and Yacc to build a bottom-up parser (optional lab for extra credit)

1. Download and install the Flex (lex) and Bison (yacc) package from http://gnuwin32.sourceforge.net/packages/bison.htm and http://gnuwin32.sourceforge.net/packages/flex.htm

Note: If you use Linux it has already been installed.

2. Add the folders containing bison.exe and flex.exe to the PATH

3. Read a tutorial: A Compact Guide to Lex & Yacc by Tom Niemann

Professor M Werner 7 01/18/18 COMP501 Laboratory Assignments Fall 2012

4. Test it out by using lex and yacc to generate C code for a simple calculator. The source files are available from Niemann’s site.

5. Submit evidence that you have done this, i.e. a sample run using your calculator.

Lab 5c Using Lex and Yacc to build a bottom-up parser for the WitEval language (optional lab for extra credit)

1. Build a lexer and a parser for the WitEval language.

2. Use your parser to evaluate WitEval expressions.

Lab 6 Using Scheme to describe pictures due Nov 30

1. Download and install Racket from http://racket-lang.org/. 2. Run DrRacket. 3. Press on the Language menu. Choose the first radio button: Use the Language declared in the source. 4. As a way of getting introduced to scheme, follow the tutorial: Quick: An Introduction to PLT Scheme with Pictures . 5. Submit evidence of having completed the tutorial, i.e. you could submit a picture showing your initials built up from geometric objects such as circles and rectangles. Naturally include the code that produced the picture.

Lab 7 Writing Scheme Functions due Dec 5

2. Practice arithmetic. Translate the following expressions into prefix and evaluate in scheme.  27.5 + 18*(3 + 4 + 5)  (7/9) +(5/4)  sqrt(10 - 3*(5.5))

3. Write a function to evaluate 2x2 - 5x + 12 for argument x

4. Write a function to find the area of a circle, given the diameter.

5. Write a recursive function named count-up, which is passed a list as an argument and returns the length of the list.

6. Write a recursive function named add-numbers, which is passed a mixed list of symbols and numbers, and returns the sum of the numbers.

ex. (add-numbers '(A 60 RALPH 5)) returns 65

Professor M Werner 8 01/18/18 COMP501 Laboratory Assignments Fall 2012

7. Write a function, which is passed a symbol S and a list lst, and returns true if S is in lst, false otherwise.

8. Write a function, which when passed a positive integer n, returns 1 + 2 + ... + n .

9. Write a function named count-all, to count all the symbols in lists, which may contain sublists.

ex. (count-all '(A (B C) D E)) returns 5

10. Write intersection. It returns the set intersection of two lists.

11. Write copy. It builds a copy of a list using new cons cells.

Submit a file containing your scheme function definitions and screen shots showing the results of calling the functions on various inputs.

Lab 8 More Scheme Functions due Dec 9

1. Define reverse. It reverses a list.

2. Define power. It takes two arguments, b and e and raises b to the power e. Use recursion.

3. Define harmonic. When given an argument n, harmonic returns the sum: 1 + 1/2 + 1/3 + ... + 1/n .

4. symbol? is a built-in function that returns #t if its argument is a symbol, #f otherwise. Define a function named allsymbols?, which is passed a list and returns true if every element in the list is a symbol, false otherwise.

5. Define remove, which takes 2 arguments, an atom a, and a list lst. It returns lst with all instances of a removed.

6. Define Rotate-Left, a function that takes a list as its arguments and returns a new list in which the former first element becomes the last: example: (rotate-left '(a b c)) results: (B C A) example: (rotate-left(rotate-left '(a b c))) results: (C A B)

7. Try out the following function: (define (squareall) (begin (display "Enter a list of numbers in parentheses> ")

Professor M Werner 9 01/18/18 COMP501 Laboratory Assignments Fall 2012

(let ( (lst (read)) ) (display (map (lambda (x) (* x x)) lst)) ))) 8. Using #7 as an example, write a function that asks the user to type in a list, and prints it out reversed.

Lab 9 – Prolog due Dec 12

Part I Choose Method A or Method B

Method A – Using Current Version of AMZI in Eclipse

1A. Download and install the free version of anzi prolog from http://www.amzi.com/download/index.htm 2A. The current version of amzi prolog runs as an eclipse plug-in. From the computer’s start menu you can select the program AMZI! IDE and run it. This brings up eclipse.

3A. Start a new project named family.

After pressing Next, name the project family on the next screen.

In the Navigator, right-click on family and add a new file, named family.pro.

Professor M Werner 10 01/18/18 COMP501 Laboratory Assignments Fall 2012

Method B – Using an Older Stand-Alone Version of AMZI

1B Download the installation executable posted on Blackboard.

2B Install on your computer. You may need to reinstall using recommended settings.

3B Run the program.

Part 2. Try out prolog.

Type in a few facts into the edit window like this:

%%family.pro duck(donald). duck(daisy).

The facts also appear in the Outline window, and the Cross Ref window (after a refresh).

Professor M Werner 11 01/18/18 COMP501 Laboratory Assignments Fall 2012

From the Menu, select run as interpreted project. This opens the listener.

You can now try some queries in the listener.

?- duck(donald). yes ?- duck(X).

X = donald f

X = daisy f no ?- Enter the following Prolog code. Please make sure that you maintain case sensitivity:

%%CLAUSES

Professor M Werner 12 01/18/18 COMP501 Laboratory Assignments Fall 2012 parent(john,anthony). parent(david,tony). parent(john,charles). parent(pat,brandi). parent(john,peter). parent(pat,tony). parent(john,carmella). male(john). parent(john,louise). male(anthony). parent(john,rosemary). male(charles). parent(john,john f.). male(peter). parent(rose,anthony). male(john f). parent(rose,charles). male(michael). parent(rose,peter). male(david). parent(rose,carmella). male(tony). parent(rose,louise). female(rose). parent(rose,rosemary). female(carmella). parent(rose,john f.). female(pat). parent(anthony,michael). female(louise). parent(anthony,david). female(marlene). parent(marlene,michael). female(brandi). parent(marlene,david). female(rosemary). parent(david,brandi).

%%Rules grandparent(X,Y):-parent(X,Z),parent(Z,Y). father(X,Y):-parent(X,Y),male(X). mother(X,Y):-parent(X,Y),female(X).

4. Start a listener and try these goals:  grandparent(A,brandi).  grandparent(rose,tony).  parent(anthony,X).  mother(rose,Y).

5. Add the following information to the program:

 carmella is a parent of peter j., john p., and maria  charles is the parent of thomas, steven and dino  thomas has children sandra and hunter  deena is the mother of sandra and hunter

6. Add rules to define grandfather and grandmother.

7. Add rules to define sister, brother, siblings, cousin, aunt and uncle. We can fix the problem of individuals being their own siblings by using the built-in predicate that succeeds if two values are unequal, and fails if they are the same. The predicate is \=(X,Y).

8. Test your rules on the data.

Submit the rules you wrote and evidence that they work properly.

Professor M Werner 13 01/18/18 COMP501 Laboratory Assignments Fall 2012

Lab 10 List Processing using Prolog due Dec 12 (optional)

Write list utilities that perform the following functions.

1. Remove a given element from a list 2. Find the element after a given element 3. Split a list into two lists at a given element (Hint - append/3 is close.) 4. Get the last element of a list 5. Count the elements in a list (Hint - the length of the empty list is 0, the length of a non- empty list is 1 + the length of its tail.) 6. Find the set union of two lists 7. Write merge. It takes two sorted lists of numbers as it first two arguments, the third argument is the merged list. i.e. ?- merge([1,4,5],[2,3,4,6,7],X) yields X = [1,2,3,4,4,5,6,7].

Lab 11 Prolog and Scheme for the same tasks due Dec 12 (optional)

For each of the following, write as a Scheme function and a Prolog predicate

1. member – returns true if an element is a member of a list 2. intersection – finds the intersection of two lists considered as sets 3. reverse – reverses a list 4. deep-reverse – reverses a list and all its sublists 5. minimum – finds the lowest number in a list of numbers 6. sort – sorts a list ascending

Professor M Werner 14 01/18/18

Recommended publications