Update app.py
Browse files164 unmodified lines1651661671681691681691701711721731741761771751761771791801811821781841851861871791801811911821831931841851861971981992002011871881891902041911921931941951962111971981992132002012152022032172182192202042052222062242072082262092102112122132142152162172182192202212222232242252352262272282294 unmodified lines2342352362462472482492502512372382392402412422432442452462473 unmodified lines2512522532632642652542552562572582592606 unmodified lines26726826927827027127227328227427527627727827928628028128228329128428528628710 unmodified lines298299300308309310311312301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337314315316317318319320321322323338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376164 unmodified lines return parse_table, grammar_is_LL
def validateStringUsingStackBuffer(parse_table, input_string, start_sym): print("Validating:", input_string) # Debug print """Validates a string using the parsing table""" # Initialize stack and input buffer stack = [start_sym, '$'] input_tokens = input_string.split() input_tokens.append('$') buffer = input_tokens print("Initial stack:", stack) # Debug print print("Initial buffer:", buffer) # Debug print steps = [] steps.append(("Initial Configuration:", f"Stack: {stack}", f"Input: {buffer}")) parsing_steps = [] parsing_steps.append(f"Stack: {stack}, Input: {buffer}")
# Processing loop while stack and buffer: print(f"\nCurrent stack: {stack}") # Debug print print(f"Current buffer: {buffer}") # Debug print # Get top of stack and current input top_stack = stack[0] current_input = buffer[0] parsing_steps.append(f"Top of stack: {top_stack}, Current input: {current_input}") steps.append(("Current Step:", f"Stack Top: {top_stack}", f"Current Input: {current_input}")) # Case 1: Match found if top_stack == current_input: stack.pop(0) buffer.pop(0) parsing_steps.append("Matched and consumed") continue # Case 2: Non-terminal on top if top_stack in parse_table: 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-terminal stack.pop(0) # Push the production in reverse (if it's not epsilon) if production != ['#']: stack = production + stack parsing_steps.append(f"Applied rule: {top_stack} -> {' '.join(production) if production else '#'}") steps.append(("Production Applied:", f"{top_stack} -> {' '.join(production) if production else '#'}", f"New Stack: {stack}")) else: return False, f"No production for {top_stack} with input {current_input}", parsing_steps return False, steps, f"No production for {top_stack} with input {current_input}" else: return False, f"Input symbol {current_input} not in parse table for {top_stack}", parsing_steps return False, steps, f"Input symbol {current_input} not in parse table for {top_stack}" else: # If top of stack is not in parse table and doesn't match input return False, f"Unexpected symbol {top_stack} on stack", parsing_steps print(f"Updated stack: {stack}") # Debug print return False, steps, f"Unexpected symbol {top_stack} on stack" # Check if both stack and buffer are empty (except for $) if len(stack) <= 1 and len(buffer) <= 1: return True, "String accepted", parsing_steps return True, steps, "String accepted!" else: return False, "String rejected - incomplete parse", parsing_steps 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"):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")
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"):# Process Grammar Buttonif st.button("Process Grammar"): st.session_state.grammar_processed = False # Clear previous data diction.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 rules for rule in rules:3 unmodified lines rhs_parts = [x.strip().split() for x in rhs.split("|")] diction[lhs] = rhs_parts # Remove left recursion and perform left factoring st.subheader("Grammar Processing") with st.expander("Show Grammar Transformations"): # Grammar Processing st.subheader("Grammar Analysis") with st.expander("Grammar Transformations", expanded=True): st.write("After removing left recursion:") diction = removeLeftRecursion(diction) st.write(diction)6 unmodified lines computeAllFirsts() computeAllFollows() with st.expander("Show FIRST and FOLLOW Sets"): 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 and display parse table # Create parse table parse_table, grammar_is_LL = createParseTable() st.session_state.parse_table = parse_table # Display parse table st.subheader("Parse Table") # Convert parse table to pandas DataFrame for better display df_data = [] terminals = term_userdef + ['$'] for non_term in parse_table: row = [non_term] # First column is non-terminal row = [non_term] for term in terminals: production = parse_table[non_term].get(term, "") if production:10 unmodified lines else: st.error("This grammar is not LL(1)!") # String validation section st.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) st.session_state.grammar_processed = True
# String Validation Sectionif st.session_state.grammar_processed: st.header("String Validation") # Input for new test string col1, 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 strings if 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 result if is_valid: st.success(message) else: st.error(message) # Display parsing steps st.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}") # Display the result if is_valid: st.success(message) else: st.error(message) # Display parsing steps st.subheader("Parsing Steps") for i, step in enumerate(steps): st.text(f"Step {i+1}: {step}") # Option to clear test strings if 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 terminals 2. **Process the Grammar**: - Click "Process Grammar" to analyze the grammar - View the transformed grammar, FIRST/FOLLOW sets, and parse table 3. **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 O A -> A d | a B | a C C -> c B -> 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