Update app.py
Browse files137 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931943 unmodified lines19819920020120220320420520620720820921021121242 unmodified lines2552562572582592602616 unmodified lines268269270271272273274275276277137 unmodified linesdef 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")3 unmodified linesstart_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()]42 unmodified linesfor 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)6 unmodified lines# 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)137 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282293 unmodified lines23323423523623723823924024124224324424524624742 unmodified lines2902912922932942952962972982993006 unmodified lines307308309310311312313314315316317318319320321322323137 unmodified linesdef createParseTable():global diction, term_userdef, firsts, followsparse_table = {}for non_term in diction:parse_table[non_term] = {}for term in term_userdef + ['$']:parse_table[non_term][term] = ""grammar_is_LL = Truefor non_term in diction:for production in diction[non_term]:first_set = first(production)if '#' in first_set:first_set.remove('#')follow_set = follows[non_term]first_set.extend(follow_set)for terminal in first_set:if terminal in term_userdef + ['$']:if parse_table[non_term][terminal] == "":parse_table[non_term][terminal] = productionelse:grammar_is_LL = Falsereturn parse_table, grammar_is_LLdef validateStringUsingStackBuffer(parse_table, input_string, start_sym):print("Validating:", input_string) # Debug print# Initialize stack and input bufferstack = [start_sym, '$']input_tokens = input_string.split()input_tokens.append('$')buffer = input_tokensprint("Initial stack:", stack) # Debug printprint("Initial buffer:", buffer) # Debug printparsing_steps = []parsing_steps.append(f"Stack: {stack}, Input: {buffer}")# Processing loopwhile stack and buffer:print(f"\nCurrent stack: {stack}") # Debug printprint(f"Current buffer: {buffer}") # Debug print# Get top of stack and current inputtop_stack = stack[0]current_input = buffer[0]parsing_steps.append(f"Top of stack: {top_stack}, Current input: {current_input}")# Case 1: Match foundif top_stack == current_input:stack.pop(0)buffer.pop(0)parsing_steps.append("Matched and consumed")continue# Case 2: Non-terminal on topif top_stack in parse_table:if current_input in parse_table[top_stack]:production = parse_table[top_stack][current_input]if production:# Pop the non-terminalstack.pop(0)# Push the production in reverse (if it's not epsilon)if production != ['#']:stack = production + stackparsing_steps.append(f"Applied rule: {top_stack} -> {' '.join(production) if production else '#'}")else:return False, f"No production for {top_stack} with input {current_input}", parsing_stepselse:return False, f"Input symbol {current_input} not in parse table for {top_stack}", parsing_stepselse:# If top of stack is not in parse table and doesn't match inputreturn False, f"Unexpected symbol {top_stack} on stack", parsing_stepsprint(f"Updated stack: {stack}") # Debug print# Check if both stack and buffer are empty (except for $)if len(stack) <= 1 and len(buffer) <= 1:return True, "String accepted", parsing_stepselse:return False, "String rejected - incomplete parse", parsing_steps# Streamlit UIst.title("LL(1) Grammar Analyzer")3 unmodified linesstart_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=4)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,C")term_input = st.text_input("Enter Terminals (comma-separated):", "a,b,c,d,k,r,O")if nonterm_input.strip():nonterm_userdef = [x.strip() for x in nonterm_input.split(',') if x.strip()]42 unmodified linesfor non_term in parse_table:row = [non_term] # First column is non-terminalfor term in terminals:production = parse_table[non_term].get(term, "")if production:row.append(' '.join(production))else:row.append("")df_data.append(row)df = pd.DataFrame(df_data, columns=['Non-Terminal'] + terminals)6 unmodified lines# String validation sectionst.subheader("String Validation")input_string = st.text_input("Enter string to validate (space-separated):", "a r k O")if input_string:is_valid, message, steps = validateStringUsingStackBuffer(parse_table, input_string, start_symbol)# Display the resultif is_valid:st.success(message)else:st.error(message)# Display parsing stepsst.subheader("Parsing Steps")for i, step in enumerate(steps):st.text(f"Step {i+1}: {step}")
app.py+77-31