APL(NARS), 389380 chars
r←f w;a;b;i;l;c;t;p;q;np;G
G←⍬
w←,w⋄r←G⍳⊂w⋄→4×⍳r≤≢G⋄G,←⊂w⋄→6
r←0⋄→0
r←1⋄→0
r←2⋄→0
i←1⋄r←a←b←''⋄l←≢w⋄np←1⋄p←q←''np←i←1⋄p←q←r←a←b←''⋄l←≢w
→3×⍳i>l⋄a←w[i]⋄i+←1⋄→10×⍳a='('
→3×⍳i>l⋄c←w[i]⋄i+←1
→11×⍳∼c='→12×⍳∼c='('⋄p←''
p←'('⋄q←')'
→3×⍳i>l⋄c←w[i]⋄i+←1⋄np+←c='('⋄np→3×⍳i>l⋄c←w[i]⋄i+←1⋄np+←c=p⋄np-←c=')'⋄→12×⍳np=0⋄b←c=q⋄→13×⍳np=0⋄b,←c⋄→10←c⋄→11
b←,c
t←b⋄→14×⍳a='t←b⋄→15×⍳a='('⋄→5×⍳(np=1)∧(a='T')∧'T'=↑,b⋄→5×⍳(a='T')∧'ST'≡b
t←{a='N':''⋄a='S':b⋄a='D':b,p,b,q⋄a='T':b,p,b,q,p,b,q⋄'Fail'}
w←t,(i-1)↓w⋄→2
// ++/ 27 4 30 7 7 7 3025 31 20 24 5912 12 55 5 61 62 15=38915=380
f function has as input one string of chars, and return 0 for programfunction terminate, 1 if there is a loop withfunction meets a repeat state (this means a loop), 2 if the function find a loop has the conseguencewith no repeat state, this means that if f is not stopped it will go of out of memory for the program in a future time.
f function puts in the globalan array G, the state, that is each input, that would be the string array in w in each loop inside f function. If some state is repeated (find the w is already in G) than retun 1 because there is detected an infinite loop. If else function terminate it return 0. Else return 2 in the case it finds in the start of w the strings TT or T(ST) at beginningthat it seems generate always differents states tha will have as effect the go out of w variablememory in the future. I don't know if these string are the only one that generate always differents states.
r←f w;a;b;i;l;c;t;p;q;np;G
1: G←⍬
2: w←,w⋄r←G⍳⊂w⋄→4×⍳r≤≢G⋄G,←⊂w⋄→6
3: r←0⋄→0
4: r←1⋄→0
5: r←2⋄→0
6: i←1⋄r←a←b←''⋄l←≢w⋄np←1⋄p←q←''np←i←1⋄p←q←r←a←b←''⋄l←≢w
7: →3×⍳i>l⋄a←w[i]⋄i+←1⋄→10×⍳a='('
8: →3×⍳i>l⋄c←w[i]⋄i+←1
9: →11×⍳∼c='→12×⍳∼c='('⋄p←''
10: p←'('⋄q←')'
1011: →3×⍳i>l⋄c←w[i]⋄i+←1⋄np+←c='('⋄np→3×⍳i>l⋄c←w[i]⋄i+←1⋄np+←c=p⋄np-←c=')'⋄→12×⍳np=0⋄b←c=q⋄→13×⍳np=0⋄b,←c⋄→10←c⋄→11
1112: b←,c
1213: t←b⋄→14×⍳a='t←b⋄→15×⍳a='('⋄→5×⍳(np=1)∧(a='T')∧'T'=↑,b⋄→5×⍳(a='T')∧'ST'≡b
1314: t←{a='N':''⋄a='S':b⋄a='D':b,p,b,q⋄a='T':b,p,b,q,p,b,q⋄'Fail'}
1415: w←t,(i-1)↓w⋄→2