Skip to content

Instantly share code, notes, and snippets.

@afzafri
Created December 3, 2017 15:57
Show Gist options
  • Save afzafri/afb772e87edfc5647e04dca2184fe087 to your computer and use it in GitHub Desktop.
Save afzafri/afb772e87edfc5647e04dca2184fe087 to your computer and use it in GitHub Desktop.
Recursive Descent Parser for LL(1) Grammar. A mini project for my course, CSC569 Principles of Compiler. This codes are taken from the text book, but we modified the Grammar Rules according to the questions given.
import java.io.* ;
import java.util.* ;
class RDP // Recursive Decent Parser
{
char inp;
public static void main(String[] args) throws IOException
{
System.out.print("Please enter an input string : ");
InputStreamReader stdin = new InputStreamReader(System. in );
RDP rdp = new RDP();
rdp.parse();
}
void parse()
{
inp = getInp();
S(); // Call starting non-terminal, which is S
if (inp == '\r') // end marker, computer read the end marker as "\r"
{
accept(); // if the string reached the end marker without reject, accept the string
}
else
{
reject(); // if not found end marker, reject the string
}
}
// Rule 1 & Rule 2
void S()
{
if (inp == 'b') // if found terminal b
{
inp = getInp(); // get next input
A(); // call non-terminal
}
else if (inp != 'a' | inp != 'b')
{
A();
if (inp == 'b')
{
inp = getInp();
B();
}
else
{
reject();
}
}
else
{
reject(); // if not match, reject the string
}
}
// Rule 3
void A()
{
if (inp == 'a')
{
inp = getInp();
if (inp == 'b')
{
inp = getInp();
}
else
{
reject();
}
}
else
{
reject();
}
}
// Rule 4
void B()
{
if (inp == 'b')
{
inp = getInp();
A();
}
else
{
reject();
}
}
// method for print Accept message
void accept() // Accept the input
{
System.out.println("This input string is accepted by the grammar.");
}
// method for print Reject message
void reject() // Reject the input
{
System.out.println("This input string is rejected by the grammar.");
System.exit(0); // terminate parser
}
// method for reading the input string character
char getInp()
{
try
{
return (char) System.in.read();
}
catch(IOException errormsg)
{
System.out.println("IO error " + errormsg);
}
return '#'; // must return a char
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment