Update app.py
Browse files123460 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991001011021 unmodified line104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238import streamlit as strules = []nonterm_userdef = []60 unmodified linesreturn newDictdef first(rule):if len(rule) != 0 and rule[0] in term_userdef:return rule[0]elif len(rule) != 0 and rule[0] == '#':return '#'if len(rule) != 0 and rule[0] in diction:fres = []rhs_rules = diction[rule[0]]for itr in rhs_rules:indivRes = first(itr)if type(indivRes) is list:fres.extend(indivRes)else:fres.append(indivRes)if '#' not in fres:return freselse:newList = fresfres.remove('#')if len(rule) > 1:ansNew = first(rule[1:])if ansNew is not None:if type(ansNew) is list:newList = fres + ansNewelse:newList = fres + [ansNew]fres.append('#')return fresdef follow(nt):solset = set()if nt == start_symbol:solset.add('$')for curNT in diction:rhs = diction[curNT]for subrule in rhs:1 unmodified linewhile nt in subrule:index_nt = subrule.index(nt)subrule = subrule[index_nt + 1:]if len(subrule) != 0:res = first(subrule)if res is not None:if '#' in res:res.remove('#')follow_res = follow(curNT)if follow_res:res += follow_reselse:res = []else:if nt != curNT:res = follow(curNT)if res is None:res = []solset.update(res if type(res) is list else [res])return list(solset)def computeAllFirsts():global firstsfor y in diction.keys():firsts[y] = set()for sub in diction[y]:result = first(sub)if result is not None:firsts[y].update(result if type(result) is list else [result])def computeAllFollows():global followsfor NT in diction.keys():follows[NT] = set(follow(NT))def createParseTable():global term_userdef, firsts, followstable = {}grammar_is_LL = Truefor lhs in diction.keys():table[lhs] = {}for term in term_userdef + ['$']:table[lhs][term] = ""for lhs in diction:for rule in diction[lhs]:first_res = first(rule)if '#' in first_res:first_res.remove('#')follow_res = follows[lhs]first_res.update(follow_res)for term in first_res:if table[lhs][term] == "":table[lhs][term] = f"{lhs} -> {' '.join(rule)}"else:grammar_is_LL = Falsereturn table, grammar_is_LLdef validateStringUsingStackBuffer(parse_table, input_string):stack = [start_symbol, '$']buffer = ['$'] + input_string.split()[::-1]while stack:top_stack = stack.pop(0)top_buffer = buffer.pop()if top_stack in term_userdef:if top_stack != top_buffer:return "Invalid String"elif top_stack == top_buffer:continueelse:rule = parse_table.get(top_stack, {}).get(top_buffer, None)if rule:rule_rhs = rule.split('->')[1].strip().split()stack = rule_rhs + stackelse:return "Invalid String"return "Valid String"# Main Streamlit Appst.title("LL(1) Grammar Analyzer")st.subheader("Grammar Rules Input")start_symbol = st.text_input("Enter Start Symbol (Non-terminal)")num_rules = st.number_input("Number of Grammar Rules", min_value=1, step=1)rules = []for i in range(num_rules):rule = st.text_input(f"Rule {i+1}")if rule:rules.append(rule)nonterm_userdef = st.text_input("Enter Non-Terminals (comma-separated)").split(',')term_userdef = st.text_input("Enter Terminals (comma-separated)").split(',')if st.button("Analyze Grammar"):diction.clear()firsts.clear()follows.clear()for rule in rules:lhs, rhs = rule.split("->")lhs = lhs.strip()rhs_list = [x.strip().split() for x in rhs.split("|")]diction[lhs] = rhs_listst.subheader("Grammar After Removing Left Recursion")diction = removeLeftRecursion(diction)st.write(diction)st.subheader("Grammar After Left Factoring")diction = LeftFactoring(diction)st.write(diction)computeAllFirsts()st.subheader("FIRST Sets")st.write(firsts)computeAllFollows()st.subheader("FOLLOW Sets")st.write(follows)parse_table, grammar_is_LL = createParseTable()st.subheader("Parse Table")st.write(parse_table)if grammar_is_LL:st.success("The grammar is LL(1)")else:st.error("The grammar is not LL(1)")input_string = st.text_input("Enter String to Validate (space-separated)")if input_string:result = validateStringUsingStackBuffer(parse_table, input_string)st.subheader("Validation Result")st.write(result)1234560 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011 unmodified line103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277import streamlit as stimport pandas as pdrules = []nonterm_userdef = []60 unmodified linesreturn newDictdef first(rule):global term_userdef, dictionif not rule:return ['#']if rule[0] in term_userdef:return [rule[0]]elif rule[0] == '#':return ['#']if rule[0] in diction:fres = []rhs_rules = diction[rule[0]]for itr in rhs_rules:indivRes = first(itr)if indivRes:fres.extend(indivRes)if '#' in fres and len(rule) > 1:fres.remove('#')ansNew = first(rule[1:])if ansNew:fres.extend(ansNew)return list(set(fres))return []def follow(nt):global start_symbol, dictionsolset = set()if nt == start_symbol:solset.add('$')for curNT in diction:rhs = diction[curNT]for subrule in rhs:1 unmodified linewhile nt in subrule:index_nt = subrule.index(nt)subrule = subrule[index_nt + 1:]if subrule:res = first(subrule)if '#' in res:res.remove('#')if nt != curNT:follow_res = follow(curNT)if follow_res:res.extend(follow_res)solset.update(res)else:if nt != curNT:follow_res = follow(curNT)if follow_res:solset.update(follow_res)return list(solset)def computeAllFirsts():global firsts, dictionfirsts.clear()for y in diction:firsts[y] = set()for sub in diction[y]:result = first(sub)if result:firsts[y].update(result)def computeAllFollows():global follows, dictionfollows.clear()for NT in diction:follows[NT] = set(follow(NT))def createParseTable():global diction, term_userdef, firsts, follows# Initialize parse table with empty stringsparse_table = {}for non_term in diction:parse_table[non_term] = {}for term in term_userdef + ['$']:parse_table[non_term][term] = ""# Fill parse tablegrammar_is_LL = Truefor non_term in diction:for production in diction[non_term]:first_set = first(production)# If epsilon is in FIRST set, add FOLLOW setif '#' in first_set:first_set.remove('#')first_set.extend(follows[non_term])for terminal in first_set:if parse_table[non_term].get(terminal, "") == "":parse_table[non_term][terminal] = f"{non_term} -> {' '.join(production)}"else:grammar_is_LL = Falsereturn parse_table, grammar_is_LLdef validateStringUsingStackBuffer(parse_table, input_string):stack = [start_symbol, '$']buffer = list(input_string.split()) + ['$']while stack and buffer:top_stack = stack[0]current_input = buffer[0]if top_stack == current_input:stack.pop(0)buffer.pop(0)elif top_stack in term_userdef:return "Invalid String: Terminal mismatch"elif parse_table[top_stack][current_input]:production = parse_table[top_stack][current_input].split('->')[1].strip().split()stack.pop(0)if production != ['#']:stack = production + stackelse:return "Invalid String: No production rule found"if not stack and not buffer:return "Valid String"return "Invalid String: Stack or buffer not empty"# Streamlit UIst.title("LL(1) Grammar Analyzer")# Input sectionst.header("Grammar Input")start_symbol = st.text_input("Enter Start Symbol:", "S")with st.expander("Enter Grammar Rules"):num_rules = st.number_input("Number of Rules:", min_value=1, value=3)rules = []for i in range(num_rules):rule = st.text_input(f"Rule {i+1} (format: A -> B c | d)", key=f"rule_{i}")if rule:rules.append(rule)nonterm_input = st.text_input("Enter Non-terminals (comma-separated):", "S,A,B")term_input = st.text_input("Enter Terminals (comma-separated):", "a,b,c")if nonterm_input.strip():nonterm_userdef = [x.strip() for x in nonterm_input.split(',') if x.strip()]if term_input.strip():term_userdef = [x.strip() for x in term_input.split(',') if x.strip()]if st.button("Analyze Grammar"):# Clear previous datadiction.clear()# Process rulesfor rule in rules:if '->' in rule:lhs, rhs = rule.split("->")lhs = lhs.strip()rhs_parts = [x.strip().split() for x in rhs.split("|")]diction[lhs] = rhs_parts# Remove left recursion and perform left factoringst.subheader("Grammar Processing")with st.expander("Show Grammar Transformations"):st.write("After removing left recursion:")diction = removeLeftRecursion(diction)st.write(diction)st.write("After left factoring:")diction = LeftFactoring(diction)st.write(diction)# Compute FIRST and FOLLOW setscomputeAllFirsts()computeAllFollows()with st.expander("Show FIRST and FOLLOW Sets"):st.write("FIRST Sets:", {k: list(v) for k, v in firsts.items()})st.write("FOLLOW Sets:", {k: list(v) for k, v in follows.items()})# Create and display parse tableparse_table, grammar_is_LL = createParseTable()st.subheader("Parse Table")# Convert parse table to pandas DataFrame for better displaydf_data = []terminals = term_userdef + ['$']for non_term in parse_table:row = [non_term] # First column is non-terminalfor term in terminals:row.append(parse_table[non_term].get(term, ""))df_data.append(row)df = pd.DataFrame(df_data, columns=['Non-Terminal'] + terminals)st.dataframe(df)if grammar_is_LL:st.success("This grammar is LL(1)!")else:st.error("This grammar is not LL(1)!")# String validation sectionst.subheader("String Validation")input_string = st.text_input("Enter string to validate (space-separated):", "")if input_string:result = validateStringUsingStackBuffer(parse_table, input_string)if "Valid" in result:st.success(result)else:st.error(result)
app.py+152-113