Вы находитесь на странице: 1из 298

ECE 4899: Senior Design

Final Report: Verilog


Linting Tool
UCCS

Kenneth Hassey, Danny Dauwe


5/13/2013

Sponsor\Advisor: Dr. Greg Tumbush

ECE 4899

Final Report: Linting Tool

Table of Contents
Abstract ...................................................................................................................................................... 2
Introduction ................................................................................................................................................ 3
Details of Procedure: .................................................................................................................................. 6
Results ........................................................................................................................................................ 8
Discussion and Conclusion .......................................................................................................................... 9
Appendix ................................................................................................................................................... 12
User Interface ....................................................................................................................................... 12
Description of the Linting Tool Parsers Class Hierarchy ....................................................................... 15
User Guide For Running the Linting Tool for the First Time .................................................................. 19
Guide For Running the JNLP Creator ..................................................................................................... 23
Linting Tool Code Files .......................................................................................................................... 28

ECE 4899

Final Report: Linting Tool

Abstract

The ECE 4242 Advanced Digital Design Methodologies course as well as several other courses at
University of Colorado at Colorado Springs teach students about digital design techniques and place
emphasis on the Verilog hardware description language. The students learn syntax needed to code in
Verilog, as well as methods to simulate their code. They also learn how to synthesize their Verilog code
designs to gate level schematics for FPGA devices. However, because simulation and synthesis are
separate processes, a student may find that his or her correctly simulating design may not be
synthesizable into gate level logic.
In an attempt to help prevent this problem from occurring and to improve the quality of student
Verilog code the instructor for these Verilog courses and sponsor for the project Dr. Greg Tumbush
requested the design of a Verilog Linting Tool that is capable of checking a students Verilog code for
errors that would prevent it from being synthesizable.
The Verilog Linting Tool was designed and built using the java programming language and the
java runtime environment in order to be able to continue to add new Errors after the tools initial
publication, and to allow easy building and running of the executable jar file after setup. The solution
linting tool that has been built is able to detect and report to the user the presence of up to 17 different
code errors that would prevent the Verilog code from being synthesizable. The tool is also able to be
run on several different operating system platforms, and was tested and verified to work on Mac OSX,
Windows 7, Windows 8, and Windows XP.

ECE 4899

Final Report: Linting Tool

Introduction
The University of Colorado at Colorado Springs offers several courses that require students to
write behavior-modeled digital design code using the Verilog hardware description language.
Consequently students also need a way to check for synthesis errors in their Verilog Hardware
Description Files. A linting tool that is capable of checking these files for synthesis error was requested
for students to use in these classes. UCCS students do have access to a professional linting tool, but this
professional tool requires a remote service to be started, students are inconvenienced by the necessity
of logging into a linux virtual machine, and then subsequently spending time setting up the tool. This is
a very time consuming, and inconvenient process for the students to check their Verilog files for
synthesiazability.
The request for making a new Linting Tool that will remedy these issues was made by the
project sponsor and advisor Dr. Tumbush for the improvement of the classes that he teaches. The new
tool needed to be able to be more easily accessable to all students regardless of their preferred
operating system and access to a remote connection client. The tool itself must be able to be updated
easily and as hassle free as possible for both the project sponsor hosting the tool as well as the students
of UCCS using the tool. The solution tool needs to stay up to date with the current errors and updates
that were incorporated into the tool at any given time. Next, the tools GUI must be as easy and
straightforward as possible because the tool was going to be used by students with various
technological skills. After assessing these requirements our team made the decision for developing the
new linting tool in the Java programming language.
Two of the main reasons Java was chosen was that some of the services it offered such as Java
Web Start and the Java Virtual Machine. Java Web Start is a program built into the Java Runtime
Environment that allows web-hosted programs to be downloaded and run on the users local machine.

ECE 4899

Final Report: Linting Tool

It also monitors the download location where the tool was received from and checks for updates every
time the program is run again. If an updated version of the program is found it is automatically
downloaded to the users local machine, therefore keeping the tool up to date. The Java Virtual
Machine then takes care of the requirement that the program must be able to be run on multiple
operating systems. Because java is an interpreted language that is run on the virtual Java Runtime
Environment it effectively has a Middle-man interpreting any specific instructions for the users
specific operating system and computer hardware. This eliminates any hardware and Operating Systemspecific dependencies that would prevent the Linting Tool from running on a users machine. Because
both team members have experience in java, and seeing that Java handles interpretation of code
between operating systems inherently, the Java programming language was chosen for accomplishing
the tasks that needed to be met for the tools design.
The way the group approached creating the tool was to have four main pieces to the too (All are
detailed in the appendix):
1. The Verilog code parser: this element of the design takes a users input Verilog code file and
uses it to create a virtual structure of the codes behavioral blocks, variable declarations,
assignment statements, and conditional statements. This virtual structure is saved in memory
and used to identify the errors in the file.
2. The Error Searcher: this element of the design uses the virtual structure of the code created and
passed to it from the parser in order to identify the specific errors present in the users Verilog
code.
3. The User Interface: As can be seen in Figure 1, Figure 2, and Figure 3 the user interface provides
a simple layout for the tool that hides all of the background work done during the Parsing and
Error Searching sections described above.

ECE 4899

Final Report: Linting Tool

4. Using Java Web Start: Java web start was used for hosting the tool in a way that could provide
user updates without the need for the user to continue to download the tool (though they can if
they prefer to). The details for updating the tool using Java Web Start provided to the sponsor
are detailed in the corresponding appendix section, but updating the tool using Java Web Start
happens seamlessly as far as the user is concerned.
Each of these pieces were written separately from each other, and were made over the courses of the
project by taking smalls steps at a time by incrementally adding structure items to parse and slowly
building what the parser could handle to a point where it is able to identify major code blocks and
behavior constructs in the Verilog Language. Then using this parsed structure, the first several synthesis
error checking classes could be coded in order to look through the identified structures for known
synthesis errors. As new types of behavioral code constructs and aspects of the Verilog laguage were
added to the parser the errors that need to be checked from those structures were then also added. For
example, classes that searched for errors present in always blocks were written only after the parser
was able to identify and parse always blocks into the virtual code structure. New Verilog test case files
were then written to verify the tools functionality and assure the errors are identified correctly.

ECE 4899

Final Report: Linting Tool

Details of Procedure:
After the initial planning of the project between the two team members and the project advisor
the Team members separated into two distinct roles. First, both team members would build the initial
files for storage class code. Then when the initial stages of the Linting Tool were done, one team
member would work on the Verilog code parser, while the other would work on writing the functions
that would search for errors, as well as developing the user interface and Java Web Start updater for the
tool.
The first step that needed to be done during parsing was to design a way of storing all the
constructs that could show up in the Users code. A Java class hierarchy was used for the storage and
parsing of items in the Verilog code file. Then using some very basic structure files and the existing class
hierarchy a group of class files were created to parse the basic behavior blocks, variable signal types,
and assignment statement types possible in the Verilog code. As development continued subsequent
types of behavioral blocks and code constructs were added, as well as the ability to detect new errors.
The final tool includes the ability to parse the following (Each of these pieces are discussed more
thoroughly in the corresponding section of the appendix discussing the parser):
1. Behavioral Code All behavioral blocks inherit from a generic Block class:
a. Module Block
b. Always Blocks
c. Case Blocks
d. For Loops
e. Functions
f.

If-Else Blocks

g. Module Instantiation Blocks

ECE 4899

Final Report: Linting Tool


h. Sub-Case Blocks
i.

Task Blocks

j.

While Loop Blocks

2. Variable Type Code Constructs: All Variable types inherit from a generic Variable class:
a. Reg variable
b. Wire variable
c. Task Call Instance variable
d. Function Call Instance variable
3. Assignment Statement Type Code Constructs:
a. Assignment Statements
b. Continuous assignments
c. Conditional Statements
When delays occurred or structures that werent identified were needed to be added to the
parser before the detection of more errors could take place, time from the second team member would
go into developing the GUI for the user interface as well as the JNLP file for the Java Web Start Service.
During this work automation files for building the packaged application and the JNLP Files were also
created.
Testing was done at every stage of the main engine and error searching functions. Testing
would be done by custom written Verilog test files, several that would pass and several that would fail,
to identify proper detection and structuring done by the parser and error searching functions. Also, at
the same time, backups were made of the code every three day to insure any functionality or integrity
of file problems could be rolled back to a previous date if necessary.

ECE 4899

Final Report: Linting Tool

Results
The Final Build of the tool was done on May 9, 2013 for presentation and student use. The final
tool is able to detect 17 errors as well as several parsing errors that will also be reported to the user.
The Java Web Start JNLP File is successfully built for every build of the tool, and a version number based
on the date and time ensures the version number of subsequent builds is always newer than the
previous build so that the tool will always remain up to date. A GUI was added and successfully displays
the errors that were detected, the file currently selected, and the files code with line numbers. With
interactivity, the GUI Supplies more information to the user about an error the tool has identified as well
as highlight which lines the errors are referring to.
It should be noted that the Linting Tool does not support the following aspects of Verilog code:
1. Trying to run the tool with code that does not compile correctly, the tool will give an error and
stop parsing
2. Analysis of parsed Sub-Module Instantiations
3. Analysis of parsed For loops
4. Analysis of parsed While loops:
5. Analysis of parsed Tasks
6. Analysis of parsed Functions
7. Analysis of Processor Directives
8. Parsing of Multi-Dimensional Arrays
9. Parsing of Named-Blocks
10. Parsing of ternary operators
11. Parsing of Pre-parsing parameters

ECE 4899

Final Report: Linting Tool

Discussion and Conclusion

The team feels that this project has been a success. While the final linting tool may not handle
the same level of Verilog code analysis as other professional tools, our linting tool successfully does
what it was intended to do by providing undergraduate UCCS students who are just starting to learn
Verilog a solid resource that they can go to in order to check the synthesizability of their Verilog code.

The final version of the tool is capable of:


1. detecting even more synthesis errors than was originally stipulated in the projects
requirements
2. Having a friendly user interface
3. Providing a solution that can be run across multiple operating systems
4. Providing a solution that is lightweight and easy for beginning Verilog coders to use in
comparison to some of the more professional tools
5. Providing a solution that automatically updates itself without hassle for the user
6. Highlighting of the locations of all aspects of the error (line number, code block, variable,
assignment statement, etc) so that a beginning user can more easily see what went wrong with
his or her code
7. Providing error documentation in the tool that will give a beginning Verilog coder:
a. A detailed description of what can cause the error
b. An example of poor Verilog code that would cause the error
c. Suggestion for how the user can fix the error if one occurs

ECE 4899

Final Report: Linting Tool

8. Providing the sponsor with information on how to update the tool to include new errors, this
aspect was planned for in advance so the linting tool also provides:
a. A Java class template for writing new errors
b. Information on how to integrate the new error into the linting tool after it is written
i. This was made as simple as possible, the sponsor should only need to include
the new class file into the project, and then add a single line to the
ErrorSearcher class calling an instance of that class, and passing it the parsed
virtual Verilog structure.
c. Information on how to build the new executable JAR file, and load it to the host website

Not every aspect of the Verilog Hardware Description Language is capable of begin run through
the tool (as evidence by the list of unsupported Verilog code constructs provided in the Results section
of this document), however the Verilog omissions that were made to the tool are relatively few and
furthermore several of them are more advanced Verilog concepts that fall outside of the scope the
tools intended use for students just beginning to learn the Verilog Hardware Description Language.

As for the Schedule, the originally planned schedule was not followed completely, but instead
the problems with bugs in the parser or unsupported constructs pushed some errors out while others
were done on time. The final schedule, in figure 4, below shows the final outcome of delays and bug

10

ECE 4899

Final Report: Linting Tool

fixes.

Figure 4: Final Schedule

This final schedule show where delays were and how the errors were mainly programmed in at the end
of the allotted time. If more knowledge was known about what to expect about the files that the users
were going to run through the machine then there may not have been as many bugs or changes to the
parser. This would have been a better outcome, but as it stands the parser and GUI came out in a
respectable format for the user.

11

ECE 4899

Final Report: Linting Tool

Appendix
User Interface
The User Interface: As can be seen in Figure 1, Figure 2, and Figure 3 the user interface provides a simple
layout for the tool that hides all of the background work done during the Parsing and Error Searching
sections described above. The user is provided with:
a. Three windows detailing information:
i. Files Open: Shows all of the Verilog code files that have been linted, if multiple
files have been loaded the user can click on the names of the files presented in
this window in order to change which Verilog code file data is displayed in the
File Data and Error Messages windows
ii. File Data: Displays the users code:
1.

It provides color coded keywords, comment text, and in-quote text

2. It highlights lines with errors in red when the user left-clicks on an error
in the Error Messages window
iii. Error Messages: Displays a list of the errors found in the Verilog file
1. If no errors are present then this window displays No Errors Detected
2. If the user Left-Clicks on an error the line numbers causing the error are
highlighted in the File Data window (As shown in Figure 2)
3. If the user Right-Clicks on an error then more detailed information
about the error is displayed for the user (An example of this is shown in
Figure 3)
b.

Two buttons:

12

ECE 4899

Final Report: Linting Tool


i. Load File: The user is prompted with a GUI file selection interface in order to
select a Verilog code file
ii. Remove File: Removes the currently highlighted file from the Files Open
window list

Figure 1: The Linting Tools User Interface

13

ECE 4899

Final Report: Linting Tool

Figure 2: An Example of the Linting tool identifying errors in Verilog code.

14

ECE 4899

Final Report: Linting Tool

Figure 3: An example of the user documentation giving an in-depth description of the error in question,
a code example of the error, and a description of what can be done to fix the error.

Description of the Linting Tool Parsers Class Hierarchy


As described in this documents Details of Procedure section, the tools parser has Four Main pieces:
1. Parser Class:
a. This class is what is called from the main portion of the program. The parser class is
responsible for the following steps before parsing begins:
i. Removing Comments
ii. Placing Line Numbers at the beginning of each line
iii. Putting the entire Verilog code file on a single line for parsing

15

ECE 4899

Final Report: Linting Tool


iv. Evenly spacing out tokens
v. Creating an Array of strings that can be analyzed for parsing
vi. Identifying Code Keywords that (such as timing controls) that will prevent
synthesizability
b. Once the pre-parsing is complete the parser creates a Top-Level Module type block
and begins parsing the file by creating a hierarchy of the modules sub-blocks,
Variable declarations, and Assignment Statements
c. The Parser has methods that are responsible for the following:
i. Methods involved in the pre-parsing work described above
ii. Identifying if a given string piece is a reserved Verilog keyword
iii. Resolving arithmetic expressions into decimal numbers
iv. Resolving all allowed Verilog Radix types to decimal numbers (and still
preserving dont care and high impedance types
v. Stopping Parsing if a pre-parsing, or mid-parsing error is found.

2. Behavioral Code blocks (note that a hierarchical diagram of these Block classes can be
seen in appendix Figure 2): All behavioral blocks inherit from a generic Block class that
includes the following functional pieces:
a. The data members responsible for identifying:
i.

the blocks name

ii. The blocks line number in the Verilog file


iii. Variable data types contained in the block
iv. Assignment statements contain in the block
v. A list of sub-blocks contained in the block
vi. A reference to the block that this block is contained in

16

ECE 4899

Final Report: Linting Tool


b. The Block class also includes methods that may be responsible for:
i. Adding sub-blocks to the virtual code structure as it is being parsed
ii. Searching for sub-blocks during error searching
iii. Searching for Variables During error searching
iv. Searching for Assignment statements during error searching
c. A List of the behavior code blocks present in the final tool:
i. Module
ii. Always Blocks
iii. Case Blocks
iv. For Loops
v. Functions
vi. If-Else Blocks
vii. Module Instantiation Blocks
viii. Sub-Case Blocks
ix. Task Blocks
x. While Loop Blocks

3. Variable Type Code Constructs: All Variable types inherit from a generic Variable class with
the following functional pieces:
a. Data members responsible for storing
i. Variable Name
ii. Variable type
iii. Variable Attributes
iv. Line Number of Declaration
v. Array Size

17

ECE 4899

Final Report: Linting Tool


b. Methods responsible for:
i. Getting and Setting Variable attributes
ii. Separating vector variables signals into a collection of signals
iii. Parsing and identifying variables, vectors, arrays, and memories from within
code lines and assignment statements
c. A List of Variable signal types supported by the tool:
i. Reg variable
ii. Wire variable
iii. Task Call Instance variable
iv. Function Call Instance variable
v. Parameter (and localparam) variable

4. Assignment Statement Type Code Constructs: Generic assignment statements are handled
by the AssignmentStatement class, with conditional statements and continuous
assignment statements inheriting from the AssignmentStatement class.
a. The AssignmentStatement class has data members responsible for the following:
i. Variables present on the Left Hand Side of the assignment statement
ii. Variables present on the Right Hand Side of the assignment statement
iii. A reference to the parent block that contains the assignment stamen
iv. The Line Number that the assignment statement occurs on
b. The AssignmentStatement class has methods responsible for the following:
i. Identifying variables on the Left Hand Side of the assignment statement
ii. Identifying variables on the Right Hand Side of the assignment statement
iii. Returning information about the assignment statement

18

ECE 4899

Final Report: Linting Tool

User Guide For Running the Linting Tool for the First Time
(Note: These instructions have been made available by the sponsor on his web page for the linting tool,
it is presented here as the user will see it, any changes in the formatting of this document that may be
seen is for this reason.)

Starting The Verilog Linting Tool

1. Click on "Download Verilog Linting Tool

2. Make sure "Open with Java(TM) Web Start Launcher" is selected then press the "OK" button

19

ECE 4899

Final Report: Linting Tool

3. If a window pops up informing you to update java you may either:


a) Select the "Update" button to up date your Java Run-Time Environment (Recommended)
b) Select the "Later" button to ignore the update

20

ECE 4899

Final Report: Linting Tool

4. You will see this Loading Screen if Java has Launched correctly

5. When the Security Warning pops up make sure to check the "I accept the risk and want to run this
application" check box, then click on the "Show Options" button

6. On the expanded window check the "Do not show this again for apps from the publisher and location
above" check box, then click on the "Run" button

21

ECE 4899

Final Report: Linting Tool

7. From here the linting tool should run as shown below

22

ECE 4899

Final Report: Linting Tool

Guide For Running the JNLP Creator


First Time Set Up for Files:
1. JNLP_Creator/jnlpgenerator.java
a. BaseURL needs to be assigned to the URL where the jnlp and jar file is going to be placed
in web format URL.
2. LintingToolMain/src/TestMain/MainGUI.java

23

ECE 4899

Final Report: Linting Tool


a. DocumentationURL needs to be changed to the root directory where the
Documentation is going to be hosted. Please note that all documentation files need to
be in the same directory.
b. Example
i. https://linting-tool.googlecode.com/git/Database/v/Documentation/01.html
ii. https://linting-tool.googlecode.com/git/Database/v/Documentation/02.html
1. These two links have the same base
2. https://linting-tool.googlecode.com/git/Database/v/Documentation/

3. Run First Time Run.bat


a. Enter a Password for the certificate when prompted by Command Prompt window
shown below: Password will not be seeable/cursor doesnt move.

i.
ii. Make Note of the password you used.
b. Follow the on screen instructions
4. Edit Sign Jar.bat
a. Change the *Insert Your Password Here* with your password in part 3
5. Try Running Command Line Variable Add
a. If you see the prompt information below

24

ECE 4899

Final Report: Linting Tool

i.
ii. Go to Step 6.
b. Else
i. You need to get the default java installation path
1. Usually found at C:\Program Files\Java
2. Verify a Java Development Kit Is installed.
a. Folder Usually call jdk1.7.0_xx
b. If not installed
i. Install a Java JDK
ii. Start step 5 over
3. If it is there then environmental variables will need to be manually set
a. Take note of the Java JDK Folder Location
b. In start menu search Enviro
c. You should see the picture below

d.
e. Click the Edit enviroment variables for your account

25

ECE 4899

Final Report: Linting Tool


f.

You should see the picture below

g. Edit or click new and create the two variables called


JAVA_HOME and PATH. Use your JDK Folder name in
replacement of the JDK1.7.0_15
h. Edit Create Jar and Sign.bat
i. Remove call "Command Line Variable Add.bat" from
the file
ii. Continue to step 6
6. Run Create New Key.bat Will need to be run every 6 months
a. Enter your password from Step 3 and follow the prompts
7. You can now Run Create Jar and Sign.bat

26

ECE 4899

Final Report: Linting Tool


a. These files need to be in the directory where LintingToolMain is.
b. JNLP_Creator also needs to be in the same folders as the bats.

Optional Move where the default location of the LintingTool.jar and LintingTool_WebStart.jnlp is placed
1. Edit Create Jar and Sign.bat
a. Locate the lines that contain move instructions.
b. Replace the second argument in quotes with the location you want it to copy to.
c. Example
i. Original
1. "%cdir%\Compiled\LintingTool.jar"
2. "%cdir%\Compiled\LintingTool_WebStart.jnlp"
ii. Changed
1. C:\Program Files\LintingTool.jar"
2. C:\Program Files\LintingTool_WebStart.jnlp"
Note: For Security Reasons make sure the bats are not accessible from the web.
JNLP Syntax Availible From Here:
http://docs.oracle.com/javase/7/docs/technotes/guides/javaws/developersguide/synta
x.html

27

ECE 4899

Final Report: Linting Tool

Linting Tool Code Files


(Presented to you in alphabetical order: )
Always.java:
package TestMain;

