1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Finite automaton (NFA & DFA)
24 var start
: State is noinit
26 # State that are accept states
27 var accept
= new Array[State]
30 var states
= new Array[State]
32 # Tokens associated on accept states.
33 # Use `add_tag` to update
34 var tags
= new HashMap[State, Set[Token]]
36 # Accept states associated on tokens.
37 # Use `add_tag` to update
38 var retrotags
= new HashMap[Token, Set[State]]
40 # Tag all accept states
41 fun tag_accept
(t
: Token)
43 for s
in accept
do add_tag
(s
, t
)
46 # Add a token to a state
47 fun add_tag
(s
: State, t
: Token)
49 if not tags
.has_key
(s
) then
50 var set
= new ArraySet[Token]
57 if not retrotags
.has_key
(t
) then
58 var set
= new ArraySet[State]
66 assert retrotags
[t
].has
(s
)
69 # Remove all occurrences of a tag in an automaton
70 fun clear_tag
(t
: Token)
72 if not retrotags
.has_key
(t
) then return
73 for s
in retrotags
[t
] do
74 if not tags
.has_key
(s
) then continue
76 if tags
[s
].is_empty
then tags
.keys
.remove
(s
)
78 retrotags
.keys
.remove
(t
)
81 # Remove tokens from conflicting state according the inclusion of language.
82 # REQUIRE: self isa DFA automaton
83 fun solve_token_inclusion
86 if ts
.length
<= 1 then continue
87 var losers
= new Array[Token]
90 if t1
== t2
then continue
91 if retrotags
[t1
].length
> retrotags
[t2
].length
and retrotags
[t1
].has_all
(retrotags
[t2
]) then
104 # Initialize a new automaton for the empty language.
105 # One state, no accept, no transition.
108 var state
= new State
113 # Initialize a new automaton for the empty-string language.
114 # One state, is accept, no transition.
117 var state
= new State
123 # Initialize a new automation for the language that accepts only a single symbol.
124 # Two state, the second is accept, one transition on `symbol`.
125 init atom
(symbol
: Int)
129 var sym
= new TSymbol(symbol
, symbol
)
137 # Initialize a new automation for the language that accepts only a range of symbols
138 # Two state, the second is accept, one transition for `from` to `to`
139 init cla
(first
: Int, last
: nullable Int)
143 var sym
= new TSymbol(first
, last
)
151 # Concatenate `other` to `self`.
152 # Other is modified and invalidated.
153 fun concat
(other
: Automaton)
157 a1
.add_trans
(s2
, null)
159 accept
= other
.accept
160 states
.add_all other
.states
163 # `self` become the alternation of `self` and `other`.
164 # `other` is modified and invalidated.
165 fun alternate
(other
: Automaton)
169 s
.add_trans
(start
, null)
171 a1
.add_trans
(a
, null)
173 s
.add_trans
(other
.start
, null)
174 for a2
in other
.accept
do
175 a2
.add_trans
(a
, null)
184 states
.add_all other
.states
187 # Return a new automaton that recognize `self` but not `other`.
188 # For a theoretical POV, this is the subtraction of languages.
189 # Note: the implementation use `to_dfa` internally, so the theoretical complexity is not cheap.
190 fun except
(other
: Automaton): Automaton
192 var ta
= new Token("1")
194 var tb
= new Token("2")
197 var c
= new Automaton.empty
202 for s
in c
.retrotags
[ta
] do
203 if not c
.tags
[s
].has
(tb
) then
212 # `self` absorbs all states, transitions, tags, and acceptations of `other`.
213 # An epsilon transition is added between `self.start` and `other.start`.
214 fun absorb
(other
: Automaton)
216 states
.add_all other
.states
217 start
.add_trans
(other
.start
, null)
218 for s
, ts
in other
.tags
do for t
in ts
do add_tag
(s
, t
)
219 accept
.add_all other
.accept
222 # Do the Kleene closure (*) on self
226 a1
.add_trans
(start
, null)
227 start
.add_trans
(a1
, null)
235 a1
.add_trans
(start
, null)
242 alternate
(new Automaton.epsilon
)
245 # Remove all transitions on a given symbol
246 fun minus_sym
(symbol
: TSymbol)
251 for t
in s
.outs
.to_a
do
252 if t
.symbol
== null then continue
255 var tf
= t
.symbol
.first
256 var tl
= t
.symbol
.last
257 if l
!= null and tf
> l
then continue
258 if tl
!= null and f
> tl
then continue
262 # Add left and right part if non empty
264 var sym
= new TSymbol(tf
,f-1
)
265 s
.add_trans
(t
.to
, sym
)
269 var sym
= new TSymbol(l
+1, null)
270 s
.add_trans
(t
.to
, sym
)
272 var sym
= new TSymbol(l
+1, tl
)
273 s
.add_trans
(t
.to
, sym
)
280 # Fully duplicate an automaton
283 var res
= new Automaton.empty
284 var map
= new HashMap[State, State]
285 map
[start
] = res
.start
287 if s
== start
then continue
293 res
.accept
.add map
[s
]
295 for s
, ts
in tags
do for t
in ts
do
296 res
.add_tag
(map
[s
], t
)
300 map
[s
].add_trans
(map
[t
.to
], t
.symbol
)
306 # Reverse an automaton in place
320 if accept
.length
== 1 then
328 st2
.add_trans
(s
, null)
335 # Remove states (and transitions) that does not reach an accept state
338 # Good states are those we want to keep
339 var goods
= new HashSet[State]
340 goods
.add_all
(accept
)
342 var todo
= accept
.to_a
345 while not todo
.is_empty
do
349 if goods
.has
(s2
) then continue
355 # What are the bad state then?
356 var bads
= new Array[State]
358 if not goods
.has
(s
) then bads
.add
(s
)
361 # Remove their transitions
363 for t
in s
.ins
.to_a
do t
.delete
364 for t
in s
.outs
.to_a
do t
.delete
367 # Keep only the good stuff
369 states
.add_all
(goods
)
372 # Generate a minimal DFA
373 # REQUIRE: self is a DFA
374 fun to_minimal_dfa
: Automaton
380 # Graph of known distinct states.
381 var distincts
= new HashMap[State, Set[State]]
383 distincts
[s
] = new HashSet[State]
386 # split accept states.
387 # An accept state is distinct with a non accept state.
390 if distincts
[s1
].has
(s2
) then continue
391 if not accept
.has
(s1
) then continue
392 if not accept
.has
(s2
) then
393 distincts
[s1
].add
(s2
)
394 distincts
[s2
].add
(s1
)
397 if tags
.get_or_null
(s1
) != tags
.get_or_null
(s2
) then
398 distincts
[s1
].add
(s2
)
399 distincts
[s2
].add
(s1
)
405 # Fixed point algorithm.
406 # * Get 2 states s1 and s2 not yet distinguished.
408 # * If s1.trans(w) and s2.trans(w) are distinguished, then
409 # distinguish s1 and s2.
411 var ints
= new Array[Int] # List of symbols to check
414 for s1
in states
do for s2
in states
do
415 if distincts
[s1
].has
(s2
) then continue
417 # The transitions use intervals. Therefore, for the states s1 and s2,
418 # we need to check only the meaningful symbols. They are the `first`
419 # symbol of each interval and the first one after the interval (`last+1`).
421 # Check only `s1`; `s2` will be checked later when s1 and s2 are switched.
427 if l
!= null then ints
.add l
+ 1
432 var ds1
= s1
.trans
(i
)
433 var ds2
= s2
.trans
(i
)
434 if ds1
== ds2
then continue
435 if ds1
!= null and ds2
!= null and not distincts
[ds1
].has
(ds2
) then continue
436 distincts
[s1
].add
(s2
)
437 distincts
[s2
].add
(s1
)
444 # We need to unify not-distinguished states.
445 # Just add an epsilon-transition and DFAize the automaton.
446 for s1
in states
do for s2
in states
do
447 if distincts
[s1
].has
(s2
) then continue
448 s1
.add_trans
(s2
, null)
454 # Assert that `self` is a valid automaton or abort
457 assert states
.has
(start
)
458 assert states
.has_all
(accept
)
460 for t
in s
.outs
do assert states
.has
(t
.to
)
461 for t
in s
.ins
do assert states
.has
(t
.from
)
463 assert states
.has_all
(tags
.keys
)
464 for t
, ss
in retrotags
do
465 assert states
.has_all
(ss
)
469 # Produce a graphvis file for the automaton
470 fun to_dot
(filepath
: String)
472 var names
= new HashMap[State, String]
479 var f
= new FileWriter.open
(filepath
)
480 f
.write
("digraph g \{\n")
483 f
.write
("s{names[s]}[shape=oval")
484 #f.write("label=\"\",")
485 if accept
.has
(s
) then
486 f
.write
(",color=blue")
488 if tags
.has_key
(s
) then
490 for token in tags[s] do
491 f.write("{token.name.escape_to_c}\\n
")
495 f
.write
(",label=\"\
"")
498 var outs
= new HashMap[State, Array[nullable TSymbol]]
503 if outs
.has_key
(s2
) then
506 a
= new Array[nullable TSymbol]
514 if not labe
.is_empty
then labe
+= "\n"
521 f
.write
("s{names[s]}->s{names[s2]} [label=\"{labe.escape_to_c}\
"];\n")
524 f
.write
("empty->s{names[start]}; empty[label=\"\
",shape=none];\n")
530 # Transform a NFA to a DFA.
531 # note: the DFA is not minimized.
532 fun to_dfa
: Automaton
538 var dfa
= new Automaton.empty
539 var n2d
= new ArrayMap[Set[State], State]
540 var seen
= new ArraySet[Set[State]]
541 var alphabet
= new HashSet[Int]
542 var st
= eclosure
([start
])
546 while not todo
.is_empty
do
547 var nfa_states
= todo
.pop
548 #print "* work on {nfa_states.inspect}={nfa_states} (remains {todo.length}/{seen.length})"
549 var dfa_state
= n2d
[nfa_states
]
551 for s
in nfa_states
do
552 # Collect important values to build the alphabet
555 if sym
== null then continue
556 alphabet
.add
(sym
.first
)
558 if l
!= null then alphabet
.add
(l
)
561 # Mark accept and tags
562 if accept
.has
(s
) then
563 if tags
.has_key
(s
) then
565 dfa
.add_tag
(dfa_state
, t
)
568 dfa
.accept
.add
(dfa_state
)
572 # From the important values, build a sequence of TSymbols
573 var a
= alphabet
.to_a
574 default_comparator
.sort
(a
)
575 var tsyms
= new Array[TSymbol]
578 if last
> 0 and last
<= i-1
then
579 tsyms
.add
(new TSymbol(last
,i-1
))
581 tsyms
.add
(new TSymbol(i
,i
))
585 tsyms
.add
(new TSymbol(last
,null))
587 #print "Alphabet: {tsyms.join(", ")}"
589 var lastst
: nullable Transition = null
591 var nfa_dest
= eclosure
(trans
(nfa_states
, sym
.first
))
592 if nfa_dest
.is_empty
then
596 #print "{nfa_states} -> {sym} -> {nfa_dest}"
598 if seen
.has
(nfa_dest
) then
599 #print "* reuse {nfa_dest.inspect}={nfa_dest}"
600 dfa_dest
= n2d
[nfa_dest
]
602 #print "* new {nfa_dest.inspect}={nfa_dest}"
604 dfa
.states
.add
(dfa_dest
)
605 n2d
[nfa_dest
] = dfa_dest
609 if lastst
!= null and lastst
.to
== dfa_dest
then
610 lastst
.symbol
.last
= sym
.last
612 lastst
= dfa_state
.add_trans
(dfa_dest
, sym
)
619 # Epsilon-closure on a state of states.
621 private fun eclosure
(states
: Collection[State]): Set[State]
623 var res
= new ArraySet[State]
625 var todo
= states
.to_a
626 while not todo
.is_empty
do
629 if t
.symbol
!= null then continue
631 if res
.has
(to
) then continue
639 # Trans on a set of states.
641 fun trans
(states
: Collection[State], symbol
: Int): Set[State]
643 var res
= new ArraySet[State]
647 if sym
== null then continue
648 if sym
.first
> symbol
then continue
650 if l
!= null and l
< symbol
then continue
652 if res
.has
(to
) then continue
659 # Generate the Nit source code of the lexer.
660 # `filepath` is the name of the output file.
661 # `parser` is the name of the parser module (used to import the token classes).
662 fun gen_to_nit
(filepath
: String, name
: String, parser
: nullable String)
664 var gen
= new DFAGenerator(filepath
, name
, self, parser
)
669 # Generate the Nit source code of the lexer
670 private class DFAGenerator
673 var automaton
: Automaton
674 var parser
: nullable String
676 var out
: Writer is noinit
679 self.out
= new FileWriter.open
(filepath
)
682 fun add
(s
: String) do out
.write
(s
)
686 var names
= new HashMap[State, String]
688 for s
in automaton
.states
do
693 add
"# Lexer generated by nitcc for the grammar {name}\n"
694 add
"module {name}_lexer is generated, no_warning \"missing-doc\
"\n"
695 add
("import nitcc_runtime\n")
698 if p
!= null then add
("import {p}\n")
700 add
("class Lexer_{name}\n")
701 add
("\tsuper Lexer\n")
702 add
("\tredef fun start_state do return dfastate_{names[automaton.start]}\n")
705 for s
in automaton
.states
do
707 add
("private fun dfastate_{n}: DFAState{n} do return once new DFAState{n}\n")
710 add
("class MyNToken\n")
711 add
("\tsuper NToken\n")
714 for s
in automaton
.states
do
716 add
("private class DFAState{n}\n")
717 add
("\tsuper DFAState\n")
718 if automaton
.accept
.has
(s
) then
720 if automaton
.tags
.has_key
(s
) then
721 token
= automaton
.tags
[s
].first
725 add
("\tredef fun is_accept do return true\n")
726 var is_ignored
= false
727 if token
!= null and token
.name
== "Ignored" then
729 add
("\tredef fun is_ignored do return true\n")
731 add
("\tredef fun make_token(position, source) do\n")
733 add
("\t\treturn null\n")
735 if token
== null then
736 add
("\t\tvar t = new MyNToken\n")
737 add
("\t\tt.text = position.extract(source)\n")
739 add
("\t\tvar t = new {token.cname}\n")
740 var ttext
= token
.text
741 if ttext
== null then
742 add
("\t\tt.text = position.extract(source)\n")
744 add
("\t\tt.text = \"{ttext.escape_to_nit}\
"\n")
747 add
("\t\tt.position = position\n")
748 add
("\t\treturn t\n")
752 var trans
= new ArrayMap[TSymbol, State]
758 if trans
.is_empty
then
759 # Do nothing, inherit the trans
761 add
("\tredef fun trans(char) do\n")
763 # Collect the sequence of tests in the dispatch sequence
764 # The point here is that for each transition, there is a first and a last
765 # So holes have to be identified
766 var dispatch
= new HashMap[Int, nullable State]
767 var haslast
: nullable State = null
770 for sym
, next
in trans
do
771 assert haslast
== null
772 assert sym
.first
> last
773 if sym
.first
> last
+ 1 then
774 dispatch
[sym
.first-1
] = null
785 if dispatch
.is_empty
and haslast
!= null then
786 # Only one transition that accepts everything (quite rare)
789 add
("\t\tvar c = char.code_point\n")
792 # Generate a sequence of `if` for the dispatch
793 if haslast
!= null and last
>= 0 then
794 # Special case: handle up-bound first if not an error
795 add
("\t\tif c > {last} then return dfastate_{names[haslast]}\n")
796 # previous become the new last case
797 haslast
= dispatch
[last
]
798 dispatch
.keys
.remove
(last
)
800 for c
, next
in dispatch
do
802 add
("\t\tif c <= {c} then return null\n")
804 add
("\t\tif c <= {c} then return dfastate_{names[next]}\n")
807 if haslast
== null then
808 add
("\t\treturn null\n")
810 add
("\t\treturn dfastate_{names[haslast]}\n")
823 # The associated text (if any, ie defined in the parser part)
824 var text
: nullable String is noautoinit
, writable
827 # A state in a finite automaton
829 # Outgoing transitions
830 var outs
= new Array[Transition]
832 # Ingoing transitions
833 var ins
= new Array[Transition]
835 # Add a transitions to `to` on `symbol` (null means epsilon)
836 fun add_trans
(to
: State, symbol
: nullable TSymbol): Transition
838 var t
= new Transition(self, to
, symbol
)
844 # Get the first state following the transition `i`.
845 # Null if no transition for `i`.
846 fun trans
(i
: Int): nullable State
853 if i
< f
then continue
854 if l
!= null and i
> l
then continue
861 # A range of symbols on a transition
863 # The first symbol in the range
866 # The last symbol if any.
868 # `null` means infinity.
869 var last
: nullable Int
878 res
= f
.code_point
.to_s
881 if f
== l
then return res
883 if l
== null then return res
884 if l
<= 32 or l
>= 127 then return res
+ "#{l}"
885 return res
+ l
.code_point
.to_s
889 # A transition in a finite automaton
893 # The destination state
895 # The symbol on the transition (null means epsilon)
896 var symbol
: nullable TSymbol
898 # Remove the transition from the automaton.
899 # Detach from `from` and `to`.
902 from
.outs
.remove
(self)