Update app.py
Browse files164 unmodified lines1651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372384 unmodified lines2432442452462472482492502512522532542552563 unmodified lines2602612622632642652662672686 unmodified lines27527627727827928028128228328428528628728828929029129229329410 unmodified lines305306307308309310311312313314315316317318319320321322323164 unmodified linesreturn 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")# 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=4)rules = []for i in range(num_rules):4 unmodified linesnonterm_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()]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:3 unmodified linesrhs_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)6 unmodified linescomputeAllFirsts()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:production = parse_table[non_term].get(term, "")if production:10 unmodified lineselse: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):", "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}")164 unmodified lines1651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282294 unmodified lines2342352362372382392402412422432442452462473 unmodified lines2512522532542552562572582592606 unmodified lines26726826927027127227327427527627727827928028128228328428528628710 unmodified lines298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376164 unmodified linesreturn parse_table, grammar_is_LLdef validateStringUsingStackBuffer(parse_table, input_string, start_sym):"""Validates a string using the parsing table"""# Initialize stack and input bufferstack = [start_sym, '$']input_tokens = input_string.split()input_tokens.append('$')buffer = input_tokenssteps = []steps.append(("Initial Configuration:", f"Stack: {stack}", f"Input: {buffer}"))while stack and buffer:top_stack = stack[0]current_input = buffer[0]steps.append(("Current Step:", f"Stack Top: {top_stack}", f"Current Input: {current_input}"))if top_stack == current_input:stack.pop(0)buffer.pop(0)steps.append(("Action:", "Matched and consumed terminal", f"Remaining Input: {buffer}"))elif 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 + stacksteps.append(("Production Applied:", f"{top_stack} -> {' '.join(production) if production else '#'}",f"New Stack: {stack}"))else:return False, steps, f"No production for {top_stack} with input {current_input}"else:return False, steps, f"Input symbol {current_input} not in parse table for {top_stack}"else:return False, steps, f"Unexpected symbol {top_stack} on stack"if len(stack) <= 1 and len(buffer) <= 1:return True, steps, "String accepted!"else:return False, steps, "String rejected - incomplete parse"# Streamlit UIst.title("LL(1) Grammar Analyzer")# Session state initializationif 'test_strings' not in st.session_state:st.session_state.test_strings = []if 'parse_table' not in st.session_state:st.session_state.parse_table = Noneif 'grammar_processed' not in st.session_state:st.session_state.grammar_processed = False# Input sectionst.header("Grammar Input")start_symbol = st.text_input("Enter Start Symbol:", "S")with st.expander("Enter Grammar Rules", expanded=True):num_rules = st.number_input("Number of Rules:", min_value=1, value=4)rules = []for i in range(num_rules):4 unmodified linesnonterm_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")# Process Grammar Buttonif st.button("Process Grammar"):st.session_state.grammar_processed = False# Clear previous datadiction.clear()nonterm_userdef = [x.strip() for x in nonterm_input.split(',') if x.strip()]term_userdef = [x.strip() for x in term_input.split(',') if x.strip()]# Process rulesfor rule in rules:3 unmodified linesrhs_parts = [x.strip().split() for x in rhs.split("|")]diction[lhs] = rhs_parts# Grammar Processingst.subheader("Grammar Analysis")with st.expander("Grammar Transformations", expanded=True):st.write("After removing left recursion:")diction = removeLeftRecursion(diction)st.write(diction)6 unmodified linescomputeAllFirsts()computeAllFollows()with st.expander("FIRST and FOLLOW Sets", expanded=True):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 parse tableparse_table, grammar_is_LL = createParseTable()st.session_state.parse_table = parse_table# Display parse tablest.subheader("Parse Table")df_data = []terminals = term_userdef + ['$']for non_term in parse_table:row = [non_term]for term in terminals:production = parse_table[non_term].get(term, "")if production:10 unmodified lineselse:st.error("This grammar is not LL(1)!")st.session_state.grammar_processed = True# String Validation Sectionif st.session_state.grammar_processed:st.header("String Validation")# Input for new test stringcol1, col2 = st.columns([3, 1])with col1:new_string = st.text_input("Enter a string to test (space-separated):")with col2:if st.button("Add String"):if new_string and new_string not in st.session_state.test_strings:st.session_state.test_strings.append(new_string)# Display and validate all test stringsif st.session_state.test_strings:st.subheader("Test Results")for test_string in st.session_state.test_strings:with st.expander(f"String: {test_string}", expanded=True):is_valid, steps, message = validateStringUsingStackBuffer(st.session_state.parse_table, test_string, start_symbol)# Display resultif is_valid:st.success(message)else:st.error(message)# Display parsing stepsst.write("Parsing Steps:")for i, (step_type, *step_details) in enumerate(steps, 1):st.text(f"Step {i}:")st.text(f" {step_type}")for detail in step_details:st.text(f" {detail}")# Option to clear test stringsif st.button("Clear All Test Strings"):st.session_state.test_strings = []st.experimental_rerun()else:st.info("Please process the grammar first before testing strings.")# Help sectionwith st.expander("Help & Instructions"):st.markdown("""### How to use this LL(1) Grammar Analyzer:1. **Enter the Grammar**:- Specify the start symbol- Enter the grammar rules in the format: A -> B c | d- List all non-terminals and terminals2. **Process the Grammar**:- Click "Process Grammar" to analyze the grammar- View the transformed grammar, FIRST/FOLLOW sets, and parse table3. **Test Strings**:- Enter strings to test in the validation section- Add multiple strings to test- View detailed parsing steps for each string### Example Grammar:```S -> A k OA -> A d | a B | a CC -> cB -> b B C | r```### Example Test Strings:- a r k O- a c k O- a b r c k O""")
app.py+112-59