import java.util.ArrayList;
public class Always extends Block{
private ArrayList<Variable> sensitivityList;
/*"alwaysBlockOrder" preserves the structureal order of statements and
* subBlocks in and always block.
* 0 - indicates an assignment statement,
* 1- indicates the presence of another subBlock
*/

private String statementText;


private ArrayList<Integer> alwaysBlockOrder;

Always(Block comesFrom, String name){


BlockType = "";
BlockName = name;
vars = new ArrayList();
subBlocks = new ArrayList();
assignments = new ArrayList();
sensitivityList = new ArrayList();
alwaysBlockOrder = new ArrayList();
statementText = "";

28

ECE 4899

Final Report: Linting Tool

parent = comesFrom;
LineNumber = Parser.currentLineNumber;
}

public static String parseAlways(Block current, Parser parser){


Always always = new Always(current,"");
current.addSubBlock(always);
String temp = "";
String statementText = "";
always.parseAlwaysHead(parser);
temp = parser.getNextPiece();
//if there is more than one action in the always block
if(temp.equals("begin")){
temp = parser.getNextPiece();
for(;
!temp.equals("end")
temp=parser.getNextPiece()){

&&

!temp.equals("##END_OF_MODULE_CODE");

//will need to handle: if, switch, assignments,


//Syntax error if there are: nested always,
if(!parser.pieceIsKeyword(temp) && parser.checkTaskOrFunctionName(temp)==0){
for(; !temp.equals(";")
parser.getNextPiece()){

&&

!temp.equals("##END_OF_MODULE_CODE");

statementText += temp+" ";


}
always.addAssignment(new AssignmentStatement(statementText,always, parser));
always.alwaysBlockOrder.add(new Integer(0));
statementText = "";
}
else if(parser.checkTaskOrFunctionName(temp)!=0){

29

temp

ECE 4899

Final Report: Linting Tool


String taskCallText = "";
ArrayList<String> taskCallElements = new ArrayList();
for(; !temp.equals(";") &&
!temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece()){
taskCallText += temp+" ";
taskCallElements.add(temp);
}
always.addVariable(new TaskCall(taskCallText,taskCallElements));
always.alwaysBlockOrder.add(new Integer(2));

}
else{
if(!temp.equals("always")){
parser.checkForNewBlock(always, temp);
if(!temp.equals("$#")) //this one
always.alwaysBlockOrder.add(new Integer(1));
}
else{
String errorText = "Error: nested always blocks not allowed";
parser.addErrorToParserErrorList(new
Error("19",errorText,Parser.getCurrentLineNumber()));
parser.stopParsing();
}
}
}
}else{
if(temp.equals("$#")){
parser.checkForNewBlock(always, temp);
30

ECE 4899

Final Report: Linting Tool

temp = parser.getNextPiece();
}
if(!parser.pieceIsKeyword(temp) && parser.checkTaskOrFunctionName(temp)==0){
for(;
!temp.equals(";")
parser.getNextPiece()){

&&

!temp.equals("##END_OF_MODULE_CODE");

statementText += temp+" ";


}
always.addAssignment(new AssignmentStatement(statementText,always,parser));
always.alwaysBlockOrder.add(new Integer(0));
statementText = "";
}
else if(parser.checkTaskOrFunctionName(temp)!=0){
String taskCallText = "";
ArrayList<String> taskCallElements = new ArrayList();
for(; !temp.equals(";") &&
!temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece()){
taskCallText += temp+" ";
taskCallElements.add(temp);
}
always.addVariable(new TaskCall(taskCallText,taskCallElements));
always.alwaysBlockOrder.add(new Integer(2));
}
else{
if(!temp.equals("always")){
parser.checkForNewBlock(always, temp);
if(!temp.equals("$#"))
always.alwaysBlockOrder.add(new Integer(1));
31

temp

ECE 4899

Final Report: Linting Tool

}
else{
String errorText = "Error: nested always blocks not allowed";
parser.addErrorToParserErrorList(new Error("19",errorText,Parser.getCurrentLineNumber()));
parser.stopParsing();
}
}
}

return temp;
}
private void parseAlwaysHead(Parser parser){
statementText = "always";
String temp = parser.getNextPiece(); //temp will equal "@"
if(!temp.equals("@")){
parser.stopParsing();
return;
}
statementText += (" "+temp);
Variable tempVar; Reg tempReg; Wire tempWire;
temp = parser.getNextPiece(); //temp will equal "(" or "*"
statementText += (" "+temp);
if(temp.equals("*")){ //if the sensitivities are not explicitely specified
//

sensitivityList.add(new Variable("*",""));
BlockType = "levelSensitive";
}else if(temp.equals("(")){ //if temp == "("
temp = parser.getNextPiece(); //temp will equal the first item of interrest
statementText += (" "+temp);
32

ECE 4899

Final Report: Linting Tool

for(; !temp.equals(")") && !temp.equals("##END_OF_MODULE_CODE");


temp = parser.getNextPiece(), statementText+=(" "+temp) ){
if(temp.equals("$#")){
parser.updateLineNumber();
}else if(temp.equals("*")){
//

sensitivityList.add(new Variable("*",""));
BlockType = "levelSensitive";
}
else if(temp.equals("posedge")){
if(!(BlockType.equals("") || BlockType.equals("edgeSensitive")) ){
addError12MixedSensitivityInAlwaysBlock(parser);

//

return;
}
BlockType = "edgeSensitive";
temp = parser.getNextPiece(); statementText+=(" "+temp);
tempVar = this.findVariableInParentBlockHierarchy(temp);
if(tempVar != null){
if(tempVar.arraySize > 1){ // if the variable in question is an array
addError10VectorOrArrayInSensList(temp, parser);
}

else
if(!tempVar.getEdgeSensitivity().equals("negedge")
!tempVar.getEdgeSensitivity().equals("levelSensitive")){
tempVar.setEdgeSensitivity("posedge");
sensitivityList.add(tempVar);
}else{
addError17MixedSensitivityOfAVariable(parser, tempVar.name);
}

33

&&

ECE 4899

Final Report: Linting Tool


}else if( !this.findVectorNameInParentBlockHierarchy(temp).isEmpty() ){ //if the variable is a

vector
addError10VectorOrArrayInSensList(temp, parser);
}
else{
parser.addInstanceOfError8UndeclaredSignal(temp);
}

}
else if(temp.equals("negedge")){
if(!(BlockType.equals("") || BlockType.equals("edgeSensitive")) ){
addError12MixedSensitivityInAlwaysBlock(parser);
//

return;
}
BlockType = "edgeSensitive";
temp = parser.getNextPiece(); statementText+=(" "+temp);
tempVar = this.findVariableInParentBlockHierarchy(temp);
if(tempVar != null){
if(tempVar.arraySize > 1){ // if the variable in question is an array
addError10VectorOrArrayInSensList(temp, parser);
}

else
if(!tempVar.getEdgeSensitivity().equals("posedge")
!tempVar.getEdgeSensitivity().equals("levelSensitive")){
tempVar.setEdgeSensitivity("posedge");
sensitivityList.add(tempVar);
}else{
addError17MixedSensitivityOfAVariable(parser, tempVar.name);
}

34

&&

ECE 4899

Final Report: Linting Tool


}else if( !this.findVectorNameInParentBlockHierarchy(temp).isEmpty() ){ //if the variable is a

vector
addError10VectorOrArrayInSensList(temp, parser);
}
else{
parser.addInstanceOfError8UndeclaredSignal(temp);
}

}
else if(temp.equals("or") || temp.equals(","));
else{
if(!(BlockType.equals("") || BlockType.equals("levelSensitive")) ){
addError12MixedSensitivityInAlwaysBlock(parser);
//

return;
}
BlockType = "levelSensitive";
tempVar = this.findVariableInParentBlockHierarchy(temp);
if(tempVar != null){
if(tempVar.arraySize > 1){ // if the variable in question is an array
addError10VectorOrArrayInSensList(temp, parser);
}

else
if(!tempVar.getEdgeSensitivity().equals("posedge")
!tempVar.getEdgeSensitivity().equals("negedge")){
tempVar.setEdgeSensitivity("levelSensitive");
sensitivityList.add(tempVar);
}else{
addError17MixedSensitivityOfAVariable(parser, tempVar.name);
}

35

&&

ECE 4899

Final Report: Linting Tool


}else if( !this.findVectorNameInParentBlockHierarchy(temp).isEmpty() ){ //if the variable is a

vector
//addErrorVectorArrayInSensList(temp, parser);
Variable.safelyParseVariableFromLine(parser, this, temp,
sensitivityList,sensitivityList);
}
else{
parser.addInstanceOfError8UndeclaredSignal(temp);
}
}
}
}else {
parser.addInstanceOfError18UnexpectedToken(temp);
parser.stopParsing();
return;
}
}
public void addToAlwaysBlockOrder(int num){
this.alwaysBlockOrder.add(num);
}
public int getFromAlwaysBlockOrder(int index){
if(index< alwaysBlockOrder.size() && index>=0){
return this.alwaysBlockOrder.get(index);
}else{
return this.alwaysBlockOrder.get(0);
}
}
public String getAlwaysStatement(){
36

ECE 4899

Final Report: Linting Tool

return statementText;
}
public ArrayList<Variable> getSensitivityList()
{
return sensitivityList;
}
private void addError10VectorOrArrayInSensList(String varName, Parser parser){
String errorOutput = "Error: Vector or Array detected in Edge-Sensitive Always Block sensitivity
list,\n"
+ "\tor an Array variable was detected in a Level-Sensitive Always Block sensitivity list:\n";
errorOutput += "\t Variable ( "+varName+" ) in always on line : "+this.LineNumber+" Variable Name:
";
parser.addErrorToParserErrorList(new Error("10",errorOutput,this.LineNumber));
}
private void addError12MixedSensitivityInAlwaysBlock(Parser parser){
String errorOutput = "Error: Mixing of Level and Edge Sensitivity detected in Always Block :\n";
errorOutput += "\tin always on line : "+this.LineNumber+"\n";
parser.addErrorToParserErrorList(new Error("12",errorOutput,this.LineNumber));
}
private void addError17MixedSensitivityOfAVariable(Parser parser, String var){
String errorOutput = "Error: Mixing of Level and Edge Sensitivity detected:\n";
errorOutput += "\t variable ( "+var+" ) is used in both edge-sensitive and level-sensitive always
blocks"
+ "\n first use of mixed type occued in always on line: "+this.LineNumber;
parser.addErrorToParserErrorList(new Error("17",errorOutput,this.LineNumber));
}
@Override
public String toString(){
int i = 0; int subBlockCount=0; int assignmentStatementCount=0; int taskCallCount=0;
37

ECE 4899

Final Report: Linting Tool

String temp = "always@( ";


if(this.BlockType.equals("edgeSensitive") && sensitivityList.size()>0){
temp+= sensitivityList.get(0).getEdgeSensitivity();
temp+= " "; temp+= sensitivityList.get(0).name;
for(i=1; i < sensitivityList.size(); i++){
temp+=" or";
temp+= " "; temp+= sensitivityList.get(i).getEdgeSensitivity();
temp+= " "; temp+= sensitivityList.get(i).name;
}
}
else if(this.BlockType.equals("levelSensitive") && sensitivityList.size()>0){
temp+= sensitivityList.get(0).name;
for(i=1; i < sensitivityList.size(); i++){
temp+=" or";
temp+= " "; temp+= sensitivityList.get(i).name;
}
}
temp += " )"; temp += "begin \\\\LINE: "+LineNumber+" Statement Text: "+statementText+"\n";
for(i=0, subBlockCount=0, assignmentStatementCount=0; i<alwaysBlockOrder.size() ; i++){
if(alwaysBlockOrder.get(i) == 0){
temp+= assignments.get(assignmentStatementCount).toString();
assignmentStatementCount++;
}else if(alwaysBlockOrder.get(i) == 1){
temp+= subBlocks.get(subBlockCount).toString();
subBlockCount++;
}else if(alwaysBlockOrder.get(i) == 2){
temp+= vars.get(taskCallCount);
taskCallCount++;
38

ECE 4899

Final Report: Linting Tool

}
}
temp += "end //end always\n";

return temp;
}

39

ECE 4899

Final Report: Linting Tool

AssignmentStatement.java

package TestMain;

import java.util.ArrayList;

public class AssignmentStatement {


//LHSvars needs to be an ArrayList in case of the presence of vectors
protected ArrayList<Variable> LHSvars;
protected ArrayList<Variable> RHSvars;
protected String assignmentText;
Block parent;
protected int LineNumber;
AssignmentStatement(){
assignmentText = "";
LHSvars = new ArrayList();
RHSvars = new ArrayList();
LineNumber = Parser.currentLineNumber;
}
AssignmentStatement(String rawText, Parser parser){
assignmentText = rawText;
LHSvars = new ArrayList();
RHSvars = new ArrayList();
LineNumber = Parser.currentLineNumber;

identifyLHSvariables(parser);
}
AssignmentStatement(String rawText, Block blockSource, Parser parser){
40

ECE 4899

Final Report: Linting Tool

assignmentText = rawText;
LHSvars = new ArrayList();
RHSvars = new ArrayList();
parent = blockSource;
LineNumber = Parser.currentLineNumber;

System.out.println(LineNumber);

identifyLHSvariables(parser);
identifyRHSvariables(parser);
}

protected void identifyLHSvariables(Parser parser){


String preserve = assignmentText;
String temp = getNextPiece();
Variable tempVar=null;
for(; !temp.equals("=") && !temp.equals("<")&& !temp.equals("##END_OF_STATEMENT");){
if(temp.equals("$#")){
temp=getNextPiece();
parser.setLineNumber(Integer.parseInt(temp));
}
else {
tempVar = parent.findVariableInParentBlockHierarchy(temp);
if(tempVar != null){
//

LHSvars.add(tempVar);
temp = Variable.safelyParseVariableForAssignmentStatement(
parser, parent, this,temp, LHSvars,RHSvars);
41

ECE 4899

Final Report: Linting Tool

}else if(parent.findVectorNameInParentBlockHierarchy(temp).size()>0){
//

LHSvars.addAll(parent.findVectorNameInParentBlockHierarchy(temp));
temp=Variable.safelyParseVariableForAssignmentStatement(
parser, parent, this,temp, LHSvars,RHSvars);

}else{

}
}
if(!temp.equals("=")){
temp=getNextPiece();
}
}
assignmentText = preserve;
}
protected void identifyRHSvariables(Parser parser){
String preserve = assignmentText;
assignmentText = assignmentText.substring(assignmentText.indexOf("="));
String temp = getNextPiece();
Variable tempVar=null;
for(temp=getNextPiece(); !temp.equals("##END_OF_STATEMENT"); ){
if(temp.equals("$#")){
temp=getNextPiece();
parser.setLineNumber(Integer.parseInt(temp));
}
else {
tempVar = parent.findVariableInParentBlockHierarchy(temp);
if(tempVar != null){
42

ECE 4899

Final Report: Linting Tool

//

LHSvars.add(tempVar);
Variable.safelyParseVariableForAssignmentStatement(
parser, parent, this,temp, RHSvars,RHSvars);
}else if(parent.findVectorNameInParentBlockHierarchy(temp).size()>0){

//

LHSvars.addAll(parent.findVectorNameInParentBlockHierarchy(temp));
Variable.safelyParseVariableForAssignmentStatement(
parser, parent, this,temp, RHSvars,RHSvars);

}else{

}
}
if(!temp.equals("$#")){
temp=getNextPiece();
}
}
assignmentText = preserve;
}

protected String getNextPiece(){


String[] piece = assignmentText.split(" ",2);
if(piece.length != 1)
assignmentText = piece[1];
while( piece[0].equals("")){
piece = assignmentText.split(" ",2);
if(piece.length != 1){
assignmentText = piece[1];
}else{
43

ECE 4899

Final Report: Linting Tool

piece[0] = "##END_OF_STATEMENT";
}

}
return piece[0];
}

public ArrayList<Variable> getLHSvars(){


return LHSvars;
}

public ArrayList<Variable> getRHSvars(){


return RHSvars;
}

public static boolean expressionPiece(String piece){


if(piece.equals("=")){
return true;
}else if(piece.equals("!")){
return true;
}else if(piece.equals("=")){
return true;
}else if(piece.equals("~")){
return true;
}else if(piece.equals("&")){
return true;
}else if(piece.equals("|")){
return true;
44

ECE 4899

Final Report: Linting Tool

}else if(piece.equals("^")){
return true;
}else if(piece.equals("%")){
return true;
}else if(piece.equals("*")){
return true;
}else if(piece.equals("+")){
return true;
}else if(piece.equals("-")){
return true;
}else if(piece.equals("/")){
return true;
}else if(piece.equals("(")){
return true;
}else if(piece.equals(")")){
return true;
}else if(piece.equals("[")){
return true;
}else if(piece.equals("]")){
return true;
}else if(piece.equals("<")){
return true;
}else if(piece.equals(">")){
return true;
}else{
return false;
}
}
45

ECE 4899

Final Report: Linting Tool

public int getAssignmentStatementLineNumber(){


return LineNumber;
}

@Override
public String toString(){
String text = "";
text += assignmentText + ";\\\\ ";
text += "LHSvars: "+LHSvars.toString();
text += ", RHSvars: "+RHSvars.toString()+" LINE: "+LineNumber+"\n";
return text;
}
}

46

ECE 4899

Final Report: Linting Tool

Block.java

package TestMain;

import java.util.ArrayList;

public class Block {


protected String BlockName;
protected String BlockType;
protected ArrayList<Variable> vars;
protected ArrayList<Block> subBlocks;
protected ArrayList<AssignmentStatement> assignments;
protected Block parent;
protected int LineNumber;

Block(){
BlockType = "";
BlockName = "";
vars = new ArrayList();
subBlocks = new ArrayList();
assignments = new ArrayList();
LineNumber = Parser.currentLineNumber;

}
Block(String type, Block comesFrom){
BlockType = type;
BlockName = "";
vars = new ArrayList();
47

ECE 4899

Final Report: Linting Tool

subBlocks = new ArrayList();


assignments = new ArrayList();
parent = comesFrom;
LineNumber = Parser.currentLineNumber;
}
Block(String type, Block comesFrom, String name){
BlockType = type;
BlockName = name;
vars = new ArrayList();
subBlocks = new ArrayList();
assignments = new ArrayList();
parent = comesFrom;
LineNumber = Parser.currentLineNumber;
}
public void addVariable(Variable newVariable){
vars.add(newVariable);
//

sortVariables();
}
public void addSubBlock(Block newSubBlock){
subBlocks.add(newSubBlock);
}
public void addAssignment(AssignmentStatement newAssignment){
assignments.add(newAssignment);
}

public void sortVariables(){


int i=0, j=0;
Variable temp;
48

ECE 4899

Final Report: Linting Tool

for(i=0; i<vars.size(); i++){


for(j=0; j<vars.size()-(i+1); j++){
if(vars.get(j).compareVariable(vars.get(j+1)) == 1){
temp = vars.get(j);
vars.set(j, vars.get(j+1));
vars.set(j+1, temp);
}
}
}
}
protected Variable findVariableInParentBlockHierarchy(String varToFind){
int i = 0;
Block checker = this;
do{
for(i=0; i<checker.vars.size(); i++){
if(checker.vars.get(i).getName().equals(varToFind))
if(checker.vars.get(i).getClass()!=TaskCall.class
checker.vars.get(i).getClass()!=FunctionCall.class){
return checker.vars.get(i);
}
}
checker = checker.parent;
}while(checker != null);
return null;
}

protected ArrayList<Variable> findVectorNameInParentBlockHierarchy(String varToFind){


int i = 0;
49

&&

ECE 4899

Final Report: Linting Tool

Block checker = this;


ArrayList<Variable> vectorVars = new ArrayList();
do{
for(i=0; i<checker.vars.size(); i++){
if(checker.vars.get(i).getVectorName().equals(varToFind)){
vectorVars.add(checker.vars.get(i));
}
}
checker = checker.parent;
}while(checker != null);
return vectorVars;
}

public ArrayList<Variable> getAllVariables(){


ArrayList<Variable> collection = new ArrayList();
collection.addAll(vars);
for(int i=0; i<subBlocks.size(); i++){
collection.addAll( subBlocks.get(i).getAllVariables());
}

ArrayList<Variable> cleanCollection = new ArrayList();


for(int i=0; i<collection.size(); i++){
if(collection.get(i).getClass()!=TaskCall.class && collection.get(i).getClass()!=FunctionCall.class){
cleanCollection.add(collection.get(i));
}
}
return cleanCollection;
}
50

ECE 4899

Final Report: Linting Tool

public ArrayList<Block> getAllBlocks(){


ArrayList<Block> collection = new ArrayList();
collection.addAll(subBlocks);
for(int i=0; i<subBlocks.size(); i++){
collection.addAll( subBlocks.get(i).getAllBlocks());
}
return collection;
}

public ArrayList<AssignmentStatement> getAllAssignmentStatements(){


ArrayList<AssignmentStatement> collection = new ArrayList();
collection.addAll(assignments);
for(int i=0; i<subBlocks.size(); i++){
collection.addAll( subBlocks.get(i).getAllAssignmentStatements() );
}
return collection;
}

public ArrayList<AssignmentStatement> getBlockAssignmentStatements(){


return assignments;
}

public int getBlockLineNumber(){


return LineNumber;
}

@Override
51

ECE 4899

Final Report: Linting Tool

public String toString(){


int i=0;
String retVar = BlockType + " " + BlockName + " ";

for(i=0; i<vars.size(); i++){}


for(i=0; i<subBlocks.size(); i++){
retVar += subBlocks.get(i).toString();
}
for(i=0; i<assignments.size(); i++){}

return retVar;
}
}

52

ECE 4899

Final Report: Linting Tool

Case.java
package TestMain;

import java.util.ArrayList;

public class Block {


protected String BlockName;
protected String BlockType;
protected ArrayList<Variable> vars;
protected ArrayList<Block> subBlocks;
protected ArrayList<AssignmentStatement> assignments;
protected Block parent;
protected int LineNumber;

Block(){
BlockType = "";
BlockName = "";
vars = new ArrayList();
subBlocks = new ArrayList();
assignments = new ArrayList();
LineNumber = Parser.currentLineNumber;

}
Block(String type, Block comesFrom){
BlockType = type;
BlockName = "";
vars = new ArrayList();
subBlocks = new ArrayList();
53

ECE 4899

Final Report: Linting Tool

assignments = new ArrayList();


parent = comesFrom;
LineNumber = Parser.currentLineNumber;
}
Block(String type, Block comesFrom, String name){
BlockType = type;
BlockName = name;
vars = new ArrayList();
subBlocks = new ArrayList();
assignments = new ArrayList();
parent = comesFrom;
LineNumber = Parser.currentLineNumber;
}
public void addVariable(Variable newVariable){
vars.add(newVariable);
//

sortVariables();
}
public void addSubBlock(Block newSubBlock){
subBlocks.add(newSubBlock);
}
public void addAssignment(AssignmentStatement newAssignment){
assignments.add(newAssignment);
}

public void sortVariables(){


int i=0, j=0;
Variable temp;
for(i=0; i<vars.size(); i++){
54

ECE 4899

Final Report: Linting Tool

for(j=0; j<vars.size()-(i+1); j++){


if(vars.get(j).compareVariable(vars.get(j+1)) == 1){
temp = vars.get(j);
vars.set(j, vars.get(j+1));
vars.set(j+1, temp);
}
}
}
}
protected Variable findVariableInParentBlockHierarchy(String varToFind){
int i = 0;
Block checker = this;
do{
for(i=0; i<checker.vars.size(); i++){
if(checker.vars.get(i).getName().equals(varToFind))
if(checker.vars.get(i).getClass()!=TaskCall.class
checker.vars.get(i).getClass()!=FunctionCall.class){
return checker.vars.get(i);
}
}
checker = checker.parent;
}while(checker != null);
return null;
}

protected ArrayList<Variable> findVectorNameInParentBlockHierarchy(String varToFind){


int i = 0;
Block checker = this;
55

&&

ECE 4899

Final Report: Linting Tool

ArrayList<Variable> vectorVars = new ArrayList();


do{
for(i=0; i<checker.vars.size(); i++){
if(checker.vars.get(i).getVectorName().equals(varToFind)){
vectorVars.add(checker.vars.get(i));
}
}
checker = checker.parent;
}while(checker != null);
return vectorVars;
}

public ArrayList<Variable> getAllVariables(){


ArrayList<Variable> collection = new ArrayList();
collection.addAll(vars);
for(int i=0; i<subBlocks.size(); i++){
collection.addAll( subBlocks.get(i).getAllVariables());
}

ArrayList<Variable> cleanCollection = new ArrayList();


for(int i=0; i<collection.size(); i++){
if(collection.get(i).getClass()!=TaskCall.class && collection.get(i).getClass()!=FunctionCall.class){
cleanCollection.add(collection.get(i));
}
}
return cleanCollection;
}

56

ECE 4899

Final Report: Linting Tool

public ArrayList<Block> getAllBlocks(){


ArrayList<Block> collection = new ArrayList();
collection.addAll(subBlocks);
for(int i=0; i<subBlocks.size(); i++){
collection.addAll( subBlocks.get(i).getAllBlocks());
}
return collection;
}

public ArrayList<AssignmentStatement> getAllAssignmentStatements(){


ArrayList<AssignmentStatement> collection = new ArrayList();
collection.addAll(assignments);
for(int i=0; i<subBlocks.size(); i++){
collection.addAll( subBlocks.get(i).getAllAssignmentStatements() );
}
return collection;
}

public ArrayList<AssignmentStatement> getBlockAssignmentStatements(){


return assignments;
}

public int getBlockLineNumber(){


return LineNumber;
}

@Override
public String toString(){
57

ECE 4899

Final Report: Linting Tool

int i=0;
String retVar = BlockType + " " + BlockName + " ";

for(i=0; i<vars.size(); i++){}


for(i=0; i<subBlocks.size(); i++){
retVar += subBlocks.get(i).toString();
}
for(i=0; i<assignments.size(); i++){}

return retVar;
}
}

58

ECE 4899

Final Report: Linting Tool

ConditionStatement.java
package TestMain;

import java.util.ArrayList;

public class ConditionStatement extends AssignmentStatement {


ArrayList<Variable> conditionVars;
ConditionStatement(String rawText, Block blockSource, Parser parser){
assignmentText = rawText;
conditionVars = new ArrayList();
LineNumber = Parser.currentLineNumber;
parent = blockSource;

identifyConditionVariables(parser);
}

private void identifyConditionVariables(Parser parser){


String preserve = assignmentText;
String temp="";
Variable var;
for(temp=super.getNextPiece();!temp.equals("##END_OF_STATEMENT");temp=super.getNextPiece()){
if(temp.equals("$#")){
temp=getNextPiece();
parser.setLineNumber(Integer.parseInt(temp));
}
else if( parent.findVariableInParentBlockHierarchy(temp) != null
|| !parent.findVectorNameInParentBlockHierarchy(temp).isEmpty()){
59

ECE 4899
//

Final Report: Linting Tool


conditionVars.add(parent.findVariableInParentBlockHierarchy(temp));

temp = Variable.safelyParseVariableForAssignmentStatement(
parser, parent, this,temp, conditionVars,conditionVars);
}else {
//

conditionVars.addAll(parent.findVectorNameInParentBlockHierarchy(temp));

//

temp = Variable.safelyParseVariableForAssignmentStatement(

//

parser, parent, this,temp, conditionVars,conditionVars);


}
}
assignmentText = preserve;
}

@Override
public String toString(){
return assignmentText + "";
}

60

ECE 4899

Final Report: Linting Tool

ContinuousAssignment.java
package TestMain;

import java.util.ArrayList;

public class ContinuousAssignment extends AssignmentStatement {


ContinuousAssignment(String rawText, Block blockSource, Parser parser){
assignmentText = rawText;
LHSvars = new ArrayList();
RHSvars = new ArrayList();
parent = blockSource;
LineNumber = Parser.currentLineNumber;

identifyLHSvariables(parser);
identifyRHSvariables(parser);
}
/*
@Override
protected void identifyLHSvariables(Parser parser){
String preserve = assignmentText;
String temp = super.getNextPiece();
Variable tempVar=null;
for(; !temp.equals("="); temp=super.getNextPiece()){
if( !super.expressionPiece(temp) ){
tempVar = parent.findVariableInParentBlockHierarchy(temp);
if(tempVar != null){
LHSvars.add(tempVar);
}
61

ECE 4899

Final Report: Linting Tool

}
}
assignmentText = preserve;
}
@Override
protected void identifyRHSvariables(Parser parser){
String preserve = assignmentText;
assignmentText = assignmentText.substring(assignmentText.indexOf("="));
String temp;
for(temp=getNextPiece(); !temp.equals("##END_OF_STATEMENT"); temp=getNextPiece()){
if( parent.findVariableInParentBlockHierarchy(temp) != null){
RHSvars.add(parent.findVariableInParentBlockHierarchy(temp));
}else {
RHSvars.addAll(parent.findVectorNameInParentBlockHierarchy(temp));
}
}
assignmentText = preserve;
}
*/
@Override
public String toString(){
String text = "";
text += "assign " + assignmentText + ";\\\\ ";
text += "LHSvars: "+LHSvars.toString();
text += ", RHSvars: "+RHSvars.toString()+" LINE: "+LineNumber+"\n";
return text;
}
}
62

ECE 4899

Final Report: Linting Tool

DocumentationGUI.java
package TestMain;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.net.URL;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.text.DefaultEditorKit;
import sun.security.krb5.internal.crypto.Des;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Deathwarror
*/
public class DocumentationGui extends javax.swing.JDialog {

private Dimension dim;


private int ScreenHeight;
private int ScreenWidth;

63

ECE 4899

Final Report: Linting Tool

/**
* Creates new form DocumentationGui
*/
public DocumentationGui(java.awt.Frame parent, boolean modal,String ErrorNumber ,String
DURL,String DType,String DDType) {
super(parent, modal);
initComponents();

ErrorDocumentationLoader EDL = new ErrorDocumentationLoader(DURL,DType);


ErrorDocumentationLoader EDL2 = new ErrorDocumentationLoader(DURL,DDType);
Toolkit toolkit = Toolkit.getDefaultToolkit();
dim = toolkit.getScreenSize();
String Description= EDL.getURL(ErrorNumber);
//try loading the html version of the description
try{
Description = (EDL.getURL(ErrorNumber));
try{
DocumentationField.setPage((String)Description);
}
catch(Exception E)
{
Description = EDL2.getURL(ErrorNumber);
DocumentationField.setPage(new URL(Description));
}
DocumentationField.setEditable(false);
ErrorName.setText("Error "+ErrorNumber+":");
ScreenHeight = (int)(dim.height*.8);
ScreenWidth = (int)(dim.width*.8);
64

ECE 4899

Final Report: Linting Tool

this.setSize(new Dimension(ScreenWidth,ScreenHeight));
this.setLocation((int)((dim.width-ScreenWidth)/2),(int)((dim.height-ScreenHeight)/2));
this.setSize(new Dimension((int)(ScreenWidth*.9-200),(int)(ScreenHeight*.9-30)));
this.setVisible(true);
}
//try loading the txt version of he description
catch(Exception e)
{
e.printStackTrace();
Description = EDL2.load(ErrorNumber);
JOptionPane.showMessageDialog(new
JFrame(),
ErrorNumber),JOptionPane.INFORMATION_MESSAGE );

Description,("Error:

this.dispose();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

65

"+

ECE 4899

Final Report: Linting Tool

CloseButton = new javax.swing.JButton();


JSP = new javax.swing.JScrollPane();
DocumentationField = new javax.swing.JEditorPane();
ErrorName = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

CloseButton.setText("OK");
CloseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CloseButtonActionPerformed(evt);
}
});

JSP.setViewportView(DocumentationField);

ErrorName.setText("jLabel1");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(JSP,
javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
66

ECE 4899

Final Report: Linting Tool


.addGap(0, 0, Short.MAX_VALUE)
.addComponent(CloseButton))
.addGroup(layout.createSequentialGroup()
.addComponent(ErrorName)
.addGap(0, 0, Short.MAX_VALUE)))

.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(ErrorName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JSP, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CloseButton)
.addGap(7, 7, 7))
);

pack();
}// </editor-fold>

private void CloseButtonActionPerformed(java.awt.event.ActionEvent evt) {


this.dispose();
}

/**
* @param args the command line arguments
*/
67

ECE 4899

Final Report: Linting Tool

// Variables declaration - do not modify


private javax.swing.JButton CloseButton;
private javax.swing.JEditorPane DocumentationField;
private javax.swing.JLabel ErrorName;
private javax.swing.JScrollPane JSP;
// End of variables declaration
}

68

ECE 4899

Final Report: Linting Tool

Error.java
package TestMain;

/** @Author: Kenneth Hassey


* @Date: 1/7/2013
* @Version: 1.000
* Function
*

Contains all information about an error, Definition, Identification

Number, and Message Given to the user

* Status: UPDATE
* Updated by Danny on 2/24/2013
*/

import java.util.ArrayList;

