def kstar(graph, id_alloc): """ Kleene Star operator """ new_start = NFAState(id_alloc.create_id()) new_start.add_path(create_epsilon_trans(), graph.start) new_end = NFAState(id_alloc.create_id()) new_start.add_path(create_epsilon_trans(), new_end) graph.end.add_path(create_epsilon_trans(), new_end) graph.end.add_path(create_epsilon_trans(), graph.start) return NFA(new_start, new_end)
def union(graph1, graph2, id_alloc): """ A union is represented by the pipe operator ('|') """ new_start = NFAState(id_alloc.create_id()) new_start.add_path(create_epsilon_trans(), graph1.start) new_start.add_path(create_epsilon_trans(), graph2.start) new_end = NFAState(id_alloc.create_id()) graph1.end.add_path(create_epsilon_trans(), new_end) graph2.end.add_path(create_epsilon_trans(), new_end) return NFA(new_start, new_end)
def test_epsilon_transition_always_passes(self): transition = create_epsilon_trans() self.assertTrue(transition.is_available('a')) self.assertTrue(transition.is_available('A')) self.assertTrue(transition.is_available('0')) self.assertTrue(transition.is_available('-')) self.assertTrue(transition.is_available('\n'))
def trans_desc_to_trans(desc_str): """ Takes a description str and converts it into an actual transition """ if desc_str == "epsilon": return create_epsilon_trans() elif desc_str == "metachar": return create_metachar_trans() elif desc_str[0:6] == "char: ": return create_char_trans(desc_str[6]) else: Exception("cannot convert " + desc_str + " to a transition")
def repeater(graph, repeater_tok, id_alloc): """ Constructs an nfa for '*', '+', '?' """ if repeater_tok.has_val('*'): return kstar(graph, id_alloc) elif repeater_tok.has_val('+'): kstar_graph = kstar(graph, id_alloc) return concat(graph, kstar_graph) elif repeater_tok.has_val('?'): empty_graph = construct_graph(create_epsilon_trans(), id_alloc) return union(graph, empty_graph) else: raise Exception("repeater not recognized: " + repeater_tok)