天天看點

LL(1)文法分析求FOLLOW集的Scala代碼(DFS實作)

def FOLLOW( string: ArrayBuffer[ (String, String) ] ): Map[ String, String ] = {
		val localVN = VN
		val FOLLOW_Group = Map[ String, String ]()
		for( ch <- VN ) {
			FOLLOW_Group(ch.toString) = dfsFOLLOW(ch.toString)
		}
		FOLLOW_Group
	}

def dfsFOLLOW( ch: String ): String = {
		val FOLLOWPositions = Map[ String, String ]()
		val FOLLOW_Group = Map[ String, String ]()
		val localLL1_G = LL1_G
		val FIRST_Group = FIRST(localLL1_G)
		val localVN = VN
		for( ch <- localVN ) {
			FOLLOWPositions(ch.toString) = findGivenValueFOLLOWPosition(ch.toString)
			FOLLOW_Group(ch.toString) = "#"
		}
		var result = ""

		if( FOLLOWPositions(ch).length == 4 ) {
			if( FOLLOWPositions(ch)(1).toString == "T" ) {
				result += FIRST_Group( FOLLOWPositions(ch)(0).toString )
				FOLLOW_Group(ch) += result.distinct
			}
			else if( FOLLOWPositions(ch)(3).toString == "T" ) {
				result += FIRST_Group( FOLLOWPositions(ch)(2).toString )
				FOLLOW_Group(ch) += result.distinct
			}
			if( FOLLOWPositions(ch)(1).toString == "W" ) {
				result += dfsFOLLOW( FOLLOWPositions(ch)(0).toString )
				FOLLOW_Group(ch) = result.distinct
			}
			else if( FOLLOWPositions(ch)(3).toString == "W" ) {
				result += dfsFOLLOW( FOLLOWPositions(ch)(2).toString )
				FOLLOW_Group(ch) = result.distinct
			}
		}

		if( FOLLOWPositions(ch).length == 2 ) {
			if( FOLLOWPositions(ch)(1).toString == "T" ) {
				result += FIRST_Group( FOLLOWPositions(ch)(0).toString )
				FOLLOW_Group(ch) = result.distinct
			}
			else if( FOLLOWPositions(ch)(1).toString == "W" ) {
				result += dfsFOLLOW( FOLLOWPositions(ch)(0).toString )
				FOLLOW_Group(ch) = result.distinct
			}
		}
		FOLLOW_Group(ch).replace("ε", "")
	}
           

因為實作了這個dfsFOLLOW函數,我節約了700+行代碼。

繼續閱讀