public class Error {


//Stores the Errors Message
private String ErrorMsg;
//Stores the error Number;
private String ErrorNumber;

private ArrayList<Integer> LineNumbers;

Error()
{
ErrorMsg = "";
ErrorNumber = "";
LineNumbers = new ArrayList();
69

ECE 4899

Final Report: Linting Tool

Error(String ErrorNum, String ErrorMsg_in)


{
ErrorNumber = ErrorNum;
ErrorMsg = ErrorMsg_in;
}

Error(String ErrorNum, String ErrorMsg_in, int line)


{
ErrorNumber = ErrorNum;
ErrorMsg = ErrorMsg_in;
LineNumbers = new ArrayList();
LineNumbers.add(line);
}

public String setLineNumbers(ArrayList<Integer> NewLns)


{
LineNumbers = NewLns;
return "Successful";
}
public String addLineNumber(int i)
{
LineNumbers.add(i);
return "Successful";
}
public ArrayList<Integer> getLineNumbers()
{
70

ECE 4899

Final Report: Linting Tool

return LineNumbers;
}
//Returns the Error Number;
public String getErrorNum()
{
return ErrorNumber;
}

//Returns the ErrorMsg


public String getErrorMsg()
{
return ErrorMsg;
}

//Returns the Error Defintion in ArrayList Form

//@Override the default to string statement


//used for testing, Displays all information in the object
public String toString()
{
System.out.println("Error Number "+ ErrorNumber+":\n"
+"Error Message: "+ErrorMsg+"\nError Definition:");
return "Successful";
}

//allows the error number to be set afterwards


public void setErrorNum(String e)
71

ECE 4899

Final Report: Linting Tool

{
ErrorNumber = e;
}
//allows the error message to be set afterwards
public void setErrorMsg(String msg)
{
ErrorMsg = msg;
}

//Used to keep duplicate errors from being placed in the array.


public boolean compareTo(Error e)
{
//checks to see if the error number and msg are the same
if((e.getErrorNum().equals(ErrorNumber))&&(e.getErrorMsg().equals(ErrorMsg)))
{
//return true if all tests have been passed.
return true;
}
//if it failed the first test return false
return false;
}
}

72

ECE 4899

Final Report: Linting Tool

Error01_05_07IdentifyClockErrors.java
/**
* @Author:
* @Date:

Kenneth Hassey
5/8/2013

* @Version: 1.100
* Function:
*

detects any always blocks that a for flip flops and searches to see if they

are missing any reset variables.

then detect to see if there is an unused signal for the clock and then

checks to see if there is more than one unused signal making the block

have multiple clocks

last checks to see if there are multiple clocks per module

*
* Status: Tested Working;
*/

package TestMain;
import java.util.ArrayList;

public class Error01_05_07IdentifyClockErrors {


public static ArrayList<Error> getErrors(Parser parser)
{
ArrayList<Error> ErrorList = new ArrayList();

String errorOutput = "No Error";

ArrayList<Block> blocks = parser.getBlockList();


ArrayList<Block> AlwaysSubBlocks;
73

ECE 4899

Final Report: Linting Tool

Variable currentVar;
Block currentBlock;
ConditionStatement currentStatement;
ArrayList<Variable> Clocks = new ArrayList();
ArrayList<Variable> SensList;
ArrayList<Integer> LineNumbers = new ArrayList();

for(int i = 0; i < blocks.size(); i++)


{
currentBlock = blocks.get(i);
if(currentBlock.getClass() == Always.class)
{
if((((Always)currentBlock).BlockType).equals("edgeSensitive"))
{
//Get the Sensitivity list for the flip flop type always block
SensList = (((Always)currentBlock).getSensitivityList());

//if there is only one item in the senselist


if(SensList.size() == 1)
{
Error e = new Error();
e.setErrorNum("01");
errorOutput = "No Reset or clock Detected in Flip Flop type always block:\n";
errorOutput += "\tin always on line :"+currentBlock.LineNumber;
e.addLineNumber(currentBlock.LineNumber);
e.setErrorMsg(errorOutput);
74

ECE 4899

Final Report: Linting Tool


System.out.println(errorOutput + "\n");
ErrorList.add(e);
}

//if there more than one item the sensitivity list


else if(SensList.size()>1)
{
AlwaysSubBlocks=currentBlock.subBlocks;
for(int j = 0; j < AlwaysSubBlocks.size(); j++)
{
if(AlwaysSubBlocks.get(j).getClass() == IfElse.class)
{
currentStatement = ((IfElse)(AlwaysSubBlocks.get(j))).getConditionStatement();
if(currentStatement != null)
{
ArrayList<Variable> vl =currentStatement.conditionVars;
for(int k = 0; k <vl.size(); k++)
{
for(int l = 0; l <SensList.size(); l++)
{
currentVar = vl.get(k);
if(currentVar.compareTo(SensList.get(l)))
{
SensList.remove(l);
l = 0;
}
}
}
75

ECE 4899

Final Report: Linting Tool


}
}
}

//if all signals were used in the sensitivity list


if(SensList.isEmpty())
{
Error e = new Error();
e.setErrorNum("07");
errorOutput = "No Clock Detected or clock is used in always block:\n";
errorOutput += "\tin always on line : "+currentBlock.LineNumber;
e.addLineNumber(currentBlock.LineNumber);
e.setErrorMsg(errorOutput);
System.out.println(errorOutput + "\n");
ErrorList.add(e);
}

//if there was more than one unused signal in the sensitivity list
else if(SensList.size()>1)
{
Error e = new Error();
e.setErrorNum("07");
errorOutput = "Multiple Clocks or unused signals detected in always block:\n";
errorOutput += "\tin always on line : "+currentBlock.LineNumber;
e.addLineNumber(currentBlock.LineNumber);
e.setErrorMsg(errorOutput);
System.out.println(errorOutput + "\n");
ErrorList.add(e);
76

ECE 4899

Final Report: Linting Tool


}
//if there is only one variable that isnt used in the sensitivity list then assumes its the clock
else
{
LineNumbers.add(currentBlock.LineNumber);
Clocks.add(SensList.get(0));
}
}

}
}
}

//compares all clock detected variables and if a variable doesnt match


//flags multiple clocks detected
for(int i = 0; i<Clocks.size(); i++)
{
currentVar = Clocks.get(0);
//if a clock doesnt match
if(currentVar.compareTo(Clocks.get(i))==false)
{
Error e = new Error();
e.setErrorNum("05");
errorOutput = "Multible Clocks detected in module\n";
errorOutput
+=
"+Clocks.get(i).getName();

"\tFirst

Clock:

e.setErrorMsg(errorOutput);
e.addLineNumber(LineNumbers.get(0));
77

"+currentVar.getName()+"\n\tSecond

Clock:

ECE 4899

Final Report: Linting Tool

e.addLineNumber(LineNumbers.get(i));
System.out.println(errorOutput + "\n");
ErrorList.add(e);
}
}
if(errorOutput.equals("No Error"))
{
System.out.println("No Problems with clock or reset detected in ClockErrors\n");
}
return ErrorList;
}
}

78

ECE 4899

Final Report: Linting Tool

Error03IdentifyAssignmentVsSensType.java
/**
* @Author:
* @Date:

Kenneth Hassey
1/7/2013

* @Version: 1.000
* Function:
*

This File is for verification of correct blocking and non blocking statements

blocking statements for combinational blocks

non blocking for timing blocks

*
* Status: Tested Working;
*/

package TestMain;

import java.util.ArrayList;

public class Error03IdentifyAssignmentVsSensType {


public static ArrayList<Error> getErrors(Parser parser)
{
ArrayList<Error> ErrorList = new ArrayList();
String errorOutput = "NE";

ArrayList<Block> blocks = parser.getBlockList();


ArrayList<AssignmentStatement> statements;
Block currentBlock;
String currentStatement;
79

ECE 4899

Final Report: Linting Tool

String SensType;
//Go through the list of blocks
for(int i = 0;i<blocks.size();i++)
{
//get the current block
currentBlock = blocks.get(i);

//see if the current block is an always block


if(currentBlock.getClass() == Always.class)
{
int error = 0;
SensType = ((Always)currentBlock).BlockType;
statements = currentBlock.getAllAssignmentStatements();

//check for blocking in a flip flop always


for(int j = 0; j <statements.size(); j++)
{
currentStatement = statements.get(j).assignmentText;
if(!(currentStatement.contains("<")))
{
if(SensType.equals("edgeSensitive"))
{
error = 1;
}
}

//check for nonblocking in a combination logic always


80

ECE 4899

Final Report: Linting Tool


else if(currentStatement.contains("<"))
{
int index = currentStatement.indexOf("<");
if(currentStatement.charAt(index+2)== '=')
{
//if the block is combinational
if((SensType.equals("levelSensitive")))
{
error = 2;
}
}
}

//if a blocking statement in a flip flop was detected


if(error == 1);
{
errorOutput = "Detected a flip flop with a Blocking Statement:\n";
errorOutput += "\tin always on line "+currentBlock.LineNumber+":";
errorOutput
+=
"+statements.get(j).LineNumber+":\t"+statements.get(j).assignmentText+";\n";

"\n\tLine

}
//if a nonblocking in a combination block was detected
if(error == 2)
{
errorOutput = "Detected a Combinational Always Block with a NonBlocking Statement:\n";
errorOutput += "\tin always on line "+currentBlock.LineNumber+":";
errorOutput
+=
"+statements.get(j).LineNumber+":\t"+statements.get(j).assignmentText+";\n";

81

"\n\tLine

ECE 4899

Final Report: Linting Tool


}

//if an error was detected


if(error!= 0)
{
//put the error message into the error list
Error e = new Error();
e.setErrorMsg(errorOutput);
e.addLineNumber(statements.get(j).LineNumber);
e.setErrorNum("03");
ErrorList.add(e);
}
error = 0;
}
}
}

if(errorOutput.equals("NE"))
{
System.out.println("No improper use of blocking and non blocking detected!\n");
return ErrorList;
}
else
{
return ErrorList;
}
}
}
82

ECE 4899

Final Report: Linting Tool

Error06IdientifyMultiplyDrivenSignals.java
package TestMain;

import java.util.ArrayList;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Deathwarror
*/
public class Error06IdentifyMultiplyDrivenSignals {
public static ArrayList<Error> getErrors(Parser parser){
ArrayList<Error> ErrorList = new ArrayList();
String errorOutput="Error: Multiply Driven Signals were detected in the following lines of code:\n";
ArrayList<String> tempString;
ArrayList<Variable> vars = parser.getVariableList();
ArrayList<Block> blocks = parser.getBlockList();
ArrayList<AssignmentStatement> statements;
ArrayList<Integer> lineNumbers = new ArrayList();
ArrayList<Integer> tempLineNumbers = new ArrayList();
Variable currentVar = null;
Block currentBlock = null;
AssignmentStatement currentStatement = null;

83

ECE 4899

Final Report: Linting Tool

int i=0; int j=0; int k=0;


// The first loop goes through every register and wire in the module
for(i=0; i<vars.size(); i++, tempString = new ArrayList(), tempLineNumbers=new ArrayList()){
currentVar = vars.get(i);
if(currentVar.getClass() == Reg.class){ //if currentVar is of type reg
//The second loop goes through every block lookin for each always block
for(j=0, tempString=new ArrayList(), currentBlock=blocks.get(0);
j<blocks.size(); j++){
currentBlock=blocks.get(j);
if(currentBlock.getClass() == Always.class){ //if currentBlock is an always block
//Retrieves all assignment statements in the current
//always block (and all of its sub-blocks)
statements = currentBlock.getAllAssignmentStatements();
for(k=0; k<statements.size(); k++){
currentStatement=statements.get(k);
//This block identifies if the (register) variable
//is present in this particular always block, if so
//it makes note of it, and then breaks to check for the variable's presence
//in the next always block
if(currentStatement.getLHSvars().indexOf( currentVar) != -1 ){
tempString.add(
" \"always\" block at line "+ currentBlock.getBlockLineNumber() +": "+
currentStatement.assignmentText
"+currentStatement.getAssignmentStatementLineNumber() +")\n"

";

(line:

);
tempLineNumbers.add(currentStatement.getAssignmentStatementLineNumber());
break;
}
84

ECE 4899

Final Report: Linting Tool


}
if(tempString.size() > 1){
errorOutput += tempString+ "\n";
tempString = new ArrayList();
lineNumbers.addAll(tempLineNumbers);
}
}

}
}

else if( currentVar.getClass() == Wire.class){ //if currentVar is of type wire


for(j=0, tempString=new ArrayList();
tempLineNumbers=new ArrayList() ){

j<blocks.size();

j++,

tempString=new

ArrayList(),

currentBlock=blocks.get(j);
if(currentBlock.getClass() == Module.class){
//Should retrive all assignment statements in the module
//but not in module subBlocks
statements = currentBlock.getBlockAssignmentStatements();
for(k=0; k<statements.size(); k++){
currentStatement=statements.get(k);
if(currentStatement.getLHSvars().indexOf( currentVar) != -1 ){
tempString.add(
"Continuous Assignment: assign"
+currentStatement.assignmentText
+ "; (line: "+ currentStatement.getAssignmentStatementLineNumber() +")\n"
);
tempLineNumbers.add(currentStatement.getAssignmentStatementLineNumber());
85

ECE 4899

Final Report: Linting Tool


}
}
}
if(tempString.size() > 1){
errorOutput += tempString+ "\n";
lineNumbers.addAll(tempLineNumbers);
}

}
}
}

if(!errorOutput.equals("Error: Multiply Driven Signals were detected in the following lines of


code:\n")){
Error e = new Error();
e.setErrorMsg(errorOutput);
e.setErrorNum("06");
e.setLineNumbers(lineNumbers);
ErrorList.add(e);
System.out.println(errorOutput);
return ErrorList;
}else{
System.out.println("No Multiply Driven Signals Detected!\n");
return ErrorList;
}
}

}
86

ECE 4899

Final Report: Linting Tool

Error09a_09bIdentifyIncompleteSensList.java
package TestMain;

/**
* @Author:
* @Date:

Kenneth Hassey
5/8/2013

* @Version: 1.000
* Function:
*

Finds sensitivity lists that have unused variables or ports and also

identifies used signals that are not in the sensitivity list.

Combinational blocks only.

*
* Status: Tested Working;
*/

import java.util.ArrayList;

public class Error09a_09bIdentifyIncompleteSensList {


public static ArrayList<Error> getErrors(Parser parser)
{
ArrayList<Error> ErrorList = new ArrayList();

String errorOutput = "No Error";

ArrayList<Block> blocks = parser.getBlockList();


ArrayList<AssignmentStatement> statements;
Variable currentVar;
87

ECE 4899

Final Report: Linting Tool

Block currentBlock;
AssignmentStatement currentStatement;
ArrayList<Variable> SensList;
ArrayList<Variable> OrigSensList;
ArrayList<Variable> UsedVars;

//go through all the blocks


for(int i = 0; i < blocks.size(); i++)
{
currentBlock = blocks.get(i);
if(currentBlock.getClass() == Always.class)
{
if((((Always)currentBlock).BlockType).equals("levelSensitive"))
{
//Get the Sensitivity list for the flip flop type always block
SensList = (((Always)currentBlock).getSensitivityList());
OrigSensList = new ArrayList();
OrigSensList.addAll(SensList);
UsedVars = new ArrayList();
//if there at least one item the sensitivity list
if(SensList.size()>0)
{

statements=currentBlock.getAllAssignmentStatements();
//

for(int j = 0; j < SensList.size() && !statements.isEmpty(); j++)


for(int j = 0; j < statements.size() && !statements.isEmpty(); j++)
{
88

ECE 4899

Final Report: Linting Tool


currentStatement = statements.get(j);
ArrayList<Variable> vl;
vl= currentStatement.RHSvars;

for(int k = 0; k <vl.size(); k++)


{
currentVar = vl.get(k);

//used to identify listed signals


for(int l = 0; l <SensList.size(); l++)
{
if(currentVar.compareTo(SensList.get(l)))
{
SensList.remove(l);
l--;
}
}

//used to identify unlisted signals


if(UsedVars.isEmpty())
{
UsedVars.add(currentVar);
}
for(int l = 0; l <UsedVars.size();l++)
{
89

ECE 4899

Final Report: Linting Tool


if(!(currentVar.compareTo((UsedVars.get(l)))))
{
UsedVars.add(currentVar);
}
}
}
}
for(int j = 0; j < currentBlock.getAllBlocks().size();j++)
{
ArrayList<Block> caseBlock = currentBlock.getAllBlocks();
if((caseBlock.get(j)).getClass() == Case.class)
{
for(int k = 0; k < statements.size() && !statements.isEmpty(); k++)
{

ArrayList<Variable> vl;
vl = ((Case)(caseBlock.get(j))).getCondition().conditionVars;
for(int l = 0; l <vl.size(); l++)
{
currentVar = vl.get(l);

//used to identify listed signals


for(int m = 0; m <SensList.size(); m++)
{
if(currentVar.compareTo(SensList.get(m)))
{
SensList.remove(m);
90

ECE 4899

Final Report: Linting Tool


m--;
}
}
//used to identify unlisted variables
for(int m = 0; m <UsedVars.size();m++)
{
if(!(currentVar.compareTo((UsedVars.get(m)))))
{
UsedVars.add(currentVar);
}
}
}
}
}
}
}

//compare the used list with the original sens list


for(int varCount = 0;varCount <(OrigSensList.size());varCount++)
{
for(int variables = 0;variables<UsedVars.size();variables++)
{
//go though the original sens list
currentVar = UsedVars.get(variables);
if(currentVar.compareTo(OrigSensList.get(varCount)))
{
//remove any matching
91

ECE 4899

Final Report: Linting Tool


UsedVars.remove(variables);
variables--;
}
}
}
//if there is a used signal not listed in the sensitivity list
if(UsedVars.size() > 0)
{
Error e = new Error();
e.setErrorNum("09b");
errorOutput = "Signal(s) used in always block that should be present in sensitivity list but

are not:\n";
errorOutput += "\tin always on line : "+currentBlock.LineNumber +"\n\tUsed Variable(s)
not present in sensitivity list: ";
e.addLineNumber(currentBlock.LineNumber);
//add the unused Vars
for(int varCount = 0;varCount <(UsedVars.size()-1);varCount++)
{
errorOutput+= UsedVars.get(varCount).getName()+", ";
}
errorOutput+=UsedVars.get(UsedVars.size()-1).getName();
System.out.println(errorOutput+"\n");
e.setErrorMsg(errorOutput);
ErrorList.add(e);
}

//if all signals weren't used in the sensitivity list

92

ECE 4899

Final Report: Linting Tool


if(SensList.size()>0)
{
Error e = new Error();
e.setErrorNum("09a");

errorOutput = "Signal(s) present in sensitivity list that are not used as inputs to
combinatorial logic modeled in always block:\n";
errorOutput += "\tin always on line : "+currentBlock.LineNumber +"\n\tUnused Variable(s)
in sensitivity list: ";
e.addLineNumber(currentBlock.LineNumber);
for(int varCount = 0;varCount <(SensList.size()-1);varCount++)
{
errorOutput+= SensList.get(varCount).getName()+", ";
}
errorOutput+=SensList.get(SensList.size()-1).getName();
System.out.println(errorOutput+"\n");
e.setErrorMsg(errorOutput);
ErrorList.add(e);
}
}
}
}
if(errorOutput.equals("No Error"))
{
System.out.println("No Error Detected in Incomplete Sensitivity List\n");
}
return ErrorList;
}
}

93

ECE 4899

Final Report: Linting Tool

Error10vectorArrayInSensList.java
/**
* @Author:
* @Date:

Kenneth Hassey
5/8/2013

* @Version: 1.000
* Function:
*

Looks for vectors in the sensitivity list of always blocks

in edge sensitivity blocks only

*
* Status: Tested Working;
*/
package TestMain;

import java.util.ArrayList;

/**
*
* @author Deathwarror
*/
public class Error10VectorArrayInSensList {
public static ArrayList<Error> getErrors(Parser parser)
{
ArrayList<Error> ErrorList = new ArrayList();

String errorOutput = "No Error";

ArrayList<Block> blocks = parser.getBlockList();


String currentVar;
94

ECE 4899

Final Report: Linting Tool

ArrayList<Variable> Variables = parser.getVariableList();


ArrayList<String> VectorNames = new ArrayList();
Block currentBlock;
String currentStatement;

for(int i = 0;i<Variables.size();i++)
{
//get go through the list and find variables that have a vector parent
if(!(Variables.get(i).vectorParentName.equals("")))
{
int add = 1;
for(int j = 0; j<VectorNames.size();j++)
{
//if the vector name is in the list flag the add variable to don't add
if((VectorNames.get(j).equals(Variables.get(i).vectorParentName)))
{
add = 0;
}
}
//if the vector name wasn't found in the list
if(add == 1)
{
//add it to the list of VectorNames
VectorNames.add(Variables.get(i).vectorParentName);
}
}
}
//go through the list of blocks
95

ECE 4899

Final Report: Linting Tool

for(int i = 0; i < blocks.size();i++)


{
currentBlock = blocks.get(i);
//if the current block is an always block
if(currentBlock.getClass() == Always.class)
{
currentStatement = ((Always)currentBlock).getAlwaysStatement();

if(currentBlock.BlockType.equals("edgeSensitive"))
{
int ignore = 0;
for(int j = 0; j < VectorNames.size();j++)
{
currentVar = VectorNames.get(j);

//if there is a series of vector bits detected


if(currentStatement.contains(":")&&ignore == 0)
{
Error e = new Error();
e.setErrorNum("10");
errorOutput = "Vector or Array Series in Edge Sensitive Always Block:\n";
errorOutput += "\tin always on line : "+currentBlock.LineNumber;
e.addLineNumber(currentBlock.LineNumber);
System.out.println(errorOutput+"\n");
e.setErrorMsg(errorOutput);
ErrorList.add(e);
ignore =1;
}
96

ECE 4899

Final Report: Linting Tool


//see if the VectorName is in the sensitivity list
else if(currentStatement.contains(" "+currentVar+" ")&& ignore == 0)
{
int StartIndex = currentStatement.indexOf(" "+currentVar+" ");
String tempStr = currentStatement.substring(StartIndex);
//if the variable doesn't have a bracket following it.
char debugCharIndex=tempStr.charAt(currentVar.length());
if(tempStr.charAt(currentVar.length()) != '[')
{
Error e = new Error();
e.setErrorNum("10");
errorOutput = "Vector or Array Series in Edge Sensitive Always Block:\n";
errorOutput += "\tin always on line : "+currentBlock.LineNumber+"\n\tVariable Name:

";
errorOutput += currentVar;
e.addLineNumber(currentBlock.LineNumber);
System.out.println(errorOutput+"\n");
e.setErrorMsg(errorOutput);
ErrorList.add(e);
}
}
}
}//end of level sensitive check
}
}

if(errorOutput.equals("No Error"))
{
97

ECE 4899

Final Report: Linting Tool

System.out.println("No Errors Detected In VectorArraySensList\n");


}

return ErrorList;
}
}

98

ECE 4899

Final Report: Linting Tool

Error11LogicalNotWithVector.java
/**
* @Author:
* @Date:

Kenneth Hassey
5/8/2013

* @Version: 1.001
* Function:
*

looks for vectors with a logical not in front of the vector

*
* Status: Tested Working;
*/
package TestMain;

import java.util.ArrayList;

public class Error11LogicalNotWithVector {


public static ArrayList<Error> getErrors(Parser parser)
{
ArrayList<Error> ErrorList = new ArrayList();

String errorOutput = "No Error";

ArrayList<Block> blocks = parser.getBlockList();


Block currentBlock;
String currentVar;
ArrayList<Variable> Variables = parser.getVariableList();
ArrayList<String> VectorNames = new ArrayList();
ArrayList<AssignmentStatement> As;
String currentStatement;
99

ECE 4899

Final Report: Linting Tool

for(int i = 0;i<Variables.size();i++)
{
//get go through the list and find variables that have a vector parent
if(!(Variables.get(i).vectorParentName.equals("")))
{
int add = 1;
for(int j = 0; j<VectorNames.size();j++)
{
//if the vector name is in the list flag the add variable to don't add
if((VectorNames.get(j).equals(Variables.get(i).vectorParentName)))
{
add = 0;
}
}
//if the vector name wasn't found in the list
if(add == 1)
{
//add it to the list of VectorNames
VectorNames.add(Variables.get(i).vectorParentName);
}
}
}

if(blocks.size()>0)
{
//get the top block
currentBlock = blocks.get(0);
100

ECE 4899

Final Report: Linting Tool

//get all assignment statements in the code


As= currentBlock.getAllAssignmentStatements();
for(int j = 0; j < As.size(); j++)
{

//get the assignment text and add a space for missing end character
currentStatement = As.get(j).assignmentText+" ";
for(int k = 0; k<VectorNames.size();k++)
{

//get one of the vector names


currentVar = VectorNames.get(k);
//if a vector was identified
if(currentStatement.contains(" "+currentVar+" "))
{
//get the position of the vector
int index = currentStatement.indexOf(" "+currentVar+" ");
if((index-1)>=0)
{
//get the character before the vector
char debugChar = currentStatement.charAt(index -1);
//see if it was a logical not
if(debugChar =='!')
{

int StartIndex = currentStatement.indexOf(" "+currentVar+" ");


int EndIndex;
String tempStr = currentStatement.substring(StartIndex);
101

ECE 4899

Final Report: Linting Tool

//if the vector does not have indexing


char debugChar2 = tempStr.charAt(currentVar.length()+2);
String debugString = tempStr.substring(currentVar.length()+2);
if(debugChar2!= '[')
{
Error e = new Error();
e.setErrorNum("11");
errorOutput = "Vector or Array Series is being operated on with the logical not
operator:\n";
errorOutput += "\tin always on line : "+As.get(j).LineNumber+"\n\tVariable Name:
";
errorOutput += currentVar;
e.addLineNumber(As.get(j).LineNumber);
System.out.println(errorOutput+"\n");
e.setErrorMsg(errorOutput);
ErrorList.add(e);
}
//if the vector does have indexing
else
{
StartIndex = currentStatement.indexOf("[");
EndIndex = currentStatement.indexOf("]");
tempStr = currentStatement.substring(StartIndex,EndIndex);
//see if the indexing contains an range
if(tempStr.contains(":"))
{
Error e = new Error();

102

ECE 4899

Final Report: Linting Tool


e.setErrorNum("11");
errorOutput = "Vector or Array Series is being operated on with the logical not

operator:\n";
errorOutput += "\tin always on line : "+As.get(j).LineNumber+"\n\tVariable
Name: ";
errorOutput += currentVar;
e.addLineNumber(As.get(j).LineNumber);
System.out.println(errorOutput+"\n");
e.setErrorMsg(errorOutput);
ErrorList.add(e);
}
}
}
}
}
}
}
}

if(errorOutput.equals("No Error"))
{
System.out.println("No Errors Detected In LogicaNotWithVector\n");
}

return ErrorList;
}
}

103

ECE 4899

Final Report: Linting Tool

Error13IdentifyOperatorInSensList.java
/**
* @Author:
* @Date:

Kenneth Hassey
5/8/2013

* @Version: 1.010
* Function:
*

This File is for detection of operators in the sensitivity list of an

always block

*
* Status: Tested Working;
*/

package TestMain;

import java.util.ArrayList;

public class Error13IdentifyOperatorsInSensList {


//This function identifies any operators in the sensitivity list
public static ArrayList<Error> getErrors(Parser parser)
{
ArrayList<Error> ErrorList = new ArrayList();
String errorOutput = "No Error";

ArrayList<Block> blocks = parser.getBlockList();


String AlwaysStatement;
Block currentBlock;
String CharactersIdentified;
//Go through the list of blocks
104

ECE 4899

Final Report: Linting Tool

for(int i = 0;i<blocks.size();i++)
{
//get the current block
currentBlock = blocks.get(i);

//see if the current block is an always block


if(currentBlock.getClass() == Always.class)
{
CharactersIdentified = "";
AlwaysStatement = ((Always)currentBlock).getAlwaysStatement();
int j = AlwaysStatement.indexOf("(");
int k = AlwaysStatement.lastIndexOf(")");
if(j>0&&k>0)
{
AlwaysStatement = AlwaysStatement.substring(j,k);
}
if(AlwaysStatement.contains("="))
{
CharactersIdentified += "=";
}
if(AlwaysStatement.contains("|"))
{
if(CharactersIdentified.equals(""))
CharactersIdentified += "|";
else
CharactersIdentified += ", |";
}
if(AlwaysStatement.contains("&"))
105

ECE 4899

Final Report: Linting Tool

{
if(CharactersIdentified.equals(""))
CharactersIdentified += "&";
else
CharactersIdentified += ", &";
}
if(AlwaysStatement.contains("*"))
{
if(((Always)currentBlock).getSensitivityList().size()>0)
{
if(CharactersIdentified.equals(""))
CharactersIdentified += "*";
else
CharactersIdentified += ", *";
}
}
if(AlwaysStatement.contains("/"))
{
if(CharactersIdentified.equals(""))
CharactersIdentified += "/";
else
CharactersIdentified += ", /";
}
if(AlwaysStatement.contains("+"))
{
if(CharactersIdentified.equals(""))
CharactersIdentified += "+";
else
106

ECE 4899

Final Report: Linting Tool


CharactersIdentified += ", +";

}
if(AlwaysStatement.contains("-"))
{
if(CharactersIdentified.equals(""))
CharactersIdentified += "-";
else
CharactersIdentified += ", -";
}
if(AlwaysStatement.contains("%"))
{
if(CharactersIdentified.equals(""))
CharactersIdentified += "%";
else
CharactersIdentified += ", %";
}
if(AlwaysStatement.contains("!"))
{
if(CharactersIdentified.equals(""))
CharactersIdentified += "!";
else
CharactersIdentified += ", ";
}
if(AlwaysStatement.contains("<"))
{
if(CharactersIdentified.equals(""))
CharactersIdentified += "<";
else
107

ECE 4899

Final Report: Linting Tool


CharactersIdentified += ", <";

}
if(AlwaysStatement.contains(">"))
{
if(CharactersIdentified.equals(""))
CharactersIdentified += ">";
else
CharactersIdentified += ", >";
}
if(AlwaysStatement.contains("^"))
{
if(CharactersIdentified.equals(""))
CharactersIdentified += "^";
else
CharactersIdentified += ", ^";
}
if(AlwaysStatement.contains("~"))
{
if(CharactersIdentified.equals(""))
CharactersIdentified += "~";
else
CharactersIdentified += ", ~";
}
if(AlwaysStatement.contains("?"))
{
if(CharactersIdentified.equals(""))
CharactersIdentified += "?";
else
108

ECE 4899

Final Report: Linting Tool


CharactersIdentified += ", ?";

if(!(CharactersIdentified.equals("")))
{
errorOutput = "Detected Mathametical or Logical operator in the Sensitivity List:\n";
errorOutput += "\tin always on line "+currentBlock.LineNumber+": \n\t Character List:
"+CharactersIdentified;
errorOutput
+=
"+currentBlock.LineNumber+":\t"+((Always)currentBlock).getAlwaysStatement()+";\n";

//put the error message into the error list


Error e = new Error();
e.setErrorMsg(errorOutput);
e.setErrorNum("13");
e.addLineNumber(currentBlock.LineNumber);
ErrorList.add(e);
System.out.println(errorOutput);

}
}

if(errorOutput.equals("No Error"))
{
System.out.println("No Operators In Sensitivity List!\n");

109

"\n\tLine

ECE 4899

Final Report: Linting Tool

return ErrorList;
}
else
{
return ErrorList;
}
}

110

ECE 4899

Final Report: Linting Tool

Error14IdentifyBackwardDrivenPortDirection.java
/**
* @Author:
* @Date:

Kenneth Hassey
5/8/2013

* @Version: 1.010
* Function:
*

This File is for detecting backward port assignment or use.

this flags for any calculations that are using output ports and

input ports being assigned.

*
* Status: Tested Working;
*

Improved due to changes in the parser on the 8th

*/

package TestMain;

import java.util.ArrayList;

public class Error14IdentifyBackwardPortDirection {


//This function Detects if there is an improper used port either on the left
//or on the right hand side of an assignment statement
public static ArrayList<Error> getErrors(Parser parser)
{
ArrayList<Error> ErrorList = new ArrayList();
String errorOutput = "No Error";
int lineFlagged;

111

ECE 4899

Final Report: Linting Tool

ArrayList<Block> blocks = parser.getBlockList();


ArrayList<AssignmentStatement> statements;
ArrayList<Variable> LHSVList;
ArrayList<Variable> RHSVList;
Variable inputVar;
Variable outputVar;
Block currentBlock;

if(!blocks.isEmpty()){
//get the top block
currentBlock = blocks.get(0);

//Get all assignment statements


statements = currentBlock.getAllAssignmentStatements();

for(int j = 0; j < statements.size(); j++)


{
lineFlagged = 0;
//Checks Left hand side for an input
LHSVList = statements.get(j).getLHSvars();
for(int k = 0; k< LHSVList.size();k++)
{
inputVar = LHSVList.get(k);
if(inputVar.variableAttribute.equals("input") &&lineFlagged ==0)
{
errorOutput = "Detected input being assigned:\n";
errorOutput += "\tin always on line "+currentBlock.LineNumber+": \n\t Variable:
"+LHSVList.get(k).name;
112

ECE 4899

Final Report: Linting Tool

errorOutput
+=
"+statements.get(j).LineNumber+":\t"+statements.get(j).assignmentText+";\n";

"\n\tLine

//put the error message into the error list


Error e = new Error();
e.setErrorMsg(errorOutput);
e.addLineNumber(statements.get(j).LineNumber);
e.setErrorNum("14");
ErrorList.add(e);
System.out.println(errorOutput);

//label the input side as already been flagged so that multiply errors arent listed
lineFlagged = 1;
}
}

lineFlagged = 0;
//Look For an output being used in a calculation or right side of assignment
RHSVList = statements.get(j).getRHSvars();
for(int k = 0; k < RHSVList.size();k++)
{
outputVar = RHSVList.get(k);
if(outputVar.variableAttribute.equals("output") &&lineFlagged ==0
&& outputVar.getClass()!= Reg.class)
{
errorOutput = "Detected output being being used in Right Side of equation:\n";
errorOutput += "\tin always on line "+currentBlock.LineNumber+": \n\t Variable:
"+RHSVList.get(k).name;

113

ECE 4899

Final Report: Linting Tool

errorOutput
+=
"+statements.get(j).LineNumber+":\t"+statements.get(j).assignmentText+";\n";

"\n\tLine

//put the error message into the error list


Error e = new Error();
e.setErrorMsg(errorOutput);
e.setErrorNum("14");
e.addLineNumber(statements.get(j).LineNumber);
ErrorList.add(e);
System.out.println(errorOutput);

//label the operation side as already been flagged so that multiply errors arent listed
lineFlagged = 1;
}
}
}

if(errorOutput.equals("No Error"))
{
System.out.println("No Improper used ports!\n");
return ErrorList;
}
else
{
return ErrorList;
}
}
114

ECE 4899

Final Report: Linting Tool

return ErrorList;
}
}

115

ECE 4899

Final Report: Linting Tool

Error15IdentifyBlockingNonBlocking.java
/**
* @Author:
* @Date:

Kenneth Hassey
5/8/2013

* @Version: 1.001
* Function:
*

This File is for detection of blocking and non blocking statements used

in the same always block.

*
* Status: Tested Working;
*/

package TestMain;

import java.util.ArrayList;

public class Error15IdentifyBlockingNonBlocking {


public static ArrayList<Error> getErrors(Parser parser)
{
ArrayList<Error> ErrorList = new ArrayList();

String errorOutput = "No Error";


int blockFlagged;

ArrayList<Block> blocks = parser.getBlockList();


ArrayList<AssignmentStatement> statements;
Block currentBlock;
AssignmentStatement currentStatement;
116

ECE 4899

Final Report: Linting Tool

//Go through the list of blocks


for(int i = 0;i<blocks.size();i++)
{
//get the current block
currentBlock = blocks.get(i);
blockFlagged = 0;
//see if the current block is an always block
if(currentBlock.getClass() == Always.class)
{
//get the list of assignment statements in the always block
statements = currentBlock.getAllAssignmentStatements();

//go through the statements


for(int j = 0; j<statements.size(); j++)
{
currentStatement = statements.get(j);

//see if current statement contains an nonblocking line of code


if(currentStatement.assignmentText.contains("< =")&&blockFlagged == 0)
{
//go though the statements again
for(int k = 0;k<statements.size(); k++)
{
currentStatement = statements.get(k);

//Look for an equals sign to see if it is an blocking line


if(currentStatement.assignmentText.contains("=")&&blockFlagged == 0)
117

ECE 4899

Final Report: Linting Tool


{
int index = currentStatement.assignmentText.indexOf("=");

//verify that it is a blocking line by making sure there is not a non blocking symbol at
the start
if (currentStatement.assignmentText.charAt(index-2) != '<'&&blockFlagged == 0)
{

//create the error message for the line


errorOutput = "Detected blocking and non blocking in following lines of code:\n";
errorOutput += "\tin always on line "+currentBlock.LineNumber+": \n";
errorOutput
"\t"+statements.get(j).LineNumber+":\t"+statements.get(j).assignmentText+";\n";

+=

errorOutput
"\t"+statements.get(k).LineNumber+":\t"+statements.get(k).assignmentText+";\n";

+=

//put the error message into the error list


Error e = new Error();
e.setErrorMsg(errorOutput);
e.setErrorNum("15");
e.addLineNumber(statements.get(j).LineNumber);
e.addLineNumber(statements.get(k).LineNumber);
ErrorList.add(e);
System.out.println(errorOutput);

//label the block as already been flagged so that multiply errors arent listed
blockFlagged = 1;
}
}
118

ECE 4899

Final Report: Linting Tool


}
}

}
}
}

if(errorOutput.equals("No Error"))
{
System.out.println("No NonBlocking with Blocking assignments Detected!\n");
return ErrorList;
}
else
{
return ErrorList;
}
}

119

ECE 4899

Final Report: Linting Tool

Error16IdentifyLatches.java
package TestMain;

import java.util.ArrayList;

public class Error16IdentifyLatches {


public static ArrayList<Error> getErrors(Parser parser)
{
ArrayList<Error> errorList = new ArrayList();
ArrayList<Block> alwaysBlocks = parser.getBlockList();
ArrayList<Variable> LHSvars;
//This loop collects all of the level-sensitive always blocks
//(all of the combinatorial logic blocks)
for(int i=0; i< alwaysBlocks.size(); i++){
if( alwaysBlocks.get(i).getClass() != Always.class
|| !alwaysBlocks.get(i).BlockType.equals("levelSensitive")){
alwaysBlocks.remove(i);
i--;
}
}

for(int i=0; i< alwaysBlocks.size(); i++){


ArrayList<AssignmentStatement>
alwaysBlocks.get(i).getAllAssignmentStatements();
LHSvars = new ArrayList();
for(int j=0;j<assignments.size();j++){
LHSvars.addAll( assignments.get(j).LHSvars );
}
120

assignments

ECE 4899

Final Report: Linting Tool

ArrayList<Variable>tempVars=LHSvars;
LHSvars = new ArrayList();
//This loop makes sure that each unique variable in the always block
// is only checked once
for(int j=0; j<tempVars.size();j++){
if(!LHSvars.contains(tempVars.get(j)) ){
LHSvars.add(tempVars.get(j) );
}
}
checkIfStatements(alwaysBlocks.get(i),errorList);
for(int j=0;j<LHSvars.size();j++){
ArrayList<Error> blockErrors = new ArrayList();
checkSubBlocks(LHSvars.get(j),alwaysBlocks.get(i), blockErrors);
if(!blockErrors.isEmpty()){
String text = "\tError: "+
"variable
("+LHSvars.get(j).name+")
("+alwaysBlocks.get(i).LineNumber+") is a latch,\n"

in

always

block

on

line

+ "\tassignments to "+LHSvars.get(j).name+" are missing from the following conditional


blocks:";
Error err = new Error("16",text, alwaysBlocks.get(i).LineNumber);
errorList.add(err);
errorList.addAll( blockErrors);
}
}
}

return errorList;
}

121

ECE 4899

Final Report: Linting Tool

private static boolean checkSubBlocks(Variable var, Block block, ArrayList<Error> list){


ArrayList<AssignmentStatement> tempAss= block.getBlockAssignmentStatements();
int varPresentInSubBlock=0;
for(int i=0;i<tempAss.size(); i++){
if(tempAss.get(i).LHSvars.contains(var)){
return true;
}
}
for(int i=0; i<block.subBlocks.size(); i++){
if(checkSubBlocks(var,block.subBlocks.get(i), list)){
varPresentInSubBlock++;
}
}
if(block.subBlocks.size()==varPresentInSubBlock && varPresentInSubBlock!=0){
return true;
}else if(block.subBlocks.size()==0){
list.add(error16MissingAssignments(var,block));
}
return false;
}
private static void checkIfStatements(Block block, ArrayList<Error> list){
int ifFlag=0;
for(int i=0; i<block.subBlocks.size(); i++){
if(block.subBlocks.get(i).getClass().equals(IfElse.class) ){
IfElse ie = (IfElse)block.subBlocks.get(i);
if(ie.getIfElseType()==0){//ie==an if statement
ifFlag++;
}else if(ie.getIfElseType()==2){//ie==an else statement
122

ECE 4899

Final Report: Linting Tool


ifFlag--;

}
}
}
if(ifFlag != 0){
list.add(error16MissingElse(block));
}
for(int i=0; i<block.subBlocks.size(); i++){
checkIfStatements(block.subBlocks.get(i), list);
}

return;
}
private static Error error16MissingAssignments(Variable var, Block block){
String text = "\tSub-Error:\n"+
"variable ("+var.name+") not assigned in block on line ("+block.LineNumber+")";
Error err = new Error("16",text, block.LineNumber);
return err;
}
private static Error error16MissingElse(Block block){
String text = "\tError: Laches present\n"+
"\"if\" without corresponding \"else\" in block on line ("+block.LineNumber+")";
Error err = new Error("16",text, block.LineNumber);
return err;
}
}

123

ECE 4899

Final Report: Linting Tool

ErrorDocumentationLoader.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestMain;
/*
* @author: Kenenth Hassey
* @date: 1/23/2013
* @Version: 1.000;
* Function: Reads in the database from the git hub url
* Status: Tested Will need to be tested again
*/
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ErrorDocumentationLoader {

//contains the base url leading to the database directory


private String baseURL = "https://raw.github.com/deathwarror/Linting-Tool/"
+ "master/Database/v/Documentation/";
private String Format;
private BufferedReader in;
private InputStreamReader inStream;
URL DocumentationURL;
//trys running the input streams
ErrorDocumentationLoader(String burl,String format)
124

ECE 4899

Final Report: Linting Tool

{
baseURL = burl;
Format = format;
try{
DocumentationURL = new URL(baseURL);
inStream = new InputStreamReader(DocumentationURL.openStream());
in = new BufferedReader(inStream);
}
catch(Exception e)
{
System.out.println("Documentation Url Streams failed to open.");
}
}
public String getURL(String Number)
{
return baseURL+Number+Format;
}
//trys reading in the database
public String load(String Number)
{
String ed = "";
String ReadLine;
try{
DocumentationURL = new URL(baseURL+Number+Format);
//open the error file
inStream = new InputStreamReader(DocumentationURL.openStream());
in = new BufferedReader(inStream);
}
125

ECE 4899

Final Report: Linting Tool

catch(Exception E)
{
return "Could not get the Documentation for error "
+ Number + ":\nThe page failed to load\n"
+ "\tThis could be caused by no internet connection or \n"
+ "\tthe webpage that holds the information is down.\n"
+ "Documentation Web Address: \n\t"+baseURL+Number+Format+"\n";
}
try{
ReadLine = in.readLine();
while(ReadLine!= null)
{
ed +=ReadLine+"\n";
ReadLine = in.readLine();
}

}
catch(Exception E)
{
return "Something Went wrong while reading the file of error "
+ Number +":\n The reading of the file was unsuccessful.\n"
+ "\tThis could be caused by an unstable internet connection.\n"
+ "Documentation Web Address: \n\t"+baseURL+Number+Format+"\n";
}
return ed;
}
}

126

ECE 4899

Final Report: Linting Tool

ErrorSearcher.java

package TestMain;

import java.util.ArrayList;

/**@author Kenneth Hassey


*@Version 1.000
* @date: 3/8/2013
* Function:
*

Responsible for searching for errors in the files

*/
public class ErrorSearcher {
ArrayList<Error> EL;
ErrorSearcher()
{
EL = new ArrayList();
}
public ArrayList<Error> Start(Parser parser)
{
ClearErrorList();
merge(parser.getParserErrorList());
if(EL.isEmpty()){
merge(Error06IdentifyMultiplyDrivenSignals.getErrors(parser));
merge(Error15IdentifyBlockingNonBlocking.getErrors(parser));
merge(Error14IdentifyBackwardPortDirection.getErrors(parser));
merge(Error13IdentifyOperatorsInSensList.getErrors(parser));
merge(Error03IdentifyAssignmentVsSensType.getErrors(parser));
127

ECE 4899

Final Report: Linting Tool

merge(Error01_05_07IdentifyClockErrors.getErrors(parser));
merge(Error09a_09bIdentifyIncompleteSensList.getErrors(parser));
merge(Error10VectorArrayInSensList.getErrors(parser));
merge(Error11LogicalNotWithVector.getErrors(parser));
merge(Error16IdentifyLatches.getErrors(parser));
}
return EL;
}
private void ClearErrorList()
{
EL = new ArrayList();
}
private void merge(ArrayList<Error> ErrorList)
{
EL.addAll(ErrorList);
}
}

128

ECE 4899

Final Report: Linting Tool

FileRead.java
package TestMain;

/**
* @Author:
* @Date:

Kenneth Hassey
1/7/2013

* @Version: 1.000
* Function:
*

This File is for reading in files given by the user.

Basic Steps are prompt the user for a file and convert it to an

array list of Strings of code to be parsed.

*
* Status: Tested Working;
*/
import javax.swing.JFileChooser;
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
*
*/
public class FileRead {

//Variables declared here for all functions to use.


// JFileChooser is used for a gui file selection so that the user doesn't
129

ECE 4899

Final Report: Linting Tool

// need to place files in a specific location.


private JFileChooser fileChooser;
private File file;
private ArrayList<String> code;
private String FileName;
private String FileType;

//this constructor is required to set up and allow the files to be read.


FileRead()
{
//makes the prompt window for the users file selection
fileChooser = new JFileChooser();
FileName = "";
code = new ArrayList();
//responsible for initial reading and variable writing.
}

private void getFile()


{
try{
int returnVal=fileChooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
file = fileChooser.getSelectedFile();
System.out.println("Opening File: "+file.getName());
}
FileName = file.getName();
130

ECE 4899

Final Report: Linting Tool

FileType = file.getName();
}
catch(Exception e)
{
System.out.println("File Read Error");
}
}

//This function is Responsible for the opening of the file and to convert it
//into strings for return. This function does not return the
//String ArrayList.
private void readFile()
{
code = new ArrayList();
Scanner inputFile;

//
try
{
inputFile = new Scanner(file);
//this block is responsible for converting the file to a arraylist
//of strings.
try{
while (inputFile.hasNext())
{
//adds line of code to the Arraylist.
131

ECE 4899

Final Report: Linting Tool


code.add(inputFile.nextLine());

}
}
//catches exception dealing with array out of bounds for file
//should never trigger.
catch(Exception e )
{
System.out.println("File Has Filed to transfer to ArrayList\n"
+ "Location: FileReader.readFile()");
}
}

//catch an exception most likely dealing with the input file being null
catch(Exception e)
{
System.out.println("File Has Failed to Read\n"
+ "Location: FileReader.readFile()");
}

//used to get a new file from the user and to convert it to a Arraylist of
//Strings. Call this instead of a New Constructor.
public void newFile()
{
getFile();
readFile();
}
132

ECE 4899

Final Report: Linting Tool

//Used to return the file name


public String getFileName()
{
return FileName;
}

//Returns all the code inside the file.


public ArrayList<String> getCode()
{
return code;
}
//needed to print out all information about the fileReader
//this replaced the toString Object.

@Override
public String toString()
{
String comp="";
//@Override
//prints out the file name
//

System.out.println(FileName+":");

//prints out all the code in the files array


for(int i = 0;i<code.size();i++)
{
//

System.out.println("\t"+code.get(i));
133

ECE 4899

Final Report: Linting Tool

comp += code.get(i);
}
//

return ("Successful");
return comp;
}

134

ECE 4899

Final Report: Linting Tool

ForLoop.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestMain;

import java.util.ArrayList;

/**
*
* @author cloud9
*/
public class ForLoop extends Block{
private ArrayList<String> forLoopBody;
private ArrayList<String> whileLoopHead;

ForLoop(String type, Block comesFrom, String name){


BlockType = type;
BlockName = name;
vars = new ArrayList();
subBlocks = new ArrayList();
assignments = new ArrayList();
parent = comesFrom;
forLoopBody = new ArrayList();
whileLoopHead = new ArrayList();
LineNumber = Parser.currentLineNumber;
}
135

ECE 4899

Final Report: Linting Tool

public static void parseForLoop(Block current, Parser parser){


String temp = parser.getNextPiece(); //Should be equal to "("
String lastType="DEFAULT_NET_TYPE";
String lastAttribute = "";
ForLoop forLoop = new ForLoop("forLoop",current, temp);
current.addSubBlock(forLoop);
for(;
!temp.equals(")")
temp=parser.getNextPiece()){

&&

!temp.equals("##END_OF_MODULE_CODE");

forLoop.whileLoopHead.add(temp);
}
forLoop.whileLoopHead.add(temp);
temp = parser.getNextPiece();
forLoop.forLoopBody.add(temp);
if(temp.equals("begin")){
temp = parser.getNextPiece();
for(
int
endCount=0;
(!temp.equals("end")
||
!temp.equals("##END_OF_MODULE_CODE"); temp=parser.getNextPiece()){
forLoop.forLoopBody.add(temp);
if(temp.equals("begin")){
endCount++;
}
else if(temp.equals("end")){
endCount--;
}
}
forLoop.forLoopBody.add(temp);
}else {

136

endCount!=0)

&&

ECE 4899

Final Report: Linting Tool

temp = parser.getNextPiece();
//if the for loop is not wrapped in begin/end it is assumed the loop contains
// only a single assignment statement, and not sub-blocks, this will need to
// be changed in the future if for loops are going to be legitimately used
for(;
!temp.equals(";")
temp=parser.getNextPiece()){

&&

!temp.equals("##END_OF_MODULE_CODE");

forLoop.forLoopBody.add(temp);
}
forLoop.forLoopBody.add(";");
}
}

@Override
public String toString(){
ArrayList<String> forLoopText = whileLoopHead;
forLoopText.addAll(forLoopBody);
String exit="for( ";
for(int i=0; i<forLoopText.size(); i++){
exit += forLoopText.get(i) + " ";
if(forLoopText.get(i).equals("begin")
|| forLoopText.get(i).equals("end")
|| forLoopText.get(i).equals(";") ){
exit += "\n";
}
}
return exit+"\n";
}
}
137

ECE 4899

Final Report: Linting Tool

Function.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestMain;

import java.util.ArrayList;
/**
*
* @author cloud9
*/
public class Function extends Block{
private ArrayList<String> functionText;

Function(String type, Block comesFrom, String name){


BlockType = type;
BlockName = name;
vars = new ArrayList();
subBlocks = new ArrayList();
assignments = new ArrayList();
parent = comesFrom;
functionText = new ArrayList();
LineNumber = Parser.currentLineNumber;
}

public static void parseFunction(Block current, Parser parser){


String temp = parser.getNextPiece(); //should be equal to the function name
138

ECE 4899

Final Report: Linting Tool

String lastType="DEFAULT_NET_TYPE";
String lastAttribute = "";
Function function = new Function("function",current, temp);
current.addSubBlock(function);

for(;
!temp.equals("endfunction")
temp=parser.getNextPiece()){

&&

function.functionText.add(temp);
}
}

@Override
public String toString(){
String exit="function ";
for(int i=0; i<functionText.size(); i++){
exit += functionText.get(i) + " ";
if(functionText.get(i).equals("begin")
|| functionText.get(i).equals("end")
|| functionText.get(i).equals(";") ){
exit += "\n";
}
}
return exit+"endfunction\n";
}
}

139

!temp.equals("##END_OF_MODULE_CODE");

ECE 4899

Final Report: Linting Tool

FunctionCall.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestMain;

import java.util.ArrayList;
/**
*
* @author cloud9
*/
public class FunctionCall extends Variable{
String functionCallText;
ArrayList<String> functionCallElements;
ArrayList<Variable> parameterVars;

FunctionCall(){
functionCallText = "";
functionCallElements = new ArrayList();
parameterVars = new ArrayList();
LineNumber = Parser.currentLineNumber;
}
FunctionCall(String text, ArrayList<String> elements){
functionCallText = text;
functionCallElements = elements;
parameterVars = new ArrayList();
LineNumber = Parser.currentLineNumber;
140

ECE 4899

Final Report: Linting Tool

@Override
public String toString(){
return functionCallText +" //Function Call LINE: "+LineNumber+"\n";
}
}

141

ECE 4899

Final Report: Linting Tool

IfElse.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package TestMain;

import java.util.ArrayList;
/**
*
* @author Hell-o
*/
public class IfElse extends Block {
private ConditionStatement condition;
/*"ifElseBlockOrder" preserves the structureal order of statements and
* subBlocks in and always block.
* 0 - indicates an assignment statement,
* 1- indicates the presence of another subBlock
*/
private ArrayList<Integer> ifElseBlockOrder;
private int ifElseType; //0="if", 1="else if", 2="else"

IfElse(Block comesFrom, String name){


BlockType = "";
BlockName = name;
vars = new ArrayList();
subBlocks = new ArrayList();
142

ECE 4899

Final Report: Linting Tool

assignments = new ArrayList();


ifElseBlockOrder = new ArrayList();

parent = comesFrom;
LineNumber = Parser.currentLineNumber;
}

public static IfElse parseIf(Block current, Parser parser){


IfElse ie = new IfElse(current,"");
current.addSubBlock(ie);
String temp = "";
String statementText = "";
int ifConditionStatementBreak=0;
temp = parser.getNextPiece(); // temp should get a "(" back
//This loop parses the condition statement at the beginning of the if block
for(ifConditionStatementBreak=1, temp=parser.getNextPiece(),
statementText=""; ifConditionStatementBreak!=-1
&& !temp.equals("##END_OF_MODULE_CODE"); ){
if(temp.equals("$#")){
parser.updateLineNumber();
}else if(temp.equals("(")){
ifConditionStatementBreak++;
statementText += temp+ " ";
temp = parser.getNextPiece();
}else if(temp.equals(")")){
ifConditionStatementBreak--;
if(ifConditionStatementBreak!=0){
statementText += temp+ " ";
143

ECE 4899

Final Report: Linting Tool


temp = parser.getNextPiece();

}else {
ifConditionStatementBreak = -1;
}
}else {
statementText += temp+ " ";
temp = parser.getNextPiece();
}
}
ie.condition =
new ConditionStatement(statementText, ie, parser);

temp = parser.getNextPiece();
// if there will be multiple sublocks or assginments
if(temp.equals("$#")){
parser.updateLineNumber();
temp = parser.getNextPiece();
}
if(temp.equals("begin")){
for(temp=parser.getNextPiece();
!temp.equals("end")
!temp.equals("##END_OF_MODULE_CODE"); temp=parser.getNextPiece() ){
if(parser.pieceIsKeyword(temp)){
if(!temp.equals("always")){
parser.checkForNewBlock(ie, temp);
if(!temp.equals("$#"))
ie.ifElseBlockOrder.add(new Integer(1));
}
else{
144

&&

ECE 4899

Final Report: Linting Tool


String errorText = "Error: nested always blocks not allowed";

parser.addErrorToParserErrorList(new
Error("19",errorText,Parser.getCurrentLineNumber()));
parser.stopParsing();
}
}
else if(parser.checkTaskOrFunctionName(temp)!=0){
String taskCallText = "";
ArrayList<String> taskCallElements = new ArrayList();
for(; !temp.equals(";") &&
!temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece()){
taskCallText += temp+" ";
taskCallElements.add(temp);
}
ie.addVariable(new TaskCall(taskCallText,taskCallElements));
ie.ifElseBlockOrder.add(new Integer(2));
}
else if( ie.findVariableInParentBlockHierarchy(temp)!=null ||
!ie.findVectorNameInParentBlockHierarchy(temp).isEmpty()){
for(statementText=""; !temp.equals(";") && !temp.equals("##END_OF_MODULE_CODE");
temp = parser.getNextPiece()){
statementText+=temp+" ";
}
ie.addAssignment(new AssignmentStatement(statementText,ie,parser));
ie.ifElseBlockOrder.add(new Integer(0));
}
else {

145

ECE 4899

Final Report: Linting Tool


//add piece identification error here

}
}
}else {
if(temp.equals("$#")){
parser.checkForNewBlock(ie, temp);
temp = parser.getNextPiece();
}
if(parser.pieceIsKeyword(temp)){
if(!temp.equals("always")){
parser.checkForNewBlock(ie, temp);
if(!temp.equals("$#"))
ie.ifElseBlockOrder.add(new Integer(1));
}
else{
String errorText = "Error: nested always blocks not allowed";
parser.addErrorToParserErrorList(new Error("19",errorText,Parser.getCurrentLineNumber()));
parser.stopParsing();
}
}
else if(parser.checkTaskOrFunctionName(temp)!=0){
String taskCallText = "";
ArrayList<String> taskCallElements = new ArrayList();
for(; !temp.equals(";") &&
!temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece()){
taskCallText += temp+" ";
taskCallElements.add(temp);
146

ECE 4899

Final Report: Linting Tool

}
ie.addVariable(new TaskCall(taskCallText,taskCallElements));
ie.ifElseBlockOrder.add(new Integer(2));
}
else if( ie.findVariableInParentBlockHierarchy(temp)!=null ||
!ie.findVectorNameInParentBlockHierarchy(temp).isEmpty()){
for(statementText=""; !temp.equals(";") && !temp.equals("##END_OF_MODULE_CODE"); temp
= parser.getNextPiece()){
statementText+=temp+" ";
}
ie.addAssignment(new AssignmentStatement(statementText,ie,parser));
ie.ifElseBlockOrder.add(new Integer(0));
}
else {
//add piece identification error here
}
}

return ie;
}
public static String parseElse(Block current, Parser parser){
String temp = parser.getNextPiece();
String statementText = "";
if(temp.equals("$#")){
parser.updateLineNumber();
temp = parser.getNextPiece();
}
//if this "else" statement is really and "else if" then parse it like
147

ECE 4899

Final Report: Linting Tool

// an "if" statment, othewise parse it as an "else"


if(temp.equals("if")){
IfElse ie = parseIf(current, parser);
ie.setIfElseType(1);
}else if(temp.equals("begin")){
IfElse ie = new IfElse(current, "");
current.addSubBlock(ie);
ie.setIfElseType(2);
for(temp=parser.getNextPiece();
!temp.equals("end")
!temp.equals("##END_OF_MODULE_CODE"); temp=parser.getNextPiece() ){
if(parser.pieceIsKeyword(temp)){
parser.checkForNewBlock(ie, temp);
if(!temp.equals("$#"))
ie.ifElseBlockOrder.add(new Integer(1));
}
else if(parser.checkTaskOrFunctionName(temp)!=0){
String taskCallText = "";
ArrayList<String> taskCallElements = new ArrayList();
for(; !temp.equals(";") &&
!temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece()){
taskCallText += temp+" ";
taskCallElements.add(temp);
}
ie.addVariable(new TaskCall(taskCallText,taskCallElements));
ie.ifElseBlockOrder.add(new Integer(2));
}
else if( ie.findVariableInParentBlockHierarchy(temp)!=null ||
148

&&

ECE 4899

Final Report: Linting Tool


!ie.findVectorNameInParentBlockHierarchy(temp).isEmpty()){

for(statementText=""; !temp.equals(";") && !temp.equals("##END_OF_MODULE_CODE");


temp = parser.getNextPiece()){
statementText+=temp+" ";
}
ie.addAssignment(new AssignmentStatement(statementText,ie,parser));
ie.ifElseBlockOrder.add(new Integer(0));
}
else {
//add piece identification error here
}
}
}else {
IfElse ie = new IfElse(current, "");
current.addSubBlock(ie);
ie.setIfElseType(2);
if(temp.equals("$#")){
parser.checkForNewBlock(ie, temp);
temp = parser.getNextPiece();
}
if(parser.pieceIsKeyword(temp)){
parser.checkForNewBlock(ie, temp);
if(!temp.equals("$#"))
ie.ifElseBlockOrder.add(new Integer(1));
}
else if(parser.checkTaskOrFunctionName(temp)!=0){
String taskCallText = "";
ArrayList<String> taskCallElements = new ArrayList();
149

ECE 4899

Final Report: Linting Tool

for(; !temp.equals(";") &&


!temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece()){
taskCallText += temp+" ";
taskCallElements.add(temp);
}
ie.addVariable(new TaskCall(taskCallText,taskCallElements));
ie.ifElseBlockOrder.add(new Integer(2));
}
else if( ie.findVariableInParentBlockHierarchy(temp)!=null ||
!ie.findVectorNameInParentBlockHierarchy(temp).isEmpty()){
for(statementText=""; !temp.equals(";") && !temp.equals("##END_OF_MODULE_CODE"); temp
= parser.getNextPiece()){
statementText+=temp+" ";
}
ie.addAssignment(new AssignmentStatement(statementText,ie,parser));
ie.ifElseBlockOrder.add(new Integer(0));
}
else{
//add piece identification error here
}
}

return temp;
}
public void setIfElseType(int type){
this.ifElseType = type;
150

ECE 4899

Final Report: Linting Tool

}
public ConditionStatement getConditionStatement()
{
return condition;
}
public int getIfElseType(){
return this.ifElseType;
}
@Override
public String toString(){
String temp = "";
int i=0; int subBlockCount=0; int assignmentStatementCount=0; int varsCount=0;
if(this.ifElseType == 0){
temp += "if(";
temp += this.condition.toString();
temp += ") begin \\\\LINE: "+LineNumber+", Vars in Condition: "
+condition.conditionVars.toString()+"\n";
for(i=0, subBlockCount=0, assignmentStatementCount=0, varsCount=0;
i< this.ifElseBlockOrder.size(); i++){
if(ifElseBlockOrder.get(i) == 1){
temp += this.subBlocks.get(subBlockCount).toString();
subBlockCount++;
}else if(!assignments.isEmpty()){
temp += this.assignments.get(assignmentStatementCount);
assignmentStatementCount++;
}else if(!vars.isEmpty()){
temp += this.vars.get(varsCount);
varsCount++;
151

ECE 4899

Final Report: Linting Tool

}
}
temp += "end //ends if()\n";
}else if(this.ifElseType==1){
temp += "else if("; temp += this.condition.toString(); temp += ") begin "
+ "//Vars in Condition: "+condition.conditionVars.toString()+"\n";
for(i=0, subBlockCount=0, assignmentStatementCount=0, varsCount=0;
i< this.ifElseBlockOrder.size(); i++){
if(ifElseBlockOrder.get(i) == 1){
temp += this.subBlocks.get(subBlockCount).toString();
subBlockCount++;
}else if(!assignments.isEmpty()){
temp += this.assignments.get(assignmentStatementCount);
assignmentStatementCount++;
}else if(!vars.isEmpty()){
temp += this.vars.get(varsCount);
varsCount++;
}
}
temp += "end //ends else if()\n";
}else {
temp += "else begin\n";
for(i=0, subBlockCount=0, assignmentStatementCount=0, varsCount=0;
i< this.ifElseBlockOrder.size(); i++){
if(ifElseBlockOrder.get(i) == 1){
temp += this.subBlocks.get(subBlockCount).toString();
subBlockCount++;
}else if(!assignments.isEmpty()){
152

ECE 4899

Final Report: Linting Tool


temp += this.assignments.get(assignmentStatementCount);
assignmentStatementCount++;

}else if(!vars.isEmpty()){
temp += this.vars.get(varsCount);
varsCount++;
}
}
temp += "end //ends else\n";
}

return temp;
}
}

153

ECE 4899

Final Report: Linting Tool

IntegerVariable.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestMain;

import java.util.ArrayList;

/**
*
* @author cloud9
*/
public class IntegerVariable extends Variable{
protected int startValue;
protected String startValueString;

IntegerVariable(String name_in)
{
name = name_in;
variableType = "IntegerVariable";
variableAttribute = "";
edgeSensitivity = "";
vectorParentName = "";
LineNumber = Parser.currentLineNumber;
variableSign = "";
arraySize = 0;
startValue = 0;
154

ECE 4899

Final Report: Linting Tool

startValueString = "";
}
IntegerVariable(ArrayList<String> startVals)
{
name = "";
variableType = "IntegerVariable";
variableAttribute = "";
edgeSensitivity = "";
vectorParentName = "";
LineNumber = Parser.currentLineNumber;
variableSign = "";
arraySize = 0;
startValueString = "";

parseIntegerVariable(startVals);
}

private void parseIntegerVariable(ArrayList<String> pieces){


int equalsFlag,i;
for(i=0, equalsFlag=0; i<pieces.size(); i++){
if(pieces.get(i).equals("signed") || pieces.get(i).equals("unsigned")){
variableSign = pieces.get(i);
}
else if(pieces.get(i).equals("=")){
equalsFlag=1;
}
else if(equalsFlag==0 && Module.checkVariableName(pieces.get(i))){
name = pieces.get(i);
155

ECE 4899

Final Report: Linting Tool

}
else if(Parser.isANumber(pieces.get(i))==1 && equalsFlag==1){
startValue = Integer.parseInt(Parser.parseNumberFromExpression(pieces.get(i)+" "));
startValueString = Integer.toString(startValue);
}else {
startValue = 0;
startValueString = pieces.get(i);
}
}

@Override
public String toString(){
return variableAttribute + " " + variableType + " " + variableSign + " " +
name + " = "+startValueString+"; LINE: " + LineNumber;
}
}

156

ECE 4899

Final Report: Linting Tool

MainGUI.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestMain;

import com.sun.corba.se.impl.util.Version;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;

/**
*
* @author Deathwarror
*/
public class MainGUI extends javax.swing.JFrame {

private String ErrorLineColor = "F78181";


157

ECE 4899

Final Report: Linting Tool

private String CommentColor = "04B404";


private String KeywordColor = "0404B4";
private String QuoteColor = "FFD006";
private
String
DocumentationURL
tool.googlecode.com/git/Database/v/Documentation/";
private String DocumentationType = ".html";
private String DefaultDocType = ".txt";
private DefaultListModel FileListModel;
private DefaultListModel ErrorListModel;
private DefaultListModel CodeListModel;
private int ScreenHeight;
private int ScreenWidth;
private Dimension dim;
/**
* Creates new form MainGUI
*/
public MainGUI() {
initComponents();

FileListModel = new DefaultListModel();


ErrorListModel = new DefaultListModel();
CodeListModel = new DefaultListModel();
FileListBox.setModel(FileListModel);
ErrorListBox.setModel(ErrorListModel);
CodeListBox.setModel(CodeListModel);
RemoveButton.setEnabled(false);
Toolkit toolkit = Toolkit.getDefaultToolkit();
dim = toolkit.getScreenSize();
158

"https://linting-

ECE 4899

Final Report: Linting Tool

ScreenHeight = (int)(dim.height*.8);
ScreenWidth = (int)(dim.width*.8);
VersionNumber.setText(("Version: "+version.version));
this.setSize(new Dimension(ScreenWidth,ScreenHeight));
this.setLocation((int)((dim.width-ScreenWidth)/2),(int)((dim.height-ScreenHeight)/2));
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

FileListPane = new javax.swing.JScrollPane();


FileListBox = new javax.swing.JList();
AddButton = new javax.swing.JButton();
RemoveButton = new javax.swing.JButton();
FileListTitle = new javax.swing.JLabel();
CodeListTitle = new javax.swing.JLabel();
ErrorMsgTitle = new javax.swing.JLabel();
ErrorListPane = new javax.swing.JScrollPane();
ErrorListBox = new javax.swing.JList();
CodeListPane = new javax.swing.JScrollPane();
CodeListBox = new javax.swing.JList();
VersionNumber = new javax.swing.JLabel();

159

ECE 4899

Final Report: Linting Tool

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Linting Tool");
setBounds(new java.awt.Rectangle(0, 0, 800, 600));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

FileListBox.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
FileListBoxValueChanged(evt);
}
});
FileListPane.setViewportView(FileListBox);

AddButton.setText("Load File");
AddButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AddButtonActionPerformed(evt);
}
});

RemoveButton.setText("Remove File");
RemoveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RemoveButtonActionPerformed(evt);
}
});

FileListTitle.setText("Files Opened");

160

ECE 4899

Final Report: Linting Tool

CodeListTitle.setText("File data");

ErrorMsgTitle.setText("Error Messages");

ErrorListBox.setToolTipText("Right Click For More Information about the Error (Requires Internet
Connection)");
ErrorListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ErrorListBoxMouseClicked(evt);
}
});
ErrorListBox.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
ErrorListBoxValueChanged(evt);
}
});
ErrorListPane.setViewportView(ErrorListBox);

