Java implementation eliminates left recursion of grammar

Source: Internet
Author: User

Tag:java    compiler principle     eliminate left recursive    

package com.siwanghu.syntaxanalyzer.bean;public class grammar {private string  left;private string right;private int id;private static int id =  0;public grammar ()  {super (); id = id++;} Public grammar (String left, string right)  {super ();this.left = left; this.right = right;id = id++;} Public string getleft ()  {return left;} Public void setleft (String left)  {this.left = left.replace (" ",  ");} Public string getright ()  {return right;} Public void setright (string right)  {this.right = right.replace (" ",  "" );} Public int getid ()  {return id;} @Overridepublic  string tostring ()  {return  "grammar [left="  + left +   ",  right="  + right +  "]";}}



package com.siwanghu.syntaxanalyzer.algorithm;import java.util.arraylist;import  java.util.linkedlist;import java.util.list;import java.util.listiterator;import  com.siwanghu.syntaxanalyzer.bean.grammar;public class production {private list  Productions = new linkedlist ();        //-Generation Private list  symbols = new arraylist ();         // Initial production non-Terminator private list nonterminatingsymbol = new arraylist ();  //ll (1) Grammar non-Terminator private list terminatingsymbol = new arraylist ();     //ll (1 ) grammar Terminator Public production (list productions)  {super ();this.productions = productions; Symbolproductions ();} Public list getproductions ()  {return productions;} Public list getsymbols ()  {return symbols;} Public list getnonteRminatingsymbol () {return nonterminatingsymbol;} Public list getterminatingsymbol () {return terminatingsymbol;}     public void removeleftrecursion ()  {for  (int i = 0;  i < symbols.size ();  i++)  {for  (int j = 0; j <  i; j++)  {iterativereplacement (Symbols.get (i),  symbols.get (j)); Removeleftrecursion (Symbols.get (i)); No_or_is_terminatingsymbol ();} Private void symbolproductions ()  {if  (Productions.size ()  != 0)  {for  ( Int i = 0; i < productions.size ();  i++)  {if  (! ( (ArrayList)  symbols). Contains (Productions.get (i). GetLeft (). CharAt (0))  {symbols.add (Productions.get ( i). GetLeft (). CharAt (0));}}} Private void no_or_is_terminatingsymbol ()  {for  (int i = 0; i <  productions.size ();  i++)  {if  (! ((ArrayList)  nonterminatingsymbol). Contains (Productions.get (i). GetLeft ())  {nonterminatingsymbol.add ( Productions.get (i). GetLeft ());} if  (Productions.get (i). GetLeft ()  == productions.get (i). GetLeft (). CharAt (0) +  "'")  { Nonterminatingsymbol.add (Productions.get (i). GetLeft ());}} for  (Int i = 0; i < productions.size ();  i++)  {String temp  = productions.get (i). GetRight () temp = temp.replace ("Epsilon",  "#");for  (int  j = 0; j < nonterminatingsymbol.size ();  j++)  {temp =  Temp.replaceall (Nonterminatingsymbol.get (j),  ""); Temp = temp.replaceall ("\\\\|",  ""); Temp = temp.replaceall ("'",  "");char[]  Chars = temp.tochararray ();for  (int k = 0; k < chars.length;  k++)  {if  (chars[k] ==  ' # ')  {if  (!terminatingsymbol.contains ("EPsilon "))  {terminatingsymbol.add (" Epsilon ");}}  else {if  (!terminatingsymbol.contains (string.valueof (chars[k)))  {terminatingsymbol.add ( String.valueof (Chars[k]));}}}} Private void iterativereplacement (character left, character right)  {ListIterator  listiterator = productions.listiterator ();while  (Listiterator.hasnext ())  {String  inRight =  ""; Grammar grammar = listiterator.next ();if  (Grammar.getleft (). Equals (Left.tostring ()))   {boolean isreplacement = false; String[] rights = grammar.getright (). Split ("\\\\|"); for  (int i = 0; i < rights.length; i++)  {if  (Rights[i]. StartsWith (Right.tostring ()))  {isreplacement = true;}} if  (isreplacement)  {listiterator _listiterator = productions.listiterator ();   (_listiterator.hasnext ())  {grammar _grammaR = _listiterator.next ();if  (_grammar.getleft (). Equals (Right.tostring ()))  {string[] _ Rights = _grammar.getright (). Split ("\\\\|"); for  (int i = 0; i < rights.length; i++)  {boolean isCheck  = false;if  (Rights[i].startswith (right.tostring))  {isCheck = true;for  ( int j = 0; j < _rights.length; j++)  {String temp =  rights[i];inright +=  (Temp.replacefirst (right.tostring (),  _rights[j])  +  "|";}} if  (!ischeck)  {inRight +=  (rights[i] +  "|");}}} if  (Inright.length ()  != 0)  {listiterator.remove (); Listiterator.add (New Grammar ( Left.tostring (),  inright.substring (0, inright.length ()  - 1)));}}}} Private void removeleftrecursion (Character left)  {listiterator listiterator =  productions.listiteratoR ();while  (Listiterator.hasnext ())  {grammar grammar = listiterator.next ();if  ( Grammar.getleft (). Equals (Left.tostring ()))  {string[] rights = grammar.getright (). split ("\ \ \\|"); boolean isleftrecursion = false;for  (int i = 0; i <  rights.length; i++)  {if  (Rights[i].startswith (left.tostring))  {isleftrecursion =  true;}} if  (isleftrecursion)  {listiterator.remove (); string oneright =  "", tworight =  "";for  (int i = 0; i  < rights.length; i++)  {if  (!rights[i].startswith (left.tostring))  {oneright  +=  (Rights[i].concat (left.tostring ()  +  "'")  +  "|");}  else {twoRight +=  (Rights[i].replacefirst (left.tostring (),  ""). Concat (Left.tostring ( )  +  "'")  +  "|");}} Listiterator.add (New grammar (left.tostring (),  oneright.substring (0, oneright.length ()  - 1)); Listiterator.add (New Grammar ( Left.tostring ()  +  "'", Tworight.concat ("Epsilon")));}}} @Overridepublic  string tostring ()  {String temp =  "non-Terminator: ";for  (int  i = 0; i < nonterminatingsymbol.size ();  i++)  {temp +=  Nonterminatingsymbol.get (i)  +  " ";} temp+= "   total:" +nonterminatingsymbol.size ();temp +=  "\\n Terminator: ";for  (int i  = 0; i < terminatingsymbol.size ();  i++)  {temp +=  Terminatingsymbol.get (i)  +  "  ";} temp+= "   total:" +terminatingsymbol.size ();temp +=  "\\n Eliminate left recursion grammar: \\n";for  (int i  = 0; i < productions.size ();  i++)  {temp +=  (Productions.get (i )  +  "\\n");} Return temp;}} package com.siwanghu.syntaxanalyzer.test;import java.util.linkedlist;import java.util.list;import  Com.siwanghu.syntaxanalyzer.algorithm.production;import com.siwanghu.syntaxanalyzer.bean.grammar;public  class test {public static void main (String[] args)  { System.out.println ("The productions of g"); Grammar g1 = new grammar ("S",  "Qc|c"); Grammar g2 = new grammar ("Q",  "rb|b"); Grammar g3 = new grammar ("R",  "Sa|a"); List g_productions = new linkedlist (); G_productions.add (G3); G_productions.add (G2); g_ Productions.add (G1); Production g_production = new production (g_productions); G_production.removeleftrecursion () ; System.out.print (g_production); System.out.println ("end g\\n"); System.out.println ("The productions of h"); Grammar h1 = new grammar ("E",  "e+t| T "); Grammar h2 = new grammar ("T",  "t*f| F "); Grammar h3 = new grammar ("F",  "(E) |i"); List h_productions = new linkedlist (); H_productions.add (H1); H_productions.add (H2); H_ Productions.add (H3); Production h_production = new production (h_productions); H_production.removeleftrecursion () ; System.out.print (h_production); System.out.println ("End h");}}


This article is from the "Hu Swang" blog, make sure to keep this source http://siwanghu.blog.51cto.com/10630140/1716493

Java implementation eliminates left recursion of grammar

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.