CodeListPane.setViewportView(CodeListBox);

VersionNumber.setText("jLabel1");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
161

ECE 4899

Final Report: Linting Tool

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ErrorListPane)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(FileListPane,
javax.swing.GroupLayout.PREFERRED_SIZE)

javax.swing.GroupLayout.PREFERRED_SIZE,

172,

.addComponent(FileListTitle)
.addComponent(ErrorMsgTitle)
.addGroup(layout.createSequentialGroup()
.addComponent(AddButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(RemoveButton,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(CodeListTitle)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(VersionNumber))
.addComponent(CodeListPane))
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(FileListTitle,
javax.swing.GroupLayout.PREFERRED_SIZE)

javax.swing.GroupLayout.PREFERRED_SIZE,

162

14,

ECE 4899

Final Report: Linting Tool


.addComponent(CodeListTitle)
.addComponent(VersionNumber))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(FileListPane)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(AddButton)
.addComponent(RemoveButton)))
.addComponent(CodeListPane))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ErrorMsgTitle)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ErrorListPane,
javax.swing.GroupLayout.PREFERRED_SIZE))

javax.swing.GroupLayout.PREFERRED_SIZE,

);

pack();
}// </editor-fold>

private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
SimpleFileStore newFile = new SimpleFileStore();
FileRead FR = new FileRead();
Parser parser;
ErrorSearcher ES = new ErrorSearcher();
FR.newFile();
163

221,

ECE 4899

Final Report: Linting Tool

if(!FR.getFileName().equals(""))
{
newFile.setCode(FR.getCode());
newFile.setName(FR.getFileName());
System.out.println("enter");
parser = new Parser(newFile.getCode());
System.out.println("exit parser");
newFile.setErrorList(ES.Start(parser));
System.out.println("exit Error list");
FileListModel.addElement(newFile);
FileListBox.setSelectedIndex(FileListModel.size()-1);
FileListBox.ensureIndexIsVisible(FileListModel.size()-1);
}
else
{
JOptionPane.showMessageDialog(new JFrame(), "Error the File Failed to Read");
}

private void FileListBoxValueChanged(javax.swing.event.ListSelectionEvent evt) {


// TODO add your handling code here:
if(evt.getValueIsAdjusting()==false)
{
int index = FileListBox.getSelectedIndex();
SimpleFileStore WorkingStore;
ArrayList<String> Code;
ArrayList<Error> Errors;
164

ECE 4899

Final Report: Linting Tool

String FileCode;

//Clear The ErrorList and the Code List here


ErrorListModel.clear();
CodeListModel.clear();
if(index == -1)
{
RemoveButton.setEnabled(false);
}
else
{
WorkingStore = (SimpleFileStore) FileListModel.get(index);
Code = WorkingStore.getCode();
Code = ReplaceSpecialCharacter(Code);
Code = HighlightKeyWords(Code);
Errors = WorkingStore.getErrorList();
RemoveButton.setEnabled(true);
for(int i = 0; i<Code.size();i++)
{
FileCode = AdjustLine(i+1,Code.get(i));
CodeListModel.addElement("<html>"+FileCode+"</html>");
}

for(int i = 0; i<Errors.size();i++)
{
Error e = Errors.get(i);
if(!e.getLineNumbers().isEmpty()){
165

ECE 4899

Final Report: Linting Tool

String Temp = ReplaceSpecialCharacterS(e.getLineNumbers().get(0)+":


"+e.getErrorNum()+": "+e.getErrorMsg()+"\n\n");

Error

Temp = convertToHTML(Temp);
ErrorListModel.addElement("<html>"+Temp+"</html>");
}else {
String
Temp
"+e.getErrorMsg()+"\n\n");

ReplaceSpecialCharacterS("Error

Temp = convertToHTML(Temp);
ErrorListModel.addElement("<html>"+Temp+"</html>");
}
}
if(Errors.isEmpty())
{
ErrorListModel.addElement("No Errors Detected");
}
}
}
}

private void RemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {


int index = FileListBox.getSelectedIndex();
if(index != -1)
{
String FileName = ((SimpleFileStore) FileListModel.get(index)).getName();
FileListModel.remove(index);
}

166

"+e.getErrorNum()+":

ECE 4899

Final Report: Linting Tool

int size = FileListModel.getSize();


if(size == 0)
{
RemoveButton.setEnabled(false);
}
else
{
if(index == FileListModel.getSize())
{
index--;
}
FileListBox.setSelectedIndex(index);
FileListBox.ensureIndexIsVisible(index);
}

private void ErrorListBoxValueChanged(javax.swing.event.ListSelectionEvent evt) {


// TODO add your handling code here:
if(evt.getValueIsAdjusting()==false)
{
int index = ErrorListBox.getSelectedIndex();
int FileIndex = FileListBox.getSelectedIndex();
SimpleFileStore WorkingStore;
Error e;
ArrayList<Error> EL;
ArrayList<Integer> ErrorLines;
167

ECE 4899

Final Report: Linting Tool

ArrayList<String> Code;
String FileCode;
//if nothing is selected

if(index == -1)
{
}
else
{

WorkingStore = (SimpleFileStore) FileListModel.get(FileIndex);


EL = WorkingStore.getErrorList();
Code = WorkingStore.getCode();
Code = ReplaceSpecialCharacter(Code);
Code = HighlightKeyWords(Code);

if(EL.size() >0)
{
//if Something was selected
CodeListModel.clear();

e = EL.get(index);
ErrorLines = e.getLineNumbers();
sortLineNumbers(ErrorLines);
//fill the cell with
int j = 0;

//rebuilds the HTML code so that the error lines are highlighted
168

ECE 4899

Final Report: Linting Tool


for(int i = 0; i<Code.size();i++)
{
FileCode = AdjustLine(i+1,Code.get(i));
if(j < ErrorLines.size())
{
if(ErrorLines.get(j).intValue()-1 == i)
{
FileCode = "<body bgcolor="+ErrorLineColor+"\">"+FileCode;
j++;
}
}
CodeListModel.addElement("<html>"+FileCode+"</html>");
}

}
}
}
}

private void ErrorListBoxMouseClicked(java.awt.event.MouseEvent evt) {


//if the right mouse button was used
if(evt.getButton() ==java.awt.event.MouseEvent.BUTTON3)
{
ErrorDocumentationLoader
EDL
ErrorDocumentationLoader(DocumentationURL,DocumentationType);

new

ErrorDocumentationLoader
EDL2
ErrorDocumentationLoader(DocumentationURL,DefaultDocType);

new

String Description;
SimpleFileStore WorkingStore;

169

ECE 4899

Final Report: Linting Tool

ArrayList<Error> EL;
String ErrorNumber;
JEditorPane ErrorD;
JScrollPane JSP;

int FileIndex = FileListBox.getSelectedIndex();


int index = ErrorListBox.getSelectedIndex();
if(index>=0)
{
WorkingStore = (SimpleFileStore) FileListModel.get(FileIndex);
EL = WorkingStore.getErrorList();

if(EL.size()>0)
{
ErrorNumber = EL.get(index).getErrorNum();
//try using the gui based load method

DocumentationGui dialog = new DocumentationGui(new javax.swing.JFrame(), true,


ErrorNumber,DocumentationURL,DocumentationType,DefaultDocType);

}
}

}
}

private String ReplaceSpecialCharacterS(String s)


170

ECE 4899

Final Report: Linting Tool

{
s=s.replaceAll("&","&#38");
s=s.replaceAll("<","&#60");
s=s.replaceAll("<","&#62");
return s;
}
private ArrayList<String> ReplaceSpecialCharacter(ArrayList<String>al)
{
ArrayList<String> temp = new ArrayList();
String s;
for(int i = 0; i <al.size();i++)
{
s = al.get(i);
s=s.replaceAll("&","&#38");
s=s.replaceAll("<","&#60");
s=s.replaceAll("<","&#62");
temp.add(s);
}

return temp;
}
//converts the arraylist of numbers to an integer array
private static void sortLineNumbers(ArrayList<Integer> arr){
int i=0, j=0;
Integer temp = new Integer(0);
for(i=0; i<arr.size(); i++){
for(j=0; j<arr.size()-(i+1); j++){
if(arr.get(j).compareTo(arr.get(j+1)) == 1){
171

ECE 4899

Final Report: Linting Tool


temp = arr.get(j);
arr.set(j, arr.get(j+1));
arr.set(j+1, temp);

}
}
for(int k = 0; k <arr.size()-1;k++)
{
if(arr.get(k).compareTo(arr.get(k+1))==0)
{
arr.remove(k);
k--;
}
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for
(javax.swing.UIManager.LookAndFeelInfo
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
172

info

ECE 4899

Final Report: Linting Tool


javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;

}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
}
//</editor-fold>

/* Create and display the form */


java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new MainGUI().setVisible(true);
}
});
}
private String AdjustLine(int i, String text){
String Temp = i+":&#8202;";

173

ECE 4899

Final Report: Linting Tool

String inte = ""+i;


for(int j = 0; j<(4-inte.length());j++)
{
Temp= Temp+"&nbsp;&nbsp;";
}
return Temp+convertToHTML(text);
}
private ArrayList<String> HighlightKeyWords(ArrayList<String> TempAL){
ArrayList<String> newLines = new ArrayList();
String temp1, temp2;
int startIndex=0,endIndex = 0;
boolean blockComment = false;
for(int i = 0; i < TempAL.size();i++)
{
temp1 = "";
temp2 = " "+TempAL.get(i)+" ";

temp2 = replaceAll(temp2);

boolean inQuote = false;


char[] arr = temp2.toCharArray();
String line = "", line2 = "";
for(int k=1; k<arr.length; k++){
if(arr[k]=='\"' && arr[k-1]!='\\' && !inQuote){
line += line2; line2="";
line += "<font color=#"+QuoteColor+">\"";
inQuote = true;
}
174

ECE 4899

Final Report: Linting Tool

else if(arr[k]=='\"' && arr[k-1]!='\\' && inQuote){


line2 = removePreviousColors(line2);
line += line2; line2 = "";
line += "\"</font>";
inQuote = false;
}
else{
line2 += arr[k];
}
}

line += line2;
temp2 = line;

if(blockComment && !temp2.contains("*/")){


temp2 = removePreviousColors(temp2);
temp2 = "<font color=#"+CommentColor+">"+temp2;
temp2 += "</font>";
}
else if(temp2.contains("/*") && !temp2.contains("*/"))
{
startIndex = temp2.indexOf("/*");
temp1 = temp2.substring(0,startIndex);
temp1 = replaceAll(temp1);
temp2 = removePreviousColors(temp2.substring(startIndex));
temp2 = temp1+temp2;
temp2 = temp2.replace("/*","<font color=#"+CommentColor+">/*");
temp2 = temp2 + "</font>";
175

ECE 4899

Final Report: Linting Tool

blockComment = true;
}
else if(temp2.contains("/*") && temp2.contains("*/"))
{
temp2 = removePreviousColors(temp2);
int comNum = 0;
boolean lineCom = false;
arr = temp2.toCharArray();
line = "";
for(int j=1; j<arr.length; j++){
if(arr[j]=='*' && arr[j-1]=='/' && !lineCom){
if(line.length()>0){
line = line.substring(0, line.length()-1);
}
line = replaceAll(line);
line += "<font color=#"+CommentColor+">/*";
comNum++;
}
else if(arr[j]=='/' && arr[j-1]=='*' && !lineCom){
line += "/</font>";
comNum--;
lineCom = false;
}
else if(arr[j]=='/' && arr[j-1]=='/'){
if(line.length()>0){
line = line.substring(0, line.length()-1);
}
line = replaceAll(line);
176

ECE 4899

Final Report: Linting Tool


line += "<font color=#"+CommentColor+">//";
}
else{
line += arr[j];
}

if(lineCom){
line += "</font>/";
}
else if(comNum > 0){
line += "</font>/";
blockComment = true;
}
temp2 = line;
}
else if(temp2.contains("*/"))
{

startIndex = temp2.indexOf("*/");
temp1 = temp2.substring(startIndex);
temp1 = replaceAll(temp1);
temp2 = removePreviousColors(temp2.substring(0,startIndex))+temp1;
temp2 = temp2.replace("*/","*/</font>");
temp2 = "<font color=#"+CommentColor+">"+ temp2;
blockComment = false;
}
else if(temp2.contains("//"))
177

ECE 4899

Final Report: Linting Tool

{
startIndex = temp2.indexOf("//");
temp1 = temp2.substring(0,startIndex);
temp1 = replaceAll(temp1);
temp2 = temp1+removePreviousColors(temp2.substring(startIndex));
temp2 = temp2.replace("//","<font color=#"+CommentColor+">//");
temp2 = temp2+"</font>";
}

newLines.add(temp2);
}
return newLines;
}
private String replaceAll(String S){
//module
S = S.replaceAll(" module "," <font color=#"+KeywordColor+">module</font> ");
S = S.replaceAll(";module ",";<font color=#"+KeywordColor+">module</font> ");
S = S.replaceAll("module ","<font color=#"+KeywordColor+">module</font> ");
//input
S = S.replaceAll(" input "," <font color=#"+KeywordColor+">input</font> ");
S = S.replaceAll(",input ",",<font color=#"+KeywordColor+">input</font> ");
S = S.replaceAll(";input ",";<font color=#"+KeywordColor+">input</font> ");
S = S.replaceAll("\\(input ","\\(<font color=#"+KeywordColor+">input</font> ");
//inout
S = S.replaceAll(" inout "," <font color=#"+KeywordColor+">inout</font> ");
S = S.replaceAll(",inout ",",<font color=#"+KeywordColor+">inout</font> ");
S = S.replaceAll(";inout ",";<font color=#"+KeywordColor+">inout</font> ");
S = S.replaceAll("\\(inout ","\\(<font color=#"+KeywordColor+">inout</font> ");
178

ECE 4899

Final Report: Linting Tool

//output
S = S.replaceAll(" output "," <font color=#"+KeywordColor+">output</font> ");
S = S.replaceAll(",output ",",<font color=#"+KeywordColor+">output</font> ");
S = S.replaceAll(";output ",";<font color=#"+KeywordColor+">output</font> ");
S = S.replaceAll("\\(output ","\\(<font color=#"+KeywordColor+">output</font> ");
//parameter
S = S.replaceAll(" parameter "," <font color=#"+KeywordColor+">parameter</font> ");
S = S.replaceAll(";parameter ",";<font color=#"+KeywordColor+">parameter</font> ");
S = S.replaceAll(" parameter="," <font color=#"+KeywordColor+">parameter</font>=");
S = S.replaceAll(";parameter=",";<font color=#"+KeywordColor+">parameter</font>=");
//localparameter
S = S.replaceAll(" localparam "," <font color=#"+KeywordColor+">localparam</font> ");
S = S.replaceAll(";localparam ",";<font color=#"+KeywordColor+">localparam</font> ");
S = S.replaceAll(" localparam="," <font color=#"+KeywordColor+">localparam</font>=");
S = S.replaceAll(";localparam=",";<font color=#"+KeywordColor+">localparam</font>=");
//register
S = S.replaceAll(" reg ", " <font color=#"+KeywordColor+">reg</font> ");
S = S.replaceAll(";reg ", ";<font color=#"+KeywordColor+">reg</font> ");
//wire
S = S.replaceAll(" wire ", " <font color=#"+KeywordColor+">wire</font> ");
S = S.replaceAll(";wire ", ",<font color=#"+KeywordColor+">wire</font> ");
//always
S = S.replaceAll(" always "," <font color=#"+KeywordColor+">always</font> ");
S = S.replaceAll(";always ",";<font color=#"+KeywordColor+">always</font> ");
S = S.replaceAll(" always@"," <font color=#"+KeywordColor+">always</font>@");
S = S.replaceAll(";always@",";<font color=#"+KeywordColor+">always</font>@");
//if
S = S.replaceAll(" if "," <font color=#"+KeywordColor+">if</font> ");
179

ECE 4899

Final Report: Linting Tool

S = S.replaceAll(";if ",";<font color=#"+KeywordColor+">if</font> ");


S = S.replaceAll(" if\\("," <font color=#"+KeywordColor+">if</font>\\(");
S = S.replaceAll(";if\\(",";<font color=#"+KeywordColor+">if</font>\\(");
//else
S = S.replaceAll(";else ",";<font color=#"+KeywordColor+">else</font> ");
S = S.replaceAll(" else "," <font color=#"+KeywordColor+">else</font> ");
//end
S = S.replaceAll(";end ",";<font color=#"+KeywordColor+">end</font> ");
S = S.replaceAll(";end;",";<font color=#"+KeywordColor+">end</font>;");
S = S.replaceAll("\\)end ","\\)<font color=#"+KeywordColor+">end</font> ");
S = S.replaceAll("\\)end;","\\)<font color=#"+KeywordColor+">end</font>;");
S = S.replaceAll(" end;"," <font color=#"+KeywordColor+">end</font>;");
S = S.replaceAll(" end "," <font color=#"+KeywordColor+">end</font> ");
S = S.replaceAll(";end\\(",";<font color=#"+KeywordColor+">end</font>\\(");
S = S.replaceAll(" end\\("," <font color=#"+KeywordColor+">end</font>\\(");
S = S.replaceAll("end"," <font color=#"+KeywordColor+">end</font>");
//begin
S = S.replaceAll(";begin ",";<font color=#"+KeywordColor+">begin</font> ");
S = S.replaceAll(";begin;",";<font color=#"+KeywordColor+">begin</font>;");
S = S.replaceAll(" begin;"," <font color=#"+KeywordColor+">begin</font>;");
S = S.replaceAll(" begin "," <font color=#"+KeywordColor+">begin</font> ");
S = S.replaceAll("\\)begin ","\\)<font color=#"+KeywordColor+">begin</font> ");
S = S.replaceAll("\\)begin;","\\)<font color=#"+KeywordColor+">begin</font>;");
S = S.replaceAll(";begin\\(",";<font color=#"+KeywordColor+">begin</font>\\(");
S = S.replaceAll(" begin\\("," <font color=#"+KeywordColor+">begin</font>\\(");
//endmodule
S = S.replaceAll(";endmodule ",";<font color=#"+KeywordColor+">endmodule</font> ");
S = S.replaceAll(" endmodule "," <font color=#"+KeywordColor+">endmodule</font> ");
180

ECE 4899

Final Report: Linting Tool

S = S.replaceAll("endmodule"," <font color=#"+KeywordColor+">endmodule</font> ");


//case
S = S.replaceAll(";case ",";<font color=#"+KeywordColor+">case</font> ");
S = S.replaceAll(" case "," <font color=#"+KeywordColor+">case</font> ");
S = S.replaceAll(";case\\(",";<font color=#"+KeywordColor+">case</font>\\(");
S = S.replaceAll(" case\\(",";<font color=#"+KeywordColor+">case</font>\\(");

//endcase
S = S.replaceAll(";endcase ",";<font color=#"+KeywordColor+">endcase</font> ");
S = S.replaceAll(";endcase;",";<font color=#"+KeywordColor+">endcase</font>;");
S = S.replaceAll(" endcase;"," <font color=#"+KeywordColor+">endcase</font>;");
S = S.replaceAll(" endcase "," <font color=#"+KeywordColor+">endcase</font> ");
S = S.replaceAll(";endcase\\(",";<font color=#"+KeywordColor+">endcase</font>\\(");
S = S.replaceAll(" endcase\\("," <font color=#"+KeywordColor+">endcase</font>\\(");
S = S.replaceAll("\\)endcase ","\\)<font color=#"+KeywordColor+">endcase</font> ");
S = S.replaceAll("\\)endcase;","\\)<font color=#"+KeywordColor+">endcase</font>;");
//default
S = S.replaceAll(";default ",";<font color=#"+KeywordColor+">default</font> ");
S = S.replaceAll(" default "," <font color=#"+KeywordColor+">default</font> ");
//forever
S = S.replaceAll(";forever ",";<font color=#"+KeywordColor+">forever</font> ");
S = S.replaceAll(" forever "," <font color=#"+KeywordColor+">forever</font> ");
//task
S = S.replaceAll(";task ",";<font color=#"+KeywordColor+">task</font> ");
S = S.replaceAll(" task "," <font color=#"+KeywordColor+">task</font> ");
S = S.replaceAll(";task\\(",";<font color=#"+KeywordColor+">task</font>\\(");
S = S.replaceAll(" task\\("," <font color=#"+KeywordColor+">task</font>\\(");
//function
181

ECE 4899

Final Report: Linting Tool

S = S.replaceAll(";function ",";<font color=#"+KeywordColor+">function</font> ");


S = S.replaceAll(" function "," <font color=#"+KeywordColor+">function</font> ");
S = S.replaceAll(";function\\(",";<font color=#"+KeywordColor+">function</font>\\(");
S = S.replaceAll(" function\\("," <font color=#"+KeywordColor+">function</font>\\(");
//while
S = S.replaceAll(";while ",";<font color=#"+KeywordColor+">while</font> ");
S = S.replaceAll(" while "," <font color=#"+KeywordColor+">while</font> ");
S = S.replaceAll(";while\\(",";<font color=#"+KeywordColor+">while</font>\\(");
S = S.replaceAll(" while\\("," <font color=#"+KeywordColor+">while</font>\\(");
//for
S = S.replaceAll(";for ",";<font color=#"+KeywordColor+">for</font> ");
S = S.replaceAll(" for "," <font color=#"+KeywordColor+">for</font> ");
S = S.replaceAll(";for\\(",";<font color=#"+KeywordColor+">for</font>\\(");
S = S.replaceAll(" for\\("," <font color=#"+KeywordColor+">for</font>\\(");
//repeat
S = S.replaceAll(";repeat ",";<font color=#"+KeywordColor+">repeat</font> ");
S = S.replaceAll(" repeat "," <font color=#"+KeywordColor+">repeat</font> ");
S = S.replaceAll(";repeat\\(",";<font color=#"+KeywordColor+">repeat</font>\\(");
S = S.replaceAll(" repeat\\("," <font color=#"+KeywordColor+">repeat</font>\\(");
//initial
S = S.replaceAll(";initial ",";<font color=#"+KeywordColor+">initial</font> ");
S = S.replaceAll(" initial "," <font color=#"+KeywordColor+">initial</font> ");
S = S.replaceAll(";initial\\(",";<font color=#"+KeywordColor+">initial</font>\\(");
S = S.replaceAll(" initial\\("," <font color=#"+KeywordColor+">initial</font>\\(");
return S;
}
private String removePreviousColors(String S){
String s = S;
182

ECE 4899

Final Report: Linting Tool

String ss = "";
int i, last;
boolean dont = false;
for(i=s.indexOf("<font"),last=0; i!=-1;i=s.indexOf("<font")){
ss += s.substring(last, i);
if(!dont){
i = s.indexOf(">")+1;
dont = true;
}else {
i = s.indexOf(">")+1;
s = s.substring(i, s.length());
i = s.indexOf(">")+1;
dont = false;
}
s = s.substring(i, s.length());
}
ss += s.substring(0, s.length());
s = ss; ss= "";
for(i=s.indexOf("</font>"),last=0; i!=-1;last=0,i=s.indexOf("</font>")){
ss += s.substring(last, i);
i = s.indexOf(">")+1;
s = s.substring(i, s.length());
}
ss += s.substring(0, s.length());
return ss;
}

private String convertToHTML(String S){


183

ECE 4899

Final Report: Linting Tool

String Temp = S;
Temp = Temp.replaceAll("\n","<br>");
Temp = Temp.replaceAll("\t","&nbsp;&nbsp;&nbsp;&nbsp;");
Temp = Temp.replaceAll(" ","&nbsp;");
return Temp;
}
// Variables declaration - do not modify
private javax.swing.JButton AddButton;
private javax.swing.JList CodeListBox;
private javax.swing.JScrollPane CodeListPane;
private javax.swing.JLabel CodeListTitle;
private javax.swing.JList ErrorListBox;
private javax.swing.JScrollPane ErrorListPane;
private javax.swing.JLabel ErrorMsgTitle;
private javax.swing.JList FileListBox;
private javax.swing.JScrollPane FileListPane;
private javax.swing.JLabel FileListTitle;
private javax.swing.JButton RemoveButton;
private javax.swing.JLabel VersionNumber;
// End of variables declaration

184

ECE 4899

Final Report: Linting Tool

Module.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package TestMain;

import java.util.ArrayList;

/**
*
* @author Hell-o
*/
public class Module extends Block{

protected ArrayList<Variable> preParameters;


protected ArrayList<Parameter> parameters;
protected ArrayList<Variable> portVariables;
protected ArrayList<ModuleInstantiation> subModules;
String statementText;

Module(){
BlockType = "";
BlockName = "";
statementText = "";
vars = new ArrayList();
subBlocks = new ArrayList();
185

ECE 4899

Final Report: Linting Tool

assignments = new ArrayList();


preParameters = new ArrayList();
parameters = new ArrayList();
portVariables = new ArrayList();
subModules = new ArrayList();
LineNumber = Parser.currentLineNumber;
}
Module(String type, Block comesFrom){
BlockType = type;
BlockName = "";
vars = new ArrayList();
subBlocks = new ArrayList();
assignments = new ArrayList();
parent = comesFrom;
preParameters = new ArrayList();
parameters = new ArrayList();
portVariables = new ArrayList();
subModules = new ArrayList();
LineNumber = Parser.currentLineNumber;
}
Module(String type, Block comesFrom, String name){
BlockType = type;
BlockName = name;
vars = new ArrayList();
subBlocks = new ArrayList();
assignments = new ArrayList();
parent = comesFrom;
preParameters = new ArrayList();
186

ECE 4899

Final Report: Linting Tool

parameters = new ArrayList();


portVariables = new ArrayList();
subModules = new ArrayList();
LineNumber = Parser.currentLineNumber;
}
void addVariableToModule(Variable newVar){
vars.add(newVar);
//

sortVariables();
}
void addVariableToModulePortList(Variable newVar){
portVariables.add(newVar);
addVariableToModule(newVar);
}
void addModuleInstantiation(ModuleInstantiation subModule){
subModules.add(subModule);
}
public Variable findVariableInModule(String searchName){
for(int i=0; i<vars.size(); i++){
if(vars.get(i).name.equals(searchName)){
if(vars.get(i).getClass()!=TaskCall.class && vars.get(i).getClass()!=FunctionCall.class){
return vars.get(i);
}
}
}
return null;
}
public void removeVariableFromModule(String removeName, ArrayList<Variable> rm){
for(int i=0; i<rm.size(); i++){
187

ECE 4899

Final Report: Linting Tool

if(rm.get(i).name.equals(removeName) || rm.get(i).vectorParentName.equals(removeName)){
rm.remove(i);
i--;
}
}
}
public void updatePortVariableInModule(String varName, String newType, ArrayList<Variable>
newVars){
Variable newVar;
/* If a variable by that name exists in both the overall variable list
* "vars" and in the "portVariables" list, then remove it, and add the
* updated variable.
*/
if(findVariableInModule(varName) != null){
removeVariableFromModule(varName, vars);
vars.addAll(newVars);
}
if(findVariableInModulePortList(varName) != null){
removeVariableFromModule(varName, portVariables);
portVariables.addAll(newVars);
}
}
public void sortModuleVariables(){
int i=0, j=0;
Variable temp;
for(i=0; i<vars.size(); i++){
for(j=0; j<vars.size()-(i+1); j++){
if(vars.get(j).compareVariable(vars.get(j+1)) == 1){
188

ECE 4899

Final Report: Linting Tool


temp = vars.get(j);
vars.set(j, vars.get(j+1));
vars.set(j+1, temp);

}
}
}
}
public Variable findVariableInModulePortList(String searchName){
for(int i=0; i<portVariables.size(); i++){
if(portVariables.get(i).name.equals(searchName)){
return portVariables.get(i);
}
}
for(int i=0; i<portVariables.size(); i++){
if(portVariables.get(i).vectorParentName.equals(searchName)){
return portVariables.get(i);
}
}
return null;
}
public Parameter findParameterInModule(String searchName){
for(int i=0; i<parameters.size(); i++){
if(parameters.get(i).name.equals(searchName)){
return parameters.get(i);
}
}
return null;
}
189

ECE 4899

Final Report: Linting Tool

public static boolean checkVariableName(String name){


char let;
for(int i=0; i<name.length(); i++){
let = name.charAt(i);
if(let<48 || (let>57 && let<65) || (let>90 && let<97 && let!=95) || let>122){
return false;
}
if(i == 0){
if(!( (let>64 && let<91) || (let>96 && let<123) )){
return false;
}
}
}
return true;
}

protected void parseVariableInModuleHead(String temp, Parser parser){


while(!temp.equals(")") && !temp.equals("##END_OF_MODULE_CODE")){
ArrayList<String> varNames = new ArrayList();
ArrayList<String> vecTypes = new ArrayList();
ArrayList<String> vecAttributes = new ArrayList();
String vecTypeTemp=""; String vecAttributeTemp="";
ArrayList<String> vecStart = new ArrayList();
ArrayList<String> vecEnd = new ArrayList();
String vecStartTemp=""; String vecEndTemp="";
String lastSign = "";
for( int i=0; (!(temp.equals("input") && vecAttributeTemp.equals("output") ) &&
!(temp.equals("output")&& vecAttributeTemp.equals("input") )) &&
190

ECE 4899

Final Report: Linting Tool


!temp.equals(")") &&
!temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece() ){

if(temp.equals("$#")){
parser.updateLineNumber();
}else if(temp.equals("input") || temp.equals("output") ){
vecStartTemp=""; vecEndTemp="";
vecAttributeTemp = temp;
}else if(temp.equals("reg") || temp.equals("wire")){
vecTypeTemp = temp;
}else if(temp.equals("signed") || temp.equals("unsigned")){
lastSign = temp;
}else if(temp.equals(",")){
//

vecStart.set(i,vecStartTemp);

//

vecEnd.set(i,vecEndTemp);
vecStartTemp=""; vecEndTemp="";

//

vecStart.add("");

//

vecEnd.add("");
i++;
}else if(temp.equals("[")){

for(
temp=parser.getNextPiece();
!temp.equals("##END_OF_MODULE_CODE");

!temp.equals(":")

&&

temp=parser.getNextPiece()){ vecStartTemp += temp + " "; }


for(
temp=parser.getNextPiece();
!temp.equals("##END_OF_MODULE_CODE");

!temp.equals("]")

temp=parser.getNextPiece()){ vecEndTemp += temp + " "; }

}else{

191

&&

ECE 4899

Final Report: Linting Tool


if(vecAttributeTemp.equals("") && i>0){
vecAttributes.add(vecAttributes.get(i-1));
}else{
vecAttributes.add(vecAttributeTemp);
}
if(vecStartTemp.equals("") && vecAttributeTemp.equals("") && i>0){
vecStart.add(vecStart.get(i-1) );
vecEnd.add(vecEnd.get(i-1) );
}else{
vecStart.add(vecStartTemp);
vecEnd.add(vecEndTemp);
}
vecTypes.add(vecTypeTemp);
if(!checkVariableName(temp) || parser.pieceIsKeyword(temp)){
parser.addInstanceOfError18UnexpectedToken(temp);
parser.stopParsing();
}
varNames.add(temp);
vecAttributeTemp="";
vecStartTemp=""; vecEndTemp="";

}
}
for(int i=0; i<varNames.size() && !temp.equals("##END_OF_MODULE_CODE"); i++){
ArrayList<Variable> newVars = new ArrayList();
//set up the template
Variable template = findVariableInModulePortList(varNames.get(i));
if(vecTypes.get(i).equals("reg")){
template = new Reg(varNames.get(i), vecAttributes.get(i), lastSign, 0);
192

ECE 4899

Final Report: Linting Tool

}else {
template = new Wire(varNames.get(i), vecAttributes.get(i), lastSign, 0);
}

//parse the vector if necessary


if(vecStart.get(i).equals("")){
newVars.add(template);
}else{
newVars.addAll(Variable.createVariablesFromVector(template,
vecEnd.get(i)));
}
vars.addAll(newVars);
portVariables.addAll(newVars);
}
}
temp=parser.getNextPiece(); //to remove the final ";"
}
protected void parseVariableInModule(String temp, Parser parser){
ArrayList<String> varNames = new ArrayList();
String lastType=""; String lastAttribute="";
String vecStart=""; String vecEnd="";
ArrayList<Integer> arraySize = new ArrayList();
arraySize.add(new Integer(0));
String lastSign = "";
boolean parVector = true;
boolean singleArrayParsed = false;
for( ; !temp.equals(";") && !temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece()){
193

vecStart.get(i),

ECE 4899

Final Report: Linting Tool

if(temp.equals("$#")){
parser.updateLineNumber();
}else if(temp.equals("input") || temp.equals("output") ){
lastAttribute = temp;
}else if(temp.equals("reg") || temp.equals("wire")){
lastType = temp;
}else if(temp.equals("signed") || temp.equals("unsigned")){
lastSign = temp;
}else if(temp.equals(",")){
arraySize.add(new Integer(0));
}else if(temp.equals("[") && parVector){
for(
temp=parser.getNextPiece();
!temp.equals("##END_OF_MODULE_CODE");

!temp.equals(":")

&&

!temp.equals("]")

&&

temp=parser.getNextPiece()){ vecStart += temp + " "; }


for(
temp=parser.getNextPiece();
!temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece()){ vecEnd += temp + " "; }

}else if(temp.equals("[") && !parVector && !singleArrayParsed){


String arrayStartTemp=""; String arrayEndTemp="";
for(
temp=parser.getNextPiece();
!temp.equals("##END_OF_MODULE_CODE");

!temp.equals(":")

&&

temp=parser.getNextPiece()){ arrayStartTemp += temp + " "; }


for(
temp=parser.getNextPiece();
!temp.equals("##END_OF_MODULE_CODE");

!temp.equals("]")

temp=parser.getNextPiece()){ arrayEndTemp += temp + " "; }


arraySize.remove(arraySize.size()-1);
arraySize.add(Variable.parseVariableArraySize(arrayStartTemp, arrayEndTemp));
singleArrayParsed = true;

194

&&

ECE 4899

Final Report: Linting Tool

}else if(temp.equals("[") && !parVector && singleArrayParsed){


String errorText = "Error: Parser error on signal ("+varNames.get(varNames.size()-1)+
"), (Multi-Dimentional Arrays not suppored with this tool)";
parser.addInstanceOfError20ParseError("20a",errorText);
parser.stopParsing();
}else if(temp.equals("=")){
int breakFlag = 0;
boolean inQuote = false;
boolean escapeChar = false;
for(temp=parser.getNextPiece();
!temp.equals("##END_OF_MODULE_CODE");

!temp.equals(";")

temp=parser.getNextPiece()){
if(temp.equals("{")){
breakFlag++;
}
else if(temp.equals("\\")){
escapeChar = true;
}
else if(temp.equals("\"")){
if(escapeChar){
escapeChar = false;
}
else if(inQuote){
inQuote = false;
}
else{
inQuote = true;
}
195

&&

breakFlag!=-1

&&

ECE 4899

Final Report: Linting Tool


}
else if(temp.equals("}")){
breakFlag--;
}
else if(Module.checkVariableName(temp) && !inQuote){
String errorText = "Non-Constant value ( "+temp+" ) in signal initialization";
parser.addInstanceOfError20ParseError("20g", errorText);
parser.stopParsing();
breakFlag=-1;
}
else if(temp.equals(",") && breakFlag==0){
arraySize.add(new Integer(0));
breakFlag = -1;
}

}
parser.backOneStep();
}else{
parVector = false;
if(!checkVariableName(temp)){
parser.addInstanceOfError18UnexpectedToken(temp);
parser.stopParsing();
}
varNames.add(temp);
singleArrayParsed = false;
}
}
for(int i=0; i<varNames.size() && !temp.equals("##END_OF_MODULE_CODE"); i++){
ArrayList<Variable> newVars = new ArrayList();
196

ECE 4899

Final Report: Linting Tool

//set up the template


Variable template = findVariableInModulePortList(varNames.get(i));
if(template != null){
template.name = varNames.get(i);
if(!template.variableType.equals("") && !template.variableType.equals("DEFAULT_NET_TYPE"))
lastType = template.variableType;
if(!template.variableAttribute.equals(""))
lastAttribute = template.variableAttribute;
if(!template.variableSign.equals(""))
lastSign = template.variableSign;
}
if(lastType.equals("reg")){
template = new Reg(varNames.get(i), lastAttribute, lastSign, arraySize.get(i));
}else {
template = new Wire(varNames.get(i), lastAttribute, lastSign, arraySize.get(i));
}

//parse the vector if necessary


if(vecStart.equals("")){
newVars.add(template);
}else{
newVars.addAll(Variable.createVariablesFromVector(template, vecStart, vecEnd));
}

//take the newVars list and either update the existing variable, or add the new variables to the list
if( findVariableInModulePortList(varNames.get(i)) != null ){
updatePortVariableInModule(template.name, lastType, newVars);
}else{
197

ECE 4899

Final Report: Linting Tool

vars.addAll(newVars);
}

public static String parseModule(Block current, Parser parser){


String temp = parser.getNextPiece(); //should be equal to the module head name
String lastType="DEFAULT_NET_TYPE";
String lastAttribute = "";
Module module = new Module("module",current, temp);
createParameterList(module,parser);
//

module = parseModuleHead(module,parser);
temp = parser.getNextPiece(); //should be a "("
if(temp.equals("(")){
temp = parser.getNextPiece(); //should be a the first intereting piece of the port lists
module.parseVariableInModuleHead(temp, parser);
}
current.addSubBlock(module);
Variable tempVar;
int piecePlaceholder=0; //used for checking vector names
do{
temp = parser.getNextPiece();
if(temp.equals("input") || temp.equals("output") || temp.equals("reg") || temp.equals("wire")){
module.parseVariableInModule(temp, parser);
}
else if(temp.equals("integer")){
198

ECE 4899

Final Report: Linting Tool

ArrayList<String> integerPieces = new ArrayList();


for(temp=parser.getNextPiece();
!temp.equals(";")
!temp.equals("##END_OF_MODULE_CODE"); temp=parser.getNextPiece()){

&&

integerPieces.add(temp);
}
module.addVariableToModule(new IntegerVariable(integerPieces));
}
//This effectively skips over the parameters, which have already been parsed
else if(temp.equals("parameter") || temp.equals("localparam")){
for(;
!temp.equals(";")
parser.getNextPiece());

&&

!temp.equals("##END_OF_MODULE_CODE");

temp

}
else if(temp.equals("assign")){
for(module.statementText="", temp="";
!temp.equals(";")
parser.getNextPiece()){

&&

!temp.equals("##END_OF_MODULE_CODE");

temp

module.statementText += temp+" ";


}
module.assignments.add(new ContinuousAssignment(module.statementText,module, parser));
}
else if(!parser.pieceIsKeyword(temp) && (module.findVariableInModule(temp)==null)
&& parser.checkTaskOrFunctionName(temp)==0 && Module.checkVariableName(temp)) {
String temp2 = parser.getNextPiece(); //if this is a submodule then this will be the instantiation
name
if(Module.checkVariableName(temp2)){
ArrayList<String> subModule = new ArrayList();
String subModuleText="";
int line = Parser.currentLineNumber;

199

ECE 4899

Final Report: Linting Tool


subModule.add(temp); subModuleText+=temp;
for(subModule.add(temp2), subModuleText+=" "+temp2; !temp.equals(";") &&
!temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece()){
if(temp.equals("$#")){
parser.updateLineNumber();
}else{
subModuleText+=" "+temp;
subModule.add(temp);
}
}
module.addModuleInstantiation(new

ModuleInstantiation(subModuleText,

line));
}else{
parser.addInstanceOfError8UndeclaredSignal(temp);
parser.stopParsing();
}
}
//check for a task call, and ignore it if its present
else if(parser.checkTaskOrFunctionName(temp)!=0){
int type = parser.checkTaskOrFunctionName(temp);
String CallText = "";
ArrayList<String> CallElements = new ArrayList();
for(; !temp.equals(";") &&
!temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece()){
CallText += temp+" ";
CallElements.add(temp);
200

subModule,

ECE 4899

Final Report: Linting Tool

}
if(type == 1){
module.addVariable(new TaskCall(CallText,CallElements));
}else if(type == 2){
module.addVariable(new FunctionCall(CallText,CallElements));
}
}
else if(!temp.equals("##END_OF_MODULE_CODE") ){
/* If the string temp is a keyword then once it is back in the
* it is checked to see if it is part of a block, and if so
* then it is passed back to the parser to be handled
* to another block type
*/
if(parser.pieceIsKeyword(temp))
parser.checkForNewBlock(module, temp);
else{
parser.addInstanceOfError18UnexpectedToken(temp);
parser.stopParsing();
}
}
}while( !temp.equals("endmodule") && !temp.equals("##END_OF_MODULE_CODE"));
return temp;
}
private static Module parseModuleHead(Module current, Parser parser){
Module module = current;
String piece = parser.getNextPiece();
String lastType="DEFAULT_NET_TYPE";
String lastAttribute = "";
201

ECE 4899

Final Report: Linting Tool

do{
piece = parser.getNextPiece();
if(piece.equals("$#")){
parser.checkForNewBlock(current, piece);
}
else if(piece.equals("input")){
lastAttribute = "input";
lastType = "DEFAULT_NET_TYPE";
piece = parser.getNextPiece();
if(piece.equals("reg")){
lastType = "ERROR";
piece = parser.getNextPiece();
module.addVariableToModulePortList(new Reg(piece,"input"));
}else if(piece.equals("wire")){
lastType = "wire";
piece = parser.getNextPiece();
module.addVariableToModulePortList(new Wire(piece,"input"));
}
else{
module.addVariableToModulePortList(new Variable(piece,lastType,"input"));
}
}
else if(piece.equals("output")){
lastAttribute = "output";
lastType = "DEFAULT_NET_TYPE";
piece = parser.getNextPiece();
if(piece.equals("reg")){
lastType = "reg";
202

ECE 4899

Final Report: Linting Tool


piece = parser.getNextPiece();
module.addVariableToModulePortList(new Reg(piece,"output"));

}else if(piece.equals("wire")){
lastType = "wire";
piece = parser.getNextPiece();
module.addVariableToModulePortList(new Wire(piece,"output"));
}
else {
module.addVariableToModulePortList(new Variable(piece,lastType,"input"));
}
}
else if(piece.equals("reg")){
lastType = "ERROR";
piece = parser.getNextPiece();
module.addVariableToModulePortList(new Variable(piece,lastType,lastAttribute));
}
else if(piece.equals("wire")){
lastType = "wire";
piece = parser.getNextPiece();
module.addVariableToModulePortList(new Wire(piece,lastAttribute));
}
else if(!piece.equals(")")){
module.addVariableToModulePortList(new Variable(piece,lastType,lastAttribute));
}
}while(!piece.equals(")") && !piece.equals("##END_OF_MODULE_CODE"));
piece = parser.getNextPiece(); //used to remove the final semicolon from the parse string
return module;
}
203

ECE 4899

Final Report: Linting Tool

private static void createParameterList(Module current, Parser parser){


Parameter param;
int currentPieceIndex = parser.getFreshPieceIndex();
int currentParameterIndex = currentPieceIndex;
String paramType="";
String paramName="";
String paramAssignmentValue="";
String temp=parser.getNextPiece();
for(;
!temp.equals("endmodule")
temp=parser.getNextPiece()){

&&

!temp.equals("##END_OF_MODULE_CODE");

if(temp.equals("$#")){
parser.updateLineNumber();
}
else if(temp.equals("parameter") || temp.equals("localparam") ){
paramType = temp;
temp = parser.getNextPiece();
if(temp.equals("[")){
for(;
!temp.equals("]")
temp=parser.getNextPiece());

&&

!temp.equals("##END_OF_MODULE_CODE");

temp=parser.getNextPiece(); //this last piece retrieval should be the parameter name


}
if(!checkVariableName(temp)){
parser.addInstanceOfError18UnexpectedToken(temp);
parser.stopParsing();
}
paramName = temp;
temp = parser.getNextPiece();
if(!temp.equals(";")){

204

ECE 4899

Final Report: Linting Tool


temp = parser.getNextPiece();

}
for(paramAssignmentValue="";
!temp.equals(";")
temp=parser.getNextPiece() ){

&&

!temp.equals("##END_OF_MODULE_CODE");

paramAssignmentValue += temp+" ";


}
param = new Parameter(paramName,paramType,paramAssignmentValue);
current.vars.add(param);
current.parameters.add(param);
//*
currentParameterIndex = parser.getFreshPieceIndex();
//This loop replaces all instances of the current parameter with the parameter's actual value
for(; !temp.equals("##END_OF_MODULE_CODE"); temp=parser.getNextPiece()){
if(temp.equals(paramName))
parser.replaceCurrentPieceText( param.getParameterValue() );
}
parser.setFreshPieceIndex(currentParameterIndex);
//*/
}
}

parser.setLineNumber(1);
parser.setFreshPieceIndex(currentPieceIndex);
}

@Override
public String toString(){
205

ECE 4899

Final Report: Linting Tool

int i=0;

//This section prints out the module Header


String out = "module "+BlockName+" (\n";
if(!portVariables.isEmpty()){
for(i=0; !(portVariables.get(i).getAttribute().equals("input")
|| portVariables.get(i).getAttribute().equals("output"))
&& i<portVariables.size(); i++);
out += portVariables.get(i).toString();
for(i=i+1; i<portVariables.size(); i++){
if(portVariables.get(i).getAttribute().equals("input")
|| portVariables.get(i).getAttribute().equals("output")){
out += "\t,\n";
out += portVariables.get(i).toString();
}
}
}
out+="\n);\n";

//This Section Prints out the Module Body


for(i=0; i<parameters.size(); i++)
out += parameters.get(i).toString();
if(!vars.isEmpty()){
//

for(i=0; (vars.get(i).getAttribute().equals("input")

//

|| vars.get(i).getAttribute().equals("output"))

//

&& i<vars.size(); i++);

//

out += vars.get(i).toString();
for(i=0; i<vars.size(); i++){
206

ECE 4899

Final Report: Linting Tool

if(!vars.get(i).getAttribute().equals("input")
&& !vars.get(i).getAttribute().equals("output")
&& vars.get(i).getClass() != Parameter.class){
out += vars.get(i).toString();
out += ";\n";
}
}
}
out += "\n";
for(i=0; i< subModules.size(); i++){
out += subModules.get(i).toString();
}
out += "\n";
for(i=0; i< subBlocks.size(); i++){
out += subBlocks.get(i).toString();
}
out += "\n";
for(i=0; i<assignments.size(); i++){
out += assignments.get(i).toString();
}
out+="\nendmodule\n";
return out;
}
}

207

ECE 4899

Final Report: Linting Tool

ModuleInstantiation.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestMain;

import java.util.ArrayList;
/**
*
* @author cloud9
*/

public class ModuleInstantiation extends Variable{


private String moduleText;
private ArrayList<Variable> externalPortVariables;
private ArrayList<Variable> internalPortVariables;

ModuleInstantiation(){
name = "";
variableType = "";
moduleText = "";
externalPortVariables = new ArrayList();
internalPortVariables = new ArrayList();
LineNumber = Parser.currentLineNumber;
}
ModuleInstantiation(String moduleTextIn, ArrayList<String> subModule, int line){
name = "";
208

ECE 4899

Final Report: Linting Tool

variableType = "";
moduleText = "";
externalPortVariables = new ArrayList();
internalPortVariables = new ArrayList();
moduleText = moduleTextIn;
LineNumber = line;
parseSubModule(subModule);
}
private void parseSubModule(ArrayList<String> pieces){
}
@Override
public String toString(){
return moduleText+" LINE: "+LineNumber+"\n";
}

209

ECE 4899

Final Report: Linting Tool

New_Error_Template.java
/*
* Template For Sponsor To Write New Error Files
*/
package TestMain;

import java.util.ArrayList;

public class New_Error_Template {


public static ArrayList<Error> getErrors(Parser parser)
{
ArrayList<Error> errorList = new ArrayList();

return errorList;
}
}

210

ECE 4899

Final Report: Linting Tool

Parameter.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestMain;

/**
*
* @author cloud9
*/
public class Parameter extends Variable{

private String parameterValue;


private String nonNumericalValue;

Parameter(String name_in, String type, String assignment)


{
name = name_in;
variableType = type;
variableAttribute = assignment;
edgeSensitivity = "";
LineNumber = Parser.currentLineNumber;

determineParameterValue();
}
private void determineParameterValue(){
parameterValue = Parser.parseNumberFromExpression(variableAttribute);
211

ECE 4899

Final Report: Linting Tool

}
public String getParameterValue(){
return parameterValue;
}

@Override
public String toString(){
return variableType + " " + name + " = "+ parameterValue + "; \\\\LINE:"+LineNumber+"\n";
}
}

212

ECE 4899

Final Report: Linting Tool

Parser.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package TestMain;

import java.util.ArrayList;
/**
*
* @author Hell-o
*/
public class Parser {
private Block top;
private ArrayList<Variable> variables; // A complete list of all variables
private ArrayList<Block> Blocks; // A complete list of all Blocks/subBlocks
private String cleanInput;
private ArrayList<String> usedPieces;
private ArrayList<String> freshPieces;
private ArrayList<String> taskOrFunctionNames;
private int freshPieceIndex;
public static int currentLineNumber;

public ArrayList<Error> parserErrorList;

Parser(ArrayList<String> original){
//initializes "Parser" class members
213

ECE 4899

Final Report: Linting Tool

top = new Block("Top",null);


variables = new ArrayList();
usedPieces = new ArrayList();
freshPieces = new ArrayList();
Blocks = new ArrayList();
parserErrorList = new ArrayList();
taskOrFunctionNames = new ArrayList();
freshPieceIndex = -1;
currentLineNumber=0;

//Checks to see if the ArrayList is Empty, and returns an error


if(original.isEmpty()){
System.out.println("Error, the file contians no code\n");
return;
}

cleanInput = removeComments(original);
cleanInput = spaceEvenly(cleanInput);

makePieceList(freshPieces, cleanInput);
removeBlockNames();
checkForTimingControl();
if(!parserErrorList.isEmpty()){
return;
}
getTaskAndFunctionNames();

String bob = getNextPiece();


214

ECE 4899

Final Report: Linting Tool

checkForNewBlock(top,bob); //this gets the first line number,

bob = getNextPiece();
checkForNewBlock(top,bob); // this starts actally parsing the module
System.out.println("\n"+top.toString());

variables.addAll(top.getAllVariables());
System.out.println("\nVariables: "+variables.toString());
Blocks.addAll(top.getAllBlocks());

}
private String removeComments(ArrayList<String> original){
int i=0,numChars=0;
String temp="";
for(i =0; i<original.size(); i++){
temp += " $# " + (i+1) + " ";
temp += original.get(i);
temp += " \n";
}
//

System.out.println("\nBefore:\n");

//

System.out.print(temp);
numChars = temp.length();
char[] clean = temp.toCharArray();
for(i=0; i<numChars; i++){
switch(clean[i]){
case '/':
if(clean[i+1] == '/'){
for(;clean[i]!='\n';i++)
215

ECE 4899

Final Report: Linting Tool


clean[i]=' ';
clean[i] = ' ';
}else if(clean[i+1] == '*'){
for(; !(clean[i]=='*' && clean[i+1]=='/') && i+1<numChars; i++)
clean[i]=' ';
clean[i]=' '; clean[i+1]=' ';
i++;
}
break;

case '\n':
clean[i]=' ';
break;
case '\r':
clean[i]=' ';
break;
case '\t':
clean[i]=' ';
break;
default:
break;
}
}
//

System.out.println("\nAfter:\n");

//

System.out.print(String.copyValueOf(clean));
return String.copyValueOf(clean);
}
private String spaceEvenly(String original){
String spacer = original;
216

ECE 4899

Final Report: Linting Tool

spacer = spaceElement("(",spacer);
spacer = spaceElement(")",spacer);
spacer = spaceElement("[",spacer);
spacer = spaceElement("]",spacer);
spacer = spaceElement("@",spacer);
spacer = spaceElement(",",spacer);
spacer = spaceElement("`",spacer);
spacer = spaceElement(";",spacer);
spacer = spaceElement("*",spacer);
spacer = spaceElement(":",spacer);
spacer = spaceElement("+",spacer);
spacer = spaceElement("-",spacer);
spacer = spaceElement("=",spacer);
spacer = spaceElement("<",spacer);
spacer = spaceElement(">",spacer);
spacer = spaceElement("/",spacer);
spacer = spaceElement("%",spacer);
spacer = spaceElement("!",spacer);
spacer = spaceElement("`",spacer);
spacer = spaceElement("^",spacer);
spacer = spaceElement("|",spacer);
spacer = spaceElement("&",spacer);
spacer = spaceElement("#",spacer);
spacer = spaceElement("{",spacer);
spacer = spaceElement("}",spacer);
spacer = spaceElement("\"",spacer);

//

System.out.println("\nEvenly Spaced\n"+spacer+"\n");
217

ECE 4899

Final Report: Linting Tool

return removeRadixSpaces(spacer);
}
private String removeRadixSpaces(String orig){
String unspaced = "" + orig.charAt(0) + orig.charAt(1);
char rad = ' ';
for(int i = 2; i<orig.length(); i++){
rad = orig.charAt(i-1);
if(orig.charAt(i-2)=='\'' &&
(rad=='b' || rad=='B' || rad=='d' || rad=='D' || rad=='o' || rad=='O' || rad=='h' || rad=='H')
&&
(orig.charAt(i)==' ' || orig.charAt(i)=='\n')){
for(;orig.charAt(i)==' ' || orig.charAt(i)=='\n' || orig.charAt(i)=='$'; i++){
if(orig.charAt(i)=='$'){
for(i+=3; orig.charAt(i)!=' '; i++);
}
}
}
unspaced += orig.charAt(i);
}

//

temp += " $# " + (i+1) + " ";


return unspaced;
}
private String spaceElement(String delim, String original){

//

System.out.println("Looking for "+delim+"\n");


original.indexOf(delim);
String splits = original;
String output = "";
218

ECE 4899

Final Report: Linting Tool

int delimStart = 0; int delimEnd=0;


delimEnd = original.indexOf(delim, delimStart);
while(delimEnd != -1){
if(delim.equals("$")){
if(original.charAt(delimEnd+1)!='#'){
output = output + original.substring(delimStart,delimEnd).trim()
+ " " + delim + " " ;
delimStart = delimEnd+delim.length();
delimEnd = original.indexOf(delim, delimStart);
}
}else{
output = output + original.substring(delimStart,delimEnd).trim()
+ " " + delim + " " ;
delimStart = delimEnd+delim.length();
delimEnd = original.indexOf(delim, delimStart);
}
}
output += original.substring(delimStart, original.length());

return output;
}
public void checkForNewBlock(Block current, String nextWord){
String piece = nextWord;
if( piece.equals("module") ){
Module.parseModule(current,this);
}else if( piece.equals("`")){
parseCompilerDerective(current);
}else if( piece.equals("always")){
219

ECE 4899

Final Report: Linting Tool

Always.parseAlways(current, this);
}else if( piece.equals("if")){
IfElse.parseIf(current, this);
}else if( piece.equals("else")){
IfElse.parseElse(current, this);
}else if( piece.equals("case")){
Case.parseCase(current, this);
}else if( piece.equals("task")){
Task.parseTask(current, this);
}else if( piece.equals("function")){
Function.parseFunction(current, this);
}else if( piece.equals("for")){
ForLoop.parseForLoop(current, this);
}else if( piece.equals("while")){
WhileLoop.parseWhileLoop(current, this);
}else if( piece.equals("$#")){
updateLineNumber();
}
}
public String getNextPiece(){
if(freshPieceIndex+1 < freshPieces.size()){
freshPieceIndex++;
return freshPieces.get(freshPieceIndex);
}
return "##END_OF_MODULE_CODE";
}
public void replaceCurrentPieceText(String newText){
freshPieces.set(freshPieceIndex, newText);
220

ECE 4899

Final Report: Linting Tool

}
public void reFRESHpieces(){
freshPieceIndex = -1;
}
private void removeBlockNames(){
for(int i=1; i<freshPieces.size()-1; i++){
if(freshPieces.get(i-1).equals("$#")){
currentLineNumber = Integer.parseInt( freshPieces.get(i));
}else if(freshPieces.get(i).equals(":") &&
(freshPieces.get(i-1).equals("begin") || freshPieces.get(i-1).equals("end"))){
freshPieces.remove(i+1);
freshPieces.remove(i);
String errorText="Error: Named Block Detected \n\ton line "+currentLineNumber+" (this is not
supported with this tool)";
System.out.println(errorText);
addErrorToParserErrorList(new Error("20f",errorText,currentLineNumber) );
}
}
}
private void checkForTimingControl(){
for(int i=3; i<freshPieces.size()-1; i++){
if(freshPieces.get(i-1).equals("$#")){
currentLineNumber = Integer.parseInt( freshPieces.get(i));
}else if((freshPieces.get(i).equals("posedge") || freshPieces.get(i).equals("negedge"))
&& freshPieces.get(i-1).equals("(")
&& freshPieces.get(i-2).equals("@")
&& !freshPieces.get(i-3).equals("always") ){

221

ECE 4899

Final Report: Linting Tool

addError2UnsynthesizableControlCodeError("@("+freshPieces.get(i)+"
"+freshPieces.get(i+1)+") ");
}else if(isANumber(freshPieces.get(i)) == 1
&& freshPieces.get(i-1).equals("#") ){
addError2UnsynthesizableControlCodeError("#"+freshPieces.get(i));
}else if( freshPieces.get(i).equals("wait")){
addError2UnsynthesizableControlCodeError("wait");
}else if( freshPieces.get(i).equals("while")){
addError2UnsynthesizableControlCodeError("while");
}
}
}
private void addError2UnsynthesizableControlCodeError(String offendingControl){
String errorOutput = "Timing Control, or unsynthesizable Control code "
+ "( "+offendingControl+" ) present in module";
errorOutput += "\ton line : "+currentLineNumber;
addErrorToParserErrorList(new Error("2",errorOutput,currentLineNumber));

}
private static void makePieceList(ArrayList<String> tempFreshPieces, String inputString){
//

while(tempFreshPieces.lastIndexOf("endmodule") == -1){
while( !inputString.equals("") && !inputString.equals(" ")){
String[] piece = inputString.split(" ",2);
if(piece.length != 1)
inputString = piece[1];
while( piece[0].equals("")){
piece = inputString.split(" ",2);
inputString = piece[1];
222

ECE 4899

Final Report: Linting Tool

}
tempFreshPieces.add(piece[0]);
//

System.out.print(piece[0]+" ");
}
remergeLineNumbers(tempFreshPieces);
}
private static void remergeLineNumbers(ArrayList<String> tempFreshPieces){
for(int i=1; i< tempFreshPieces.size(); i++){
if(tempFreshPieces.get(i).equals("#") && tempFreshPieces.get(i-1).equals("$")){
tempFreshPieces.set(i-1, "$#");
tempFreshPieces.remove(i);
i--;
}
}
}
public String getPreviousPiece(int traceBack){
if(freshPieceIndex-traceBack >= 0 && freshPieceIndex-traceBack < freshPieces.size()){
return freshPieces.get(freshPieceIndex - traceBack);
}else{
return "";
}
}
public void parseCompilerDerective(Block current) {
String piece = getNextPiece();
while(!pieceIsKeyword(piece)){

piece = getNextPiece();
}
223

ECE 4899

Final Report: Linting Tool

checkForNewBlock(current, piece);
}
public boolean pieceIsKeyword(String piece){
if( piece.equals("module"))
return true;
else if(piece.equals("`"))
return true;
else if(piece.equals("input"))
return true;
else if(piece.equals("output"))
return true;
else if(piece.equals("parameter"))
return true;
else if(piece.equals("localparam"))
return true;
else if(piece.equals("reg"))
return true;
else if(piece.equals("wire"))
return true;
else if(piece.equals("always"))
return true;
else if(piece.equals("if"))
return true;
else if(piece.equals("else"))
return true;
else if(piece.equals("end"))
return true;
else if(piece.equals("endmodule"))
224

ECE 4899

Final Report: Linting Tool

return true;
else if(piece.equals("case"))
return true;
else if(piece.equals("endcase"))
return true;
else if(piece.equals("default"))
return true;
else if(piece.equals("forever"))
return true;
else if(piece.equals("task"))
return true;
else if(piece.equals("function"))
return true;
else if(piece.equals("while"))
return true;
else if(piece.equals("for"))
return true;
else if(piece.equals("repeat"))
return true;
else if(piece.equals("initial"))
return true;
else if(piece.equals("$#"))
return true;
else{
return false;
}
}
public ArrayList<Variable> getVariableList(){
225

ECE 4899

Final Report: Linting Tool

return variables;
}
public ArrayList<Block> getBlockList(){
return Blocks;
}
public void setFreshPieceIndex(int newIndex){
if(newIndex > -2 && newIndex+1 < freshPieces.size()){
freshPieceIndex = newIndex;
}
}
public int getFreshPieceIndex(){
return freshPieceIndex;
}
public static String parseNumberFromExpression(String expression){
ArrayList<String> pieces = new ArrayList();
makePieceList(pieces,expression);
int num = 0;//Integer.parseInt(expression, 10);
//Integer.parseInt(expression);

for(int i=0; i<pieces.size(); i++){


if(pieces.get(i).equals("+")){
i++;
//This commented line is the one that will ultimately need to be implemented
//num += parseNumberFromExpression(module, String expression);
if( isANumber(pieces.get(i)) == 1 ){
num += Integer.parseInt(resolveNumberToDecimalRadix(pieces.get(i)) , 10);
}
}
226

ECE 4899

Final Report: Linting Tool

else if(pieces.get(i).equals("-") && i+1<pieces.size()){


i++;
//This commented line is the one that will ultimately need to be implemented
//num += parseNumberFromExpression(module, String expression);
if( isANumber(pieces.get(i)) == 1 ){
num -= Integer.parseInt(resolveNumberToDecimalRadix(pieces.get(i)) , 10);
}
}
else { //expand this
if( isANumber(pieces.get(i)) == 1 ){
num += Integer.parseInt(resolveNumberToDecimalRadix(pieces.get(i)) , 10);
}else if( isANumber(pieces.get(i)) == 2){
return resolveNumberToDecimalRadix(pieces.get(i));
}
}
}

return Integer.toString(num);
}
public static int parseNumberForParameter(Module module, String expression){
return 0;
}
public static int isANumber(String inputString){
//returns a 1 if the string is a legal verilog number,
//returns a 2 if the string is a don't care "x" or high impedence "z"
//returns a 0 if the string is neither of the two preveious
String maybe = "";
for(int i=0; i<inputString.length(); i++){
227

ECE 4899

Final Report: Linting Tool

if(inputString.charAt(i) !=' '){


maybe += inputString.charAt(i);
}
}
int quoteLocation = maybe.indexOf("'");
char test;

//if there is no quote ("'") specifing a radix then check to see if


// the number is a decimal value, otherwise it is not a number
if( quoteLocation == -1 ){
for(int i=0; i< maybe.length(); i++){
if( maybe.charAt(i)<48 || (maybe.charAt(i)>57 && maybe.charAt(i)!=95 )){
return 0;
}
}
return 1;
}else if( maybe.lastIndexOf("'") != quoteLocation ){
return 0;
}else{
test = maybe.charAt(quoteLocation+1);
if( test!='b' && test!='B' && test!='o' && test!='O' && test!='h' && test!='H'
&& test!='x' && test!='X' && test!='d' && test!='D'){
return 0;
}
for(int i=quoteLocation+2; i<maybe.length(); i++){
test = maybe.charAt(i);
if( ( test<48 || (test>57 && test<65) || (test>70 && test<97) || test>102) &&
(test!='_' && test!='z' && test!='Z' && test!='x' && test!='X') ){
228

ECE 4899

Final Report: Linting Tool


return 0;

}
}
for(int i=quoteLocation+2; i<maybe.length(); i++){
test = maybe.charAt(i);
if(test=='z' || test=='Z' || test=='x' || test=='X'){
return 2;
}
}
return 1;
}
}
public static String resolveNumberToDecimalRadix(String inputString){
String numText = "";
//This loop clears out the whitespace allowed in the number
for(int i=0; i<inputString.length(); i++){
if(inputString.charAt(i) !=' '){
numText += inputString.charAt(i);
}
}

if( isANumber(numText)==0){
//this probably should never happen!
return "NOT_A_NUMBER";
}else if(isANumber(numText)==2){
return numText;
}else{
int quoteLocation = numText.indexOf("'");
229

ECE 4899

Final Report: Linting Tool

String num = "";

if(quoteLocation == -1){
for(int i=0; i<numText.length(); i++){
if(numText.charAt(i)!='_'){
num += numText.charAt(i);
}
}
return String.valueOf( Integer.parseInt(num, 10));
}
for(int i=quoteLocation+2; i<numText.length(); i++){
num += numText.charAt(i);
}
switch(numText.charAt(quoteLocation+1)){
case('b'): return String.valueOf( Integer.parseInt(num, 2));
case('B'): return String.valueOf( Integer.parseInt(num, 2));
case('o'): return String.valueOf( Integer.parseInt(num, 8));
case('O'): return String.valueOf( Integer.parseInt(num, 8));
case('d'): return String.valueOf( Integer.parseInt(num, 10));
case('D'): return String.valueOf( Integer.parseInt(num, 10));
case('h'): return String.valueOf( Integer.parseInt(num, 16));
case('H'): return String.valueOf( Integer.parseInt(num, 16));
default: return numText;
}
}
}
public void updateLineNumber(){
String number = getNextPiece(); //number should now be equal to the line number
230

ECE 4899

Final Report: Linting Tool

currentLineNumber = Integer.valueOf(number);
}
public void setLineNumber(int num){
currentLineNumber = num;
}
public static int getCurrentLineNumber(){
return currentLineNumber;
}
public void addErrorToParserErrorList(Error e){
parserErrorList.add(e);
}
public ArrayList<Error> getParserErrorList(){
return parserErrorList;
}
public void getTaskAndFunctionNames(){
for(int i=1; i<freshPieces.size(); i++){
if(freshPieces.get(i-1).equals("function")){
taskOrFunctionNames.add("function");
taskOrFunctionNames.add(freshPieces.get(i));
}else if(freshPieces.get(i-1).equals("task")){
taskOrFunctionNames.add("task");
taskOrFunctionNames.add(freshPieces.get(i));
}
}
}
public int checkTaskOrFunctionName(String name){
// 1: indicates "name" is a task
// 2: indicates "name" is a function
231

ECE 4899

Final Report: Linting Tool

// 0: indicates "name" is neither


for(int i=1; i<taskOrFunctionNames.size(); i++){
if(taskOrFunctionNames.get(i).equals(name)){
if(taskOrFunctionNames.get(i-1).equals("task")){
return 1;
}else if(taskOrFunctionNames.get(i-1).equals("function")){
return 2;
}
}
}
return 0;
}
public void addInstanceOfError8UndeclaredSignal(String var){
String errorOutput = "Error: Undeclared sigal: "+var+"\n";
errorOutput += "\ton line : "+currentLineNumber;
System.out.println(errorOutput+"\n");
parserErrorList.add(new Error("8", errorOutput,currentLineNumber));
}
public void addInstanceOfError18UnexpectedToken(String var){
String errorOutput = "Error: Token ("+var+") is either unknown or out of place\n";
errorOutput += "\ton line : "+currentLineNumber;
System.out.println(errorOutput+"\n");
parserErrorList.add(new Error("18", errorOutput,currentLineNumber));
}
public void addInstanceOfError20ParseError(String errorNum, String errorText){
parserErrorList.add(new Error(errorNum,errorText,Parser.getCurrentLineNumber()));
}
public void stopParsing(){
232

ECE 4899

Final Report: Linting Tool

freshPieceIndex = freshPieces.size();
System.out.println("PARSING STOPPED!");
}
public void backOneStep(){
if(freshPieceIndex > 0){
freshPieceIndex--;
}
}

233

ECE 4899

Final Report: Linting Tool

Reg.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package TestMain;

/**
*
* @author Hell-o
*/
public class Reg extends Variable{
// private String edgeSensitivity;
Reg(String name_in)
{
name = name_in;
variableType = "reg";
variableAttribute = "";
edgeSensitivity = "";
vectorParentName = "";
LineNumber = Parser.currentLineNumber;
variableSign = "";
arraySize = 0;
}
Reg(String name_in, String attributeIn)
{
name = name_in;
234

ECE 4899

Final Report: Linting Tool

variableType = "reg";
variableAttribute = attributeIn;
edgeSensitivity = "";
vectorParentName = "";
LineNumber = Parser.currentLineNumber;
variableSign = "";
arraySize = 0;
}
Reg(String name_in, String attributeIn, String vectorParent)
{
name = name_in;
variableType = "reg";
variableAttribute = attributeIn;
edgeSensitivity = "";
vectorParentName = vectorParent;
LineNumber = Parser.currentLineNumber;
variableSign = "";
arraySize = 0;
}
Reg(String name_in, String attributeIn, String vectorParent, String signIn, int arraySizeIn)
{
name = name_in;
variableType = "reg";
variableAttribute = attributeIn;
edgeSensitivity = "";
vectorParentName = vectorParent;
LineNumber = Parser.currentLineNumber;
variableSign = signIn;
235

ECE 4899

Final Report: Linting Tool

arraySize = arraySizeIn;
}
Reg(String name_in, String attributeIn, String signIn, int arraySizeIn)
{
name = name_in;
variableType = "reg";
variableAttribute = attributeIn;
edgeSensitivity = "";
vectorParentName = "";
LineNumber = Parser.currentLineNumber;
variableSign = signIn;
arraySize = arraySizeIn;
}
//

public String getEdgeSensitivity(){

//

return edgeSensitivity;

//

//

public boolean setEdgeSensitivity(String sensitive){

//

if(!edgeSensitivity.equals("")){

//

return false;

//

}else if(sensitive.equals("posedge") || sensitive.equals("negedge")){

//

edgeSensitivity = sensitive;

//

return true;

//

//

return false;

//

@Override
public String toString(){
236

ECE 4899

Final Report: Linting Tool

return variableAttribute + " " + variableType + " " + variableSign + " " +
name + "; Array Size: " + arraySize + " LINE: " + LineNumber;
}
}

237

ECE 4899

Final Report: Linting Tool

SimpleFileStore.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package TestMain;
import java.util.ArrayList;
/**
*
* @author Deathwarror
*/
public class SimpleFileStore {
private String Name;
private ArrayList<String> Code;
private ArrayList<Error> ErrorList;
SimpleFileStore()
{
Name = "";
Code = new ArrayList();
ErrorList = new ArrayList();

}
public void setName(String name)
{
Name = name;
}
238

ECE 4899

Final Report: Linting Tool

public String getName()


{
return Name;
}
public void setCode(ArrayList<String> code)
{
Code = code;
}
public ArrayList<String> getCode()
{
return Code;
}
public ArrayList<Error> getErrorList()
{
return ErrorList;
}
public void setErrorList(ArrayList<Error> el)
{
ErrorList = el;
}
public String toString()
{
return Name;
}

239

ECE 4899

Final Report: Linting Tool

SubCase.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package TestMain;

import java.util.ArrayList;
/**
*
* @author Hell-o
*/
public class SubCase extends Block{
private ConditionStatement condition;
/*"caseBlockOrder" preserves the structureal order of statements and
* subBlocks in and always block.
* 0 - indicates an assignment statement,
* 1- indicates the presence of another subBlock
*/
private ArrayList<Integer> subCaseBlockOrder;

SubCase(Block comesFrom, String name){


BlockType = "";
BlockName = name;
vars = new ArrayList();
subBlocks = new ArrayList();
assignments = new ArrayList();
240

ECE 4899

Final Report: Linting Tool

subCaseBlockOrder = new ArrayList();

parent = comesFrom;
LineNumber = Parser.currentLineNumber;
}

public static String parseSubCase(Block current, Parser parser, String firstTemp){


SubCase sub = new SubCase(current,"");
current.addSubBlock(sub);
String temp = firstTemp;
String statementText = "";
int subCaseConditionStatementBreak=0;
//

temp = parser.getNextPiece(); // temp should get a "(" back


//This loop parses the condition statement at the beginning of the case block
for(subCaseConditionStatementBreak=0,

statementText="";
subCaseConditionStatementBreak!=-1
!temp.equals("##END_OF_MODULE_CODE"); ){
if(temp.equals("$#")){
parser.updateLineNumber();
temp = parser.getNextPiece();
}else if(temp.equals(":")){
if(subCaseConditionStatementBreak == 0){
subCaseConditionStatementBreak = -1;
}else {
statementText += temp+ " ";
temp = parser.getNextPiece();
}
}else if(temp.equals("[")){
241

&&

ECE 4899

Final Report: Linting Tool

subCaseConditionStatementBreak++;
statementText += temp+ " ";
temp = parser.getNextPiece();
}else if(temp.equals("]")){
subCaseConditionStatementBreak--;
statementText += temp+ " ";
temp = parser.getNextPiece();
}else {
statementText += temp+ " ";
temp = parser.getNextPiece();
}
}
sub.condition = new ConditionStatement(statementText, sub, parser);

temp = parser.getNextPiece();
// if there will be multiple sublocks or assginments
if(temp.equals("begin")){
for(temp=parser.getNextPiece();
!temp.equals("end")
!temp.equals("##END_OF_MODULE_CODE"); temp=parser.getNextPiece() ){
if(parser.pieceIsKeyword(temp)){
if(!temp.equals("always")){
parser.checkForNewBlock(sub, temp);
if(!temp.equals("$#"))
sub.subCaseBlockOrder.add(new Integer(1));
}
else{
String errorText = "Error: nested always blocks not allowed";

242

&&

ECE 4899

Final Report: Linting Tool

parser.addErrorToParserErrorList(new
Error("19",errorText,Parser.getCurrentLineNumber()));
parser.stopParsing();
}
}
else if(parser.checkTaskOrFunctionName(temp)!=0){
String taskCallText = "";
ArrayList<String> taskCallElements = new ArrayList();
for(; !temp.equals(";") &&
!temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece()){
taskCallText += temp+" ";
taskCallElements.add(temp);
}
sub.addVariable(new TaskCall(taskCallText,taskCallElements));
sub.subCaseBlockOrder.add(new Integer(2));
}
else if( sub.findVariableInParentBlockHierarchy(temp) !=null ||
!sub.findVectorNameInParentBlockHierarchy(temp).isEmpty()){
for(statementText=""; !temp.equals(";") && !temp.equals("##END_OF_MODULE_CODE");
temp = parser.getNextPiece()){
statementText+=temp+" ";
}
sub.addAssignment(new AssignmentStatement(statementText,sub,parser));
sub.subCaseBlockOrder.add(new Integer(0));
}
else {
parser.addInstanceOfError8UndeclaredSignal(temp);

243

ECE 4899

Final Report: Linting Tool


parser.stopParsing();

}
}
}else {
if(temp.equals("$#")){
parser.checkForNewBlock(sub, temp);
temp = parser.getNextPiece();
}
if(parser.pieceIsKeyword(temp)){
if(!temp.equals("always")){
parser.checkForNewBlock(sub, temp);
if(!temp.equals("$#"))
sub.subCaseBlockOrder.add(new Integer(1));
}
else{
String errorText = "Error: nested always blocks not allowed";
parser.addErrorToParserErrorList(new Error("19",errorText,Parser.getCurrentLineNumber()));
parser.stopParsing();
}
}
else if(parser.checkTaskOrFunctionName(temp)!=0){
String taskCallText = "";
ArrayList<String> taskCallElements = new ArrayList();
for(; !temp.equals(";") &&
!temp.equals("##END_OF_MODULE_CODE");
temp=parser.getNextPiece()){
taskCallText += temp+" ";
taskCallElements.add(temp);
244

ECE 4899

Final Report: Linting Tool

}
sub.addVariable(new TaskCall(taskCallText,taskCallElements));
sub.subCaseBlockOrder.add(new Integer(2));
}
else if( sub.findVariableInParentBlockHierarchy(temp)!=null ||
!sub.findVectorNameInParentBlockHierarchy(temp).isEmpty()){
for(statementText=""; !temp.equals(";") && !temp.equals("##END_OF_MODULE_CODE"); temp
= parser.getNextPiece()){
statementText+=temp+" ";
}
sub.addAssignment(new AssignmentStatement(statementText,sub,parser));
sub.subCaseBlockOrder.add(new Integer(0));
}
else {
parser.addInstanceOfError8UndeclaredSignal(temp);
parser.stopParsing();
}
}

return temp;
}
@Override
public String toString(){
String temp="";
int i=0; int subBlockCount=0; int assignmentStatementCount=0; int varsCount=0;
temp += condition.toString()+": begin \\\\LINE: "+LineNumber+
", Vars in Condition: "+condition.conditionVars.toString()+"\n";

245

ECE 4899

Final Report: Linting Tool

for(i=0, subBlockCount=0, assignmentStatementCount=0, varsCount=0;


i< this.subCaseBlockOrder.size(); i++){
if(subCaseBlockOrder.get(i) == 1){
temp += this.subBlocks.get(subBlockCount).toString();
subBlockCount++;
}else if(!assignments.isEmpty()){
temp += this.assignments.get(assignmentStatementCount);
assignmentStatementCount++;
}else if(!vars.isEmpty()){
temp += this.vars.get(varsCount);
varsCount++;
}
}

temp += "end\n";
return temp;
}
}

246

ECE 4899

Final Report: Linting Tool

Task.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestMain;

import java.util.ArrayList;
/**
*
* @author cloud9
*/
public class Task extends Block{
private ArrayList<String> taskText;

Task(String type, Block comesFrom, String name){


BlockType = type;
BlockName = name;
vars = new ArrayList();
subBlocks = new ArrayList();
assignments = new ArrayList();
parent = comesFrom;
taskText = new ArrayList();
LineNumber = Parser.currentLineNumber;
}

public static void parseTask(Block current, Parser parser){


String temp = parser.getNextPiece(); //should be equal to the task name
247

ECE 4899

Final Report: Linting Tool

String lastType="DEFAULT_NET_TYPE";
String lastAttribute = "";
Task task = new Task("task",current, temp);
current.addSubBlock(task);

for(;
!temp.equals("endtask")
temp=parser.getNextPiece()){

&&

task.taskText.add(temp);
}
}

@Override
public String toString(){
String exit="task ";
for(int i=0; i<taskText.size(); i++){
exit += taskText.get(i) + " ";
if(taskText.get(i).equals("begin")
|| taskText.get(i).equals("end")
|| taskText.get(i).equals(";") ){
exit += "\n";
}
}
return exit+"endtask\n";
}
}

248

!temp.equals("##END_OF_MODULE_CODE");

ECE 4899

Final Report: Linting Tool

TaskCall.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestMain;

import java.util.ArrayList;
/**
*
* @author cloud9
*/
public class TaskCall extends Variable{
String taskCallText;
ArrayList<String> taskCallElements;
ArrayList<Variable> parameterVars;

TaskCall(){
taskCallText = "";
taskCallElements = new ArrayList();
parameterVars = new ArrayList();
LineNumber = Parser.currentLineNumber;
}
TaskCall(String text, ArrayList<String> elements){
taskCallText = text;
taskCallElements = elements;
parameterVars = new ArrayList();
LineNumber = Parser.currentLineNumber;
249

ECE 4899

Final Report: Linting Tool

@Override
public String toString(){
return taskCallText +"; //Task Call LINE: "+LineNumber+"\n";
}
}

250

ECE 4899

Final Report: Linting Tool

TestError.java
package TestMain;

import java.util.Scanner;
import java.util.ArrayList;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Deathwarror
*/
public class TestError {

private Error e,e2;


private Scanner sc;

TestError()
{
sc = new Scanner(System.in);
e = new Error();
}
public Error Default()
{
251

ECE 4899

Final Report: Linting Tool

String en = "10";
String em = "Error Msg";
ArrayList<String> ed = new ArrayList();
ed.add("Module");
ed.add("endModule");
return new Error(en,em);
}
public void start()
{
System.out.println("Error Tester:\n");
for(int i = 0;i>-1;)
{
System.out.println("-1\t quit\n"
+ "1\tBuild Error\n"
+ "2\tSet Error Number\n"
+ "3\tSet Error Message\n"
+ "4\tDuplicate Error\n"
+ "5\tCompare Errors\n"
+ "6\tPrint Primary Stored Error\n");
i = sc.nextInt();
switch(i){
case 1:
buildError();
break;
case 2:
setEN();
break;
case 3:
252

ECE 4899

Final Report: Linting Tool

setEM();
break;
case 4:
dupE();
break;
case 5:
compareE();
break;
case 6:
PrintError();
break;
default:
break;
}
}
}
public void buildError()
{
String en="";
String em="";
String read="";
ArrayList<String> ed = new ArrayList();
System.out.println("Enter Error Number");
while(en.equals(""))
{
en = sc.nextLine();
}

253

ECE 4899

Final Report: Linting Tool

System.out.println("Enter Error Message");


while(em.equals(""))
{
em = sc.nextLine();
}
for(int i = 0;i>-1; i = sc.nextInt())
{
read = "";
System.out.println("Enter definition line");
while(read.equals(""))
{
read = sc.nextLine();
}
ed.add(read);
System.out.println("-1\t quit\n"
+ "1\tContinue\n");
}
e = new Error(en,em);
}
private void setEN()
{
System.out.println("Enter Error Number");
String Read="";
while(Read.equals(""))
{
Read = sc.nextLine();
}
e.setErrorNum(Read);
254

ECE 4899

Final Report: Linting Tool

System.out.println("Error Number Set to "+e.getErrorNum());


}
private void setEM()
{

System.out.println("Enter Error Message");


String Read="";
while(Read.equals(""))
{
Read = sc.nextLine();
}
e.setErrorMsg(Read);
System.out.println("Error Message Set to \n\t"+e.getErrorMsg());
}
private void dupE()
{
e2 = new Error(e.getErrorNum(),e.getErrorMsg());
System.out.println("Error Duplicated\n\n");
System.out.println("New Error:\n");
e2.toString();
}
public void compareE()
{
System.out.println("Error Compare = "+e.compareTo(e2));
}
public void PrintError()
{
e.toString();
255

ECE 4899

Final Report: Linting Tool

public Error getError()


{
return e;
}
}

256

ECE 4899

Final Report: Linting Tool

TestMain.java
/**
* @Author: Kenneth Hassey
* @Date:1/7/2013
* @Version: 1.000
* Function:
*

This file will be responsible for calling and running all functions and

to open, parse files, load database, test rules, and check comments.

*
*

Coders Note: This file will be the one to replace with the GUI Later on.

.toString() function will need to be re written for all

class functions.

*/
package TestMain;

//general import and export that are commonly used.


import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;

//used for the gui components


import javax.swing.*;
import java.awt.*;

257

ECE 4899

Final Report: Linting Tool

public class TestMain {


public static void main(String[] args) {
TestMenu lt = new TestMenu();
}
}
class TestMenu
{
Scanner sc;

TestMenu()
{
sc = new Scanner(System.in);

Parser parserTest;
ArrayList<String> stringArray;// = new ArrayList();

FileRead fileReaderTest = new FileRead();


fileReaderTest.newFile();
//

stringArray.add( fileReaderTest.toString() );
stringArray = fileReaderTest.getCode();
parserTest = new Parser(stringArray);

ErrorSearcher error = new ErrorSearcher();


error.Start(parserTest);
//

error.identifyMultiplyDrivenSignals(parserTest);

258

ECE 4899
//

Final Report: Linting Tool

start();
}
private void start()
{
for(int select = 0;select > -1;)
{
System.out.println("-1\t quit\n"
+ "1\tRun Class Tester");
select = sc.nextInt();
//System.out.println(select);
if(select == 1)
{
ClassTestMenu();
}
}
}
private void ClassTestMenu()
{
TestVariable V = new TestVariable();
TestError E = new TestError();
for(int i = 0; i > -1;)
{
System.out.println("-1\t quit \n"
+ "1\tError Class Tester\n"
+ "2\tVariable Class Tester\n");
i = sc.nextInt();
switch(i)
{
259

ECE 4899

Final Report: Linting Tool


case 1:
E.start();
break;
case 2:
V.start();
break;
default:
break;

}
}

}
}

260

ECE 4899

Final Report: Linting Tool

TestVariable.java
package TestMain;

import java.util.ArrayList;
import java.util.Scanner;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Deathwarror
*/
public class TestVariable {
private Scanner sc;
private Variable v, v2;
TestVariable()
{
sc = new Scanner(System.in);
v = new Variable();
v2 = new Variable();
}
public void start()
{
System.out.println("Error Tester:\n");
for(int i = 0;i>-1;)
261

ECE 4899

Final Report: Linting Tool

{
System.out.println("-1\t quit\n"
+ "1\tBuild Variable\n"
+ "2\tSet Variable Name\n"
+ "3\tSet Variable Type\n"
+ "4\tSet Variable Edges to pos\n"
+ "5\tDuplicate Variable\n"
+ "6\tCompare Variable \n"
+ "7\tCompare Variable all fields\n"
+ "8\tAdd Edge Neg Sens to Variable\n"
+ "9\tPrint Primary Stored Error\n");
i = sc.nextInt();
switch(i){
case 1:
buildVariable();
break;
case 2:
setVN();
break;
case 3:
setVT();
break;
case 4:
setEdge();
break;
case 5:
dupV();
break;
262

ECE 4899

Final Report: Linting Tool

case 6:
compareV();
break;
case 7:
compareVAll();
break;
case 8:
addNegEdge();
break;
case 9:
PrintVar();
break;
default:
break;
}
}
}
public Variable Default()
{
String vn = "Name";
String Vt = "Reg";
ArrayList<String> el = new ArrayList();
el.add("NegEdge");
el.add("PosEdge");
return new Variable(vn,Vt,el);
}
public void buildVariable()
{
263

ECE 4899

Final Report: Linting Tool

String vn="";
String vt="";
String read="";
ArrayList<String> ed = new ArrayList();
System.out.println("Enter Variable Name");
while(vn.equals(""))
{
vn = sc.nextLine();
}
System.out.println("Enter Variable Type");
while(vt.equals(""))
{
vt = sc.nextLine();
}
for(int i = 0;i>-1; i = sc.nextInt())
{
read = "";
System.out.println("Enter Edge Sensitivity");
while(read.equals(""))
{
read = sc.nextLine();
}
ed.add(read);
System.out.println("-1\t quit\n"
+ "1\tContinue\n");
}
v = new Variable(vn,vt,ed);
}
264

ECE 4899

Final Report: Linting Tool

private void setVN()


{
System.out.println("Enter Variable Name");
String Read="";
while(Read.equals(""))
{
Read = sc.nextLine();
}
v.setName(Read);
System.out.println("Variable Name Set to "+v.getName());
}
private void setVT()
{
System.out.println("Enter Variable Type");
String Read="";
while(Read.equals(""))
{
Read = sc.nextLine();
}
v.setType(Read);
System.out.println("Variable Type Set to \n\t"+v.getType());
}
private void setEdge()
{
ArrayList<String> el = new ArrayList();
el.add("PosEdge");
v.setEdge(el);
}
265

ECE 4899

Final Report: Linting Tool

private void dupV()


{
v2 = new Variable(v.getName(),v.getType(),v.getEdge());
System.out.println("Variable Duplicated\n\n");
System.out.println("New Variable:\n");
v2.toString();
}
private void compareV()
{
System.out.println("Variable Compare = "+v.compareTo(v2));
}
private void compareVAll()
{
System.out.println("Variable Compare All: "+v.compareToAll(v2));
}
private void addNegEdge()
{
System.out.println("Add NegEdge: "+ v.addEdge("NegEdge"));
}
private void PrintVar()
{
v.toString();
}
public Variable getVariable()
{
return v;
}
}
266

ECE 4899

Final Report: Linting Tool

Variable.java
package TestMain;

/**
* @Author: Kenneth Hassey
* @Date: 1/7/2013
* @Version 1.000
* Function:
*

This class is designed to store all the variables that come across in

parsing of the code. This file stores Variable's name, variableType, and any

edge sensitivities.

*
*

Status: Untested.

*/
import java.util.ArrayList;

public class Variable {


protected String variableType; //i.e. reg, wire, parameter, localparam
protected String variableAttribute; //i.e. Operational modes: input, output,
protected String variableSign; //i.e. Signed, Unsigned, or Unspecified
protected String vectorParentName;
protected String name;
protected ArrayList<String> EdgeSens;
protected String edgeSensitivity;
protected int LineNumber;
protected int arraySize;

267

ECE 4899

Final Report: Linting Tool

//Default Constructor
Variable()
{
name = "";
variableType = "";
variableAttribute = "";
EdgeSens = new ArrayList();
vectorParentName = "";
variableSign = "";
arraySize = 0;
LineNumber = Parser.currentLineNumber;
}

//This constructor will most likely be used in conjuntion with the addEdge
//function because the variable variableType may edge may not be registered at first
Variable(String name_in, String type_in)
{
name = name_in;
variableType = type_in;
variableAttribute = "";
vectorParentName = "";
variableSign = "";
arraySize = 0;
LineNumber = Parser.currentLineNumber;
}

Variable(String name_in, String type_in, String attributeIn)


{
268

ECE 4899

Final Report: Linting Tool

name = name_in;
variableType = type_in;
variableAttribute = attributeIn;
vectorParentName = "";
variableSign = "";
arraySize = 0;
LineNumber = Parser.currentLineNumber;
}

Variable(String name_in, String type_in, String attributeIn, String sign_in, int arraySizeIn)
{
name = name_in;
variableType = type_in;
variableAttribute = attributeIn;
vectorParentName = "";
variableSign = sign_in;
arraySize = arraySizeIn;
LineNumber = Parser.currentLineNumber;
}

//This constructor can be used to allow all three data slots to be filled.
//Recommended defualt use of
//

Variable(String name_in, String type_in)

//to keep duplicate edges from showing up.


Variable(String name_in,String type_in, ArrayList<String> Edge)
{
name = name_in;
variableType = type_in;
269

ECE 4899

Final Report: Linting Tool

EdgeSens = Edge;
vectorParentName = "";
variableSign = "";
arraySize = 0;
LineNumber = Parser.currentLineNumber;
}

//returns the Name of the Variable


public String getName()
{
return name;
}

public String getVectorName()


{
return vectorParentName;
}

//returns the Type of variable


public String getType()
{
return variableType;
}

public String getAttribute()


{
return variableAttribute;
270

ECE 4899

Final Report: Linting Tool

//returns the Edge Sensitivity


public ArrayList<String> getEdge()
{
return EdgeSens;
}

//Allows the name to be changed.


public void setName(String Name_in)
{
name = Name_in;
}

//Allows the variableType to be changed


public void setType(String Type_in)
{
variableType = Type_in;
}

//Allows a new list of edge sensitivity to be placed


public void setEdge(ArrayList<String> Edge)
{
EdgeSens = Edge;
}

//For adding an edge sensitivity


271

ECE 4899

Final Report: Linting Tool

public boolean addEdge(String edge)


{
for(int i = 0;(i<EdgeSens.size());i++)
{
//get integer value of relation between two strings
int compare = EdgeSens.get(i).compareTo(edge);
//Look for the edge sensitivity is already in the list
if(compare==0)
{
//return false for same
return false;
}
//if it goes in the index of the current edge
else if(compare > 0)
{
EdgeSens.add(i,edge);
return true;
}
else
{
EdgeSens.add(edge);
return true;
}

}
//catch false
return false;
}
272

ECE 4899

Final Report: Linting Tool

//compares two variable objects to see if they are the same


public boolean compareToAll(Variable V)
{
//see if the name matches
if(name.equals(V.getName()))
{
//see if types are the same
if(variableType.equals(V.getType()))
{
int i;
//if the edge sensitivity arent the same Length
if(EdgeSens.size()!= V.getEdge().size())
{
return false;
}

//checks each element of edge sensitivity


for(i = 0;i<EdgeSens.size();i++)
{
if(!(EdgeSens.get(i).equals(V.getEdge().get(i))))
{
return false;
}
}
//if they are the same
if(i== EdgeSens.size())
{
273

ECE 4899

Final Report: Linting Tool


return true;

}
}
}
return false;
}

public int compareVariable(Variable b){


if(this.variableAttribute.equals(b.getAttribute())){
if(this.variableType.equals(b.getType())){
return this.name.compareTo(b.getName());
}else{
return this.variableType.compareTo(b.getType());
}
}else{
return this.variableAttribute.compareTo(b.getAttribute());
}
}

//compares two variable's name and variableType for a lower level compare
public boolean compareTo(Variable V)
{
if(name.equals(V.getName()))
{
if(variableType.equals(V.getType()))
{
return true;
}
274

ECE 4899

Final Report: Linting Tool

}
return false;
}

public String getEdgeSensitivity(){


return edgeSensitivity;
}
public boolean setEdgeSensitivity(String sensitive){
if(!edgeSensitivity.equals("")){
return false;
}else if(sensitive.equals("posedge") || sensitive.equals("negedge")){
edgeSensitivity = sensitive;
return true;
}
return false;
}

//the "params" array list is assumed to come from the module that is currently being worked in
public static ArrayList createVariablesFromVector(Variable template, String vecStart, String vecEnd){
ArrayList<Variable> vectorVars = new ArrayList();

String temp; //parser "freshPiece" string value should currently be set to a "["

String number;
int MSB=0;
int LSB=0;
number = Parser.parseNumberFromExpression(vecStart);
if(Parser.isANumber(number)==1){
275

ECE 4899

Final Report: Linting Tool

MSB = Integer.parseInt(number);
}else{
MSB = 0;
}
number = Parser.parseNumberFromExpression(vecEnd);
if(Parser.isANumber(number)==1){
LSB = Integer.parseInt(number);
}else{
LSB = 0;
}
if(MSB < LSB){
int num = MSB; MSB = LSB; LSB = num;
}

for(int i=0; MSB-i >= LSB; i++){


if(template.getClass() == Reg.class){
vectorVars.add(new
Reg(template.name+"_"+(LSB+i),
template.name, template.variableSign, template.arraySize));

template.variableAttribute,

}else if(template.getClass() == Wire.class){


vectorVars.add(new
Wire(template.name+"_"+(LSB+i),
template.name, template.variableSign, template.arraySize));
}
}

return vectorVars;
}

public static int parseVariableArraySize(String arrayStart, String arrayEnd){

276

template.variableAttribute,

ECE 4899

Final Report: Linting Tool

String number;
int MSB=0;
int LSB=0;
number = Parser.parseNumberFromExpression(arrayStart);
if(Parser.isANumber(number)==1){
MSB = Integer.parseInt(number);
}else{
return -1;
}
number = Parser.parseNumberFromExpression(arrayEnd);
if(Parser.isANumber(number)==1){
LSB = Integer.parseInt(number);
}else{
return -1;
}
if(MSB==0 && LSB==0)
if(MSB < LSB){
int num = MSB; MSB = LSB; LSB = num;
}
return MSB+1-LSB;
}

public static String safelyParseVariableFromLine(Parser parser, Block workingBlock,


String varName,
ArrayList<Variable> varListToAddTo,ArrayList<Variable> arrayIndexVars){
ArrayList<Variable> vars = new ArrayList();
ArrayList<String> pieces = new ArrayList();
int originalIndex = parser.getFreshPieceIndex();
277

ECE 4899

Final Report: Linting Tool

String temp = parser.getNextPiece();


if(workingBlock.findVariableInParentBlockHierarchy(varName) != null){
vars.add(workingBlock.findVariableInParentBlockHierarchy(varName));
}
else if(!workingBlock.findVectorNameInParentBlockHierarchy(varName).isEmpty()){
vars.addAll(workingBlock.findVectorNameInParentBlockHierarchy(varName));
}
else {
parser.addInstanceOfError8UndeclaredSignal(varName);
parser.stopParsing();
}
boolean arrayIndexParsed = false;
int startNum=-1, stopNum=-1, arrayIndex=-1;
for(;temp.equals("[")
temp=parser.getNextPiece()){

&&

!temp.equals("##END_OF_MODULE_CODE");

pieces.add(temp);
if(temp.equals("$#")){
parser.updateLineNumber();
}
//if there is indexing present, and the signal is an array, handle it differently than a vector
else if(vars.get(0).arraySize > 1 && !arrayIndexParsed){
for(arrayIndexParsed=true, temp=parser.getNextPiece();
!temp.equals("]")
temp=parser.getNextPiece()){

&&

!temp.equals("##END_OF_MODULE_CODE");

if(temp.equals("$#")){
parser.updateLineNumber();
}
else {

278

ECE 4899

Final Report: Linting Tool


pieces.add(temp);
if(workingBlock.findVariableInParentBlockHierarchy(temp)!=null
|| !workingBlock.findVectorNameInParentBlockHierarchy(temp).isEmpty()){
temp = Variable.safelyParseVariableFromLine(
parser, workingBlock, temp, arrayIndexVars, arrayIndexVars);
}
else if(Module.checkVariableName(temp) && Parser.isANumber(temp)==0){
parser.addInstanceOfError8UndeclaredSignal(temp);
parser.stopParsing();
}
}

}
arrayIndexParsed = true;
}
//this else parses the vector variables
else {
String expression = "";
for(temp=parser.getNextPiece();
(!temp.equals("]") && !temp.equals(":"))
&& !temp.equals("##END_OF_MODULE_CODE"); temp=parser.getNextPiece()){
if(temp.equals("$#")){
parser.updateLineNumber();
}
else {
pieces.add(temp);
if(Parser.isANumber(temp)==1 || AssignmentStatement.expressionPiece(temp)){
expression += temp+" ";
}
279

ECE 4899

Final Report: Linting Tool


else if(!temp.equals(":") && !temp.equals("]")){
String errorText; String errorNum;
if(!Module.checkVariableName(temp)){
errorText = "Error: illegal token in vector bounds: ("+temp+")";
errorNum = "20b";
}
else{
errorText = "Warning: variable ("+temp+") in vector bounds:\n"
+ "\tThis will very likely not produce the results you intend.";
errorNum = "20c";
}
parser.addInstanceOfError20ParseError(errorNum,errorText);
parser.stopParsing();
}
}

}
startNum = Integer.parseInt(Parser.parseNumberFromExpression(expression));
expression = "";
if(temp.equals(":")){
for(temp=parser.getNextPiece();
!temp.equals("]")
temp=parser.getNextPiece()){

&&

!temp.equals("##END_OF_MODULE_CODE");

if(temp.equals("$#")){
parser.updateLineNumber();
}
else {
pieces.add(temp);
if(Parser.isANumber(temp)==1 || AssignmentStatement.expressionPiece(temp)){
280

ECE 4899

Final Report: Linting Tool


expression += temp+" ";
}
else if(!temp.equals("]")){
String errorText; String errorNum;
if(!Module.checkVariableName(temp)){
errorText = "Error: illegal token in vector bounds: ("+temp+")";
errorNum = "20b";
}
else{
errorText = "Warning: variable ("+temp+") in vector bounds:\n"
+ "\tThis will very likely not produce the results you intend.";
errorNum = "20c";
}
parser.addInstanceOfError20ParseError(errorNum,errorText);
parser.stopParsing();
}
}
}
stopNum = Integer.parseInt(Parser.parseNumberFromExpression(expression));

}
}
pieces.add(temp);
}

if(startNum < stopNum){


int tempNum = startNum; startNum = stopNum; stopNum = tempNum;
}
281

ECE 4899

Final Report: Linting Tool

if(startNum != -1){
Variable tempVar;
if(stopNum == -1){
stopNum = startNum;
}
for(int i=stopNum; i<startNum+1; i++){
tempVar = workingBlock.findVariableInParentBlockHierarchy(varName+"_"+i);
if(tempVar != null){
varListToAddTo.add(tempVar);
}
else {
String errorText = "Error: Parser error, index of ("+varName+") might be out of bounds\n";
parser.addInstanceOfError20ParseError("20d",errorText);
parser.stopParsing();
}
}
}
else if(workingBlock.findVariableInParentBlockHierarchy(varName)==null
&& !workingBlock.findVectorNameInParentBlockHierarchy(varName).isEmpty()){
varListToAddTo.addAll(workingBlock.findVectorNameInParentBlockHierarchy(varName));
}
else if(workingBlock.findVariableInParentBlockHierarchy(varName)!=null
&& workingBlock.findVectorNameInParentBlockHierarchy(varName).isEmpty()){
varListToAddTo.add(workingBlock.findVariableInParentBlockHierarchy(varName));
}
else {
parser.addInstanceOfError20ParseError("20e","Error: unknown parser error\n\tMake sure your
design compiles in modelsim.");
282

ECE 4899

Final Report: Linting Tool

parser.stopParsing();
}

parser.setFreshPieceIndex(parser.getFreshPieceIndex()-1);
return temp;
}
public static String safelyParseVariableForAssignmentStatement(Parser parser, Block workingBlock,
AssignmentStatement statement,
String varName, ArrayList<Variable> varListToAddTo,ArrayList<Variable> arrayIndexVars){
ArrayList<Variable> vars = new ArrayList();
ArrayList<String> pieces = new ArrayList();
String temp = statement.getNextPiece();
if(workingBlock.findVariableInParentBlockHierarchy(varName) != null){
vars.add(workingBlock.findVariableInParentBlockHierarchy(varName));
}
else if(!workingBlock.findVectorNameInParentBlockHierarchy(varName).isEmpty()){
vars.addAll(workingBlock.findVectorNameInParentBlockHierarchy(varName));
}
else {
parser.addInstanceOfError8UndeclaredSignal(varName);
parser.stopParsing();
}
boolean arrayIndexParsed = false;
int startNum=-1, stopNum=-1, arrayIndex=-1;
for(; (temp.equals("[") || temp.equals("$#"))
&& !temp.equals("##END_OF_STATEMENT"); temp=statement.getNextPiece()){
pieces.add(temp);
if(temp.equals("$#")){
283

ECE 4899

Final Report: Linting Tool

temp=statement.getNextPiece();
parser.setLineNumber(Integer.parseInt(temp));
}
//if there is indexing present, and the signal is an array, handle it differently than a vector
else if(vars.get(0).arraySize > 1 && !arrayIndexParsed){
for(arrayIndexParsed=true, temp=statement.getNextPiece();
!temp.equals("]") && !temp.equals("##END_OF_STATEMENT"); ){
if(temp.equals("$#")){
temp=statement.getNextPiece();
parser.setLineNumber(Integer.parseInt(temp));
}
else {
pieces.add(temp);
if(workingBlock.findVariableInParentBlockHierarchy(temp)!=null
|| !workingBlock.findVectorNameInParentBlockHierarchy(temp).isEmpty()){
temp = Variable.safelyParseVariableForAssignmentStatement(
parser, workingBlock, statement, temp, arrayIndexVars, arrayIndexVars);
//

temp = statement.getNextPiece();
}
else if(Module.checkVariableName(temp) && Parser.isANumber(temp)==0){
parser.addInstanceOfError8UndeclaredSignal(temp);
parser.stopParsing();
}
}
if(!temp.equals("$#") && !temp.equals("]")){
temp=statement.getNextPiece();
}
}
284

ECE 4899

Final Report: Linting Tool

arrayIndexParsed = true;
}
//this else parses the vector variables
else {
String expression = "";
for(temp=statement.getNextPiece();
(!temp.equals("]") && !temp.equals(":"))
&& !temp.equals("##END_OF_STATEMENT"); temp=statement.getNextPiece()){
if(temp.equals("$#")){
temp=statement.getNextPiece();
parser.setLineNumber(Integer.parseInt(temp));
}
else {
pieces.add(temp);
if(Parser.isANumber(temp)==1 || AssignmentStatement.expressionPiece(temp)){
expression += temp+" ";
}
else if(!temp.equals(":") && !temp.equals("]")){
String errorText; String errorNum;
if(!Module.checkVariableName(temp)){
errorText = "Error: illegal token in vector bounds: ("+temp+")";
errorNum = "20b";
}
else{
errorText = "Warning: variable ("+temp+") in vector bounds:\n"
+ "\tThis will very likely not produce the results you intend.";
errorNum = "20c";
}
285

ECE 4899

Final Report: Linting Tool


parser.addInstanceOfError20ParseError(errorNum,errorText);
parser.stopParsing();
}
}

}
startNum = Integer.parseInt(Parser.parseNumberFromExpression(expression));
expression = "";
if(temp.equals(":")){
for(temp=statement.getNextPiece();
!temp.equals("]")
temp=statement.getNextPiece()){

&&

!temp.equals("##END_OF_STATEMENT");

if(temp.equals("$#")){
temp=statement.getNextPiece();
parser.setLineNumber(Integer.parseInt(temp));
}
else {
pieces.add(temp);
if(Parser.isANumber(temp)==1 || AssignmentStatement.expressionPiece(temp)){
expression += temp+" ";
}
else if(!temp.equals("]")){
String errorText; String errorNum;
if(!Module.checkVariableName(temp)){
errorText = "Error: illegal token in vector bounds: ("+temp+")";
errorNum = "20b";
}
else{
errorText = "Warning: variable ("+temp+") in vector bounds:\n"
286

ECE 4899

Final Report: Linting Tool


+ "\tThis will very likely not produce the results you intend.";
errorNum = "20c";
}
parser.addInstanceOfError20ParseError(errorNum,errorText);
parser.stopParsing();
}
}
}
stopNum = Integer.parseInt(Parser.parseNumberFromExpression(expression));

}
}
pieces.add(temp);
}

if(startNum < stopNum){


int tempNum = startNum; startNum = stopNum; stopNum = tempNum;
}
if(startNum != -1){
Variable tempVar;
if(stopNum == -1){
stopNum = startNum;
}
for(int i=stopNum; i<startNum+1; i++){
tempVar = workingBlock.findVariableInParentBlockHierarchy(varName+"_"+i);
if(tempVar != null){
varListToAddTo.add(tempVar);
}
287

ECE 4899

Final Report: Linting Tool


else {
String errorText = "Error: Parser error, index of ("+varName+") might be out of bounds\n";
parser.addInstanceOfError20ParseError("20d",errorText);
parser.stopParsing();
}

}
}
else if(workingBlock.findVariableInParentBlockHierarchy(varName)==null
&& !workingBlock.findVectorNameInParentBlockHierarchy(varName).isEmpty()){
varListToAddTo.addAll(workingBlock.findVectorNameInParentBlockHierarchy(varName));
}
else if(workingBlock.findVariableInParentBlockHierarchy(varName)!=null
&& workingBlock.findVectorNameInParentBlockHierarchy(varName).isEmpty()){
varListToAddTo.add(workingBlock.findVariableInParentBlockHierarchy(varName));
}
else {
parser.addInstanceOfError20ParseError("20e","Error: unknown parser error\n\tMake sure your
design compiles in modelsim.");
parser.stopParsing();
}

return temp;
}

//Convert all data in the object to be outputted.


@Override
public String toString()
288

ECE 4899

Final Report: Linting Tool

{
//

System.out.println("Name: "+name + " \t\tType: "+variableType+"\nEdges");

//

for(int i = 0; i <EdgeSens.size();i++)

//

//

System.out.println("\t"+EdgeSens.get(i));

//

return variableAttribute + " " + variableType + " " + name + " Array Size: " + arraySize + " LINE: " +
LineNumber;
}
}

289

ECE 4899

Final Report: Linting Tool

WhileLoop.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestMain;

import java.util.ArrayList;

/**
*
* @author cloud9
*/
public class WhileLoop extends Block{
private ArrayList<String> whileLoopBody;
private ArrayList<String> whileLoopHead;

WhileLoop(String type, Block comesFrom, String name){


BlockType = type;
BlockName = name;
vars = new ArrayList();
subBlocks = new ArrayList();
assignments = new ArrayList();
parent = comesFrom;
whileLoopBody = new ArrayList();
whileLoopHead = new ArrayList();
LineNumber = Parser.currentLineNumber;
}
290

ECE 4899

Final Report: Linting Tool

public static void parseWhileLoop(Block current, Parser parser){


String temp = parser.getNextPiece(); //Should be equal to "("
String lastType="DEFAULT_NET_TYPE";
String lastAttribute = "";
WhileLoop whileLoop = new WhileLoop("whileLoop",current, temp);
current.addSubBlock(whileLoop);
for(;
!temp.equals(")")
temp=parser.getNextPiece()){

&&

!temp.equals("##END_OF_MODULE_CODE");

whileLoop.whileLoopHead.add(temp);
}
whileLoop.whileLoopHead.add(temp);
temp = parser.getNextPiece();
whileLoop.whileLoopBody.add(temp);
if(temp.equals("begin")){
temp = parser.getNextPiece();
for(
int
endCount=0;
(!temp.equals("end")
||
!temp.equals("##END_OF_MODULE_CODE"); temp=parser.getNextPiece()){
whileLoop.whileLoopBody.add(temp);
if(temp.equals("begin")){
endCount++;
}
else if(temp.equals("end")){
endCount--;
}
}
whileLoop.whileLoopBody.add(temp);
}else {

291

endCount!=0)

&&

ECE 4899

Final Report: Linting Tool

temp = parser.getNextPiece();
//if the while loop is not wrapped in begin/end it is assumed the loop contains
// only a single assignment statement, and not sub-blocks, this will need to
// be changed in the future if for loops are going to be legitimately used
for(;
!temp.equals(";")
temp=parser.getNextPiece()){

&&

!temp.equals("##END_OF_MODULE_CODE");

whileLoop.whileLoopBody.add(temp);
}
whileLoop.whileLoopBody.add(";");
}
}

@Override
public String toString(){
ArrayList<String> whileLoopText = whileLoopHead;
whileLoopText.addAll(whileLoopBody);
String exit="while ";
for(int i=0; i<whileLoopText.size(); i++){
exit += whileLoopText.get(i) + " ";
if(whileLoopText.get(i).equals("begin")
|| whileLoopText.get(i).equals("end")
|| whileLoopText.get(i).equals(";") ){
exit += "\n";
}
}
return exit+"\n";
}
}
292

ECE 4899

Final Report: Linting Tool

Wire.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package TestMain;

/**
*
* @author Hell-o
*/
public class Wire extends Variable{
// private String edgeSensitivity;
Wire(String name_in)
{
name = name_in;
variableType = "wire";
variableAttribute = "";
edgeSensitivity = "";
vectorParentName = "";
LineNumber = Parser.currentLineNumber;
variableSign = "";
arraySize = 0;
}
Wire(String name_in, String attributeIn)
{
name = name_in;
293

ECE 4899

Final Report: Linting Tool

variableType = "wire";
variableAttribute = attributeIn;
edgeSensitivity = "";
vectorParentName = "";
LineNumber = Parser.currentLineNumber;
variableSign = "";
arraySize = 0;
}
Wire(String name_in, String attributeIn, String vectorParent)
{
name = name_in;
variableType = "wire";
variableAttribute = attributeIn;
edgeSensitivity = "";
vectorParentName = vectorParent;
LineNumber = Parser.currentLineNumber;
variableSign = "";
arraySize = 0;
}
Wire(String name_in, String attributeIn, String vectorParent, String signIn, int arraySizeIn)
{
name = name_in;
variableType = "wire";
variableAttribute = attributeIn;
edgeSensitivity = "";
vectorParentName = vectorParent;
LineNumber = Parser.currentLineNumber;
variableSign = signIn;
294

ECE 4899

Final Report: Linting Tool

arraySize = arraySizeIn;
}
Wire(String name_in, String attributeIn, String signIn, int arraySizeIn)
{
name = name_in;
variableType = "wire";
variableAttribute = attributeIn;
edgeSensitivity = "";
vectorParentName = "";
LineNumber = Parser.currentLineNumber;
variableSign = signIn;
arraySize = arraySizeIn;
}

//

public String getEdgeSensitivity(){

//

return edgeSensitivity;

//

//

public boolean setEdgeSensitivity(String sensitive){

//

if(!edgeSensitivity.equals("")){

//

return false;

//

}else if(sensitive.equals("posedge") || sensitive.equals("negedge")){

//

edgeSensitivity = sensitive;

//

return true;

//

//

return false;

//

@Override
295

ECE 4899

Final Report: Linting Tool

public String toString(){


return variableAttribute + " " + variableType + " " + variableSign + " " +
name + "; Array Size: " + arraySize + " LINE: " + LineNumber;
}

296

ECE 4899

Final Report: Linting Tool

Version.java
//Class contains a changing current build number
//this one is used for testing
//gets remade in jars to last build date
package TestMain;
public class version {
static String version = "Build Version Here";
}

297

Вам также может понравиться