diff options
author | buraq <buraq@epfl.ch> | 2005-01-21 16:08:06 +0000 |
---|---|---|
committer | buraq <buraq@epfl.ch> | 2005-01-21 16:08:06 +0000 |
commit | 0dce46b648e6b74c0841e3ec1279029f3d3f7ae4 (patch) | |
tree | a6074598cff5308027ae9e4f9db21b5e51c4fe89 /sources/scalac/transformer | |
parent | 1098308d1ad759f0b5d52063e8b4228711db9dde (diff) | |
download | scala-0dce46b648e6b74c0841e3ec1279029f3d3f7ae4.tar.gz scala-0dce46b648e6b74c0841e3ec1279029f3d3f7ae4.tar.bz2 scala-0dce46b648e6b74c0841e3ec1279029f3d3f7ae4.zip |
translated most to scala
Diffstat (limited to 'sources/scalac/transformer')
15 files changed, 36 insertions, 1553 deletions
diff --git a/sources/scalac/transformer/matching/AlgebraicMatcher.java b/sources/scalac/transformer/matching/AlgebraicMatcher.java deleted file mode 100644 index 28278b8445..0000000000 --- a/sources/scalac/transformer/matching/AlgebraicMatcher.java +++ /dev/null @@ -1,182 +0,0 @@ -/* ____ ____ ____ ____ ______ *\ -** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala ** -** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL ** -** /_____/\____/\___/\____/____/ ** -** ** -** $Id$ -\* */ - -package scalac.transformer.matching; - -import scalac.*; -import scalac.ast.*; -import scalac.atree.AConstant; -import scalac.symtab.*; - -import PatternNode.*; -import Tree.*; - -import scalac.util.Name ; -import scalac.util.Names ; - -import java.util.Vector ; -import java.util.Iterator ; - -/** Matthias' algebraic pattern matcher, with some things factored out - * @author Matthias Zenger, Burak Emir - */ - -public class AlgebraicMatcher extends PatternMatcher { - - PartialMatcher _m; - - /** constructor - */ - public AlgebraicMatcher( CompilationUnit unit ) { - super( unit ); - this.delegateSequenceMatching = true; - this.optimize = false; - } - - /** constructs an algebraic pattern matcher from cases - */ - public void construct( PartialMatcher m, Tree[] cases) { - construct(m, cases, true); - } - - /** constructs an algebraic pattern matcher from cases - */ - public void construct( PartialMatcher m, Tree[] cases, boolean doBinding) { - this._m = m; - super.initialize( _m.selector, _m.owner, _m.resultType, doBinding ); - for( int i = 0; i < cases.length; i++ ) { - enter( cases[ i ] );//(CaseDef) cases[i], i); - } - if (unit.global.log()) { - unit.global.log("internal pattern matching structure"); - print(); - } - _m.tree = toTree(); - } - - - /** initializes this AlgebraicMatcher, see Matcher.initialize - void initialize() { - } - */ - - boolean isStarApply( Tree.Apply tree ) { - Symbol params[] = tree.fun.type.valueParams(); - //System.err.println( tree.fun.type.resultType().symbol() ); - return (tree.args.length == 1) - && (tree.type.symbol().flags & Modifiers.CASE) != 0 - && params.length > 0 - && (params[params.length-1].flags & Modifiers.REPEATED) != 0; - } - -//////////// generator methods - - public Tree toTree() { - Tree[] ts = { - gen.ValDef(root.symbol(), _m.selector ), - gen.ValDef(resultVar, - gen.mkDefaultValue(_m.pos, resultVar.info()) )}; - Tree res = gen.If( toTree(root.and), - gen.Ident( _m.pos, resultVar ), - cf.ThrowMatchError( _m.pos, _m.resultType )); - /* - gen.If( - _m.pos, - toTree(root.and), - gen.Ident( _m.pos, resultVar ), - cf.ThrowMatchError( _m.resultType )); - */ - return gen.mkBlock(_m.pos, ts, res); - } - - protected Tree toTree(PatternNode node, Tree selector) { - //System.err.println("AM.toTree called"+node); - if (node == null) - return gen.mkBooleanLit(_m.pos, false); - switch (node) { - case SeqContainerPat( _, _ ): - return callSequenceMatcher( node, - selector ); - default: - return super.toTree( node, selector ); - } - } - - /** collects all sequence patterns and returns the default - */ - PatternNode collectSeqPats( PatternNode node, - Vector seqPatNodes, - Vector bodies ) { - - PatternNode defaultNode = null; - - do { - if( node == null ) - break;// defaultNode = node; - else - switch( node ) { - case SeqContainerPat( _, _ ): - seqPatNodes.add( node ); - bodies.add( toTree( node.and ) ); - node = node.or; - break; - default: - defaultNode = node; - } - } while (defaultNode == null) ; - - return defaultNode; - } - - Tree callSequenceMatcher( PatternNode node, - Tree selector) { - - /* ???????????????????????? necessary to test whether is a Seq? - gen.If(selector.pos, - maybe cf.And( cf.Is(selector, seqpat.type()) - ... - */ - - // translate the _.and subtree of this SeqContainerPat - - Vector seqPatNodes = new Vector(); - Vector bodies = new Vector(); - - PatternNode defaultNode = collectSeqPats( node, - seqPatNodes, - bodies ); - - Tree defaultCase = toTree( defaultNode, selector ); - - SequenceMatcher wordRec = new SequenceMatcher(unit); - - PartialMatcher m = new PartialMatcher( _m.owner, - selector, - defs.boolean_TYPE() ); - - Tree pats[] = new Tree[ seqPatNodes.size() ]; - Tree body[] = new Tree[ seqPatNodes.size() ]; - - Object tmp[] = bodies.toArray(); - int j = 0; - for( Iterator it = seqPatNodes.iterator(); - it.hasNext();) { - pats[ j ] = ((SeqContainerPat) it.next()).seqpat; - body[ j ] = (Tree) tmp[j]; - j++; - } - //Tree defaultTree = toTree( node.or, selector ); // cdef.body ; - - wordRec.construct( m, pats, body, defaultCase, doBinding ); - - //_m.defs.addAll( m.defs ); - - return m.tree; - } - -} diff --git a/sources/scalac/transformer/matching/Autom2Scala.java b/sources/scalac/transformer/matching/Autom2Scala.java deleted file mode 100644 index c61a8cf420..0000000000 --- a/sources/scalac/transformer/matching/Autom2Scala.java +++ /dev/null @@ -1,228 +0,0 @@ -package scalac.transformer.matching ; - -import scalac.* ; -import scalac.symtab.Symbol ; -import scalac.symtab.Type ; -import scalac.symtab.Definitions ; -import scalac.symtab.Modifiers; -import scalac.ast.Tree; -import scalac.ast.TreeGen; -import scalac.util.Name; -import scalac.util.Names; -import Tree.*; - -import java.util.* ; - -import scala.tools.util.Position; - -public class Autom2Scala { - - protected boolean optimize = true; - - static final Name HASNEXT = Name.fromString("hasnext"); - static final Name CURRENT_ELEM = Name.fromString("cur"); - - final int FAIL = -1; - - DetWordAutom dfa; - protected CodeFactory cf; - - Definitions defs;// cf.defs only for convenience - TreeGen gen; // cf.gen only for convenience - - /** owner of the pattern matching expression */ - protected Symbol owner; - - /** symbol of the matcher DefDef or Label */ - Symbol funSym; - - /** symbol of the iterator ( scala.SequenceIterator ) */ - Symbol iterSym; - - /** symbol of the switching result ( scala.Int ) */ - Symbol resultSym; - - /** symbol of the state variable ( scala.Int ) */ - Symbol stateSym; - - /** symbol of variable holding current label */ - Symbol curSym; - - /** symbol of boolean variable that indicates we have not reached end of sequence */ - Symbol hasnSym; - - protected Type elementType; - - public int pos; - - Type funRetType() { - switch( funSym.type() ) { - case MethodType( _, Type retType ): - return retType; - } - throw new RuntimeException(); - } - - - Tree callFun( Tree[] args ) { - return gen.mkApply_V(gen.Ident(pos, funSym), args); - } - - public Autom2Scala( DetWordAutom dfa, - Type elementType, - Symbol owner, - CodeFactory cf ) { - this.dfa = dfa; - this.elementType = elementType; - this.defs = cf.defs; - this.gen = cf.gen; - this.owner = owner; - this.pos = Position.FIRSTPOS; - this.cf = cf; - this.am = new AlgebraicMatcher( cf.unit ); - } - - // overridden in RightTracerInScala - Tree loadCurrentElem( Tree body ) { - return gen.mkBlock( new Tree[] { - cf.gen.ValDef( this.hasnSym, - cf._hasNext( _iter() ) ), - cf.gen.ValDef( this.curSym, - gen.If( gen.Ident( pos, hasnSym ), - cf._next( _iter() ), - gen.mkDefaultValue(cf.pos,curSym.type())))}, - - body ); - } - - /** bug ?? */ - Tree currentElem() { return gen.Ident( cf.pos, curSym ).setType( curSym.type() ); } - - Tree currentMatches( Label label ) { - switch( label ) { - case TreeLabel( Tree pat ): - return _cur_match( pat ); - case SimpleLabel( Tree.Literal lit ): - return cf.Equals( currentElem(), lit ); - } - throw new ApplicationError("expected either algebraic or simple label:"+label); - } - - // - // translation of automata to scala code - // - - - /** `<switchResult>' */ - public Tree _swres() { return gen.Ident( pos, resultSym );} - - /** `<state>' param */ - public Tree _state() { return gen.Ident( pos, stateSym ); } - - /** `<iterator>' param */ - Tree _iter() { return gen.Ident( pos, iterSym ); } - - /** simple optimization: if we are in a sink state, stop traversing sequence - */ - Tree stateWrap(int i) { - if( dfa.isSink( i )) - return run_finished( i ); // state won't change! optimization - else - return gen.If( cf.Negate( gen.Ident( pos, hasnSym )), - run_finished( i ), - code_state_NEW( i )); - } - - /** body of the matcherDefFun - */ - public Tree code_body_NEW() { - int[] tags = new int[dfa.nstates]; - Tree[] bodies = new Tree[dfa.nstates]; - for( int i = 0; i<dfa.nstates; i++ ) { - tags[ i ] = i; - bodies[ i ] = stateWrap( i ); - } - //if( optimize ) - return loadCurrentElem( gen.Switch( _state(), - tags, - bodies, - code_error(), // cannot happen - funRetType())); - /* - Tree res = code_error(); - for( int i = dfa.nstates-2; i>= 0; i-- ) - res = gen.If( cf.Equals( _state(), gen.mkIntLit( cf.pos, i )), - bodies[ i ] , - res ); - - return loadCurrentElem( res ); - */ - } - - AlgebraicMatcher am; - - /* - void handleVars( ) { - } - */ - // calling the /*AlgebraicMatcher*/PatternMatcher here - Tree _cur_match( Tree pat ) { - PartialMatcher m = new PartialMatcher( this.funSym, /* owner*/ - currentElem(), /* root */ - defs.boolean_TYPE() /* restype */); - - am.construct( m, new CaseDef[] { - cf.gen.CaseDef( pat, - gen.mkBooleanLit( pat.pos, true )), - cf.gen.CaseDef( cf.gen.Ident(pat.pos, defs.PATTERN_WILDCARD), - gen.mkBooleanLit( pat.pos, false )) }, - false); - return am.toTree(); - } - - Tree code_delta( int i, Label label ) { - throw new RuntimeException(); - } - - /** some error happened which is due to bug in translation/automaton - */ - final Tree code_error() { - return cf.ThrowMatchError( pos, funRetType() ); - } - - Tree code_fail() { - return gen.mkIntLit(Position.FIRSTPOS, FAIL ); - } - - /** code for the return value of the automaton translation - */ - Tree run_finished( int state ) { - if( dfa.isFinal( state )) { - return gen.mkIntLit(Position.FIRSTPOS, ((Integer) dfa.finals.get( new Integer( state ) )).intValue() ); - } - return gen.mkIntLit( Position.FIRSTPOS, FAIL ); - } - - Tree code_state_NEW( int i ) { - Tree stateBody = code_delta( i, Label.DefaultLabel ); - if( stateBody == null ) - stateBody = code_fail(); - HashMap trans = ((HashMap[])dfa.deltaq)[ i ]; - - for( Iterator labs = dfa.labels.iterator(); labs.hasNext() ; ) { - Object label = labs.next(); - Integer next = (Integer) trans.get( label ); - - - Tree action = code_delta( i, (Label) label ); - - if( action != null ) { - assert stateBody != null : "stateBody is null"; - stateBody = gen.If( currentMatches((Label) label ), - action, - stateBody); - } - } - return stateBody; - } -} diff --git a/sources/scalac/transformer/matching/BerrySethi.java b/sources/scalac/transformer/matching/BerrySethi.java index a9a4abb851..3479ea0d81 100644 --- a/sources/scalac/transformer/matching/BerrySethi.java +++ b/sources/scalac/transformer/matching/BerrySethi.java @@ -17,7 +17,7 @@ import java.util.* ; * this class plays is the "Builder" for the "Director" class WordRecognizer. */ -class BerrySethi { +public class BerrySethi { CompilationUnit unit; diff --git a/sources/scalac/transformer/matching/BindingBerrySethi.java b/sources/scalac/transformer/matching/BindingBerrySethi.java index 69383fcbfa..89fd258a2d 100644 --- a/sources/scalac/transformer/matching/BindingBerrySethi.java +++ b/sources/scalac/transformer/matching/BindingBerrySethi.java @@ -52,7 +52,7 @@ public class BindingBerrySethi extends BerrySethi { revArrows.add( srcI ); } - NondetWordAutom revnfa ; + public NondetWordAutom revnfa ; void seenLabel( Tree pat, Label label ) { Integer i = new Integer( ++pos ); diff --git a/sources/scalac/transformer/matching/CodeFactory.java b/sources/scalac/transformer/matching/CodeFactory.java index cf162a364e..9d7b8ad0eb 100644 --- a/sources/scalac/transformer/matching/CodeFactory.java +++ b/sources/scalac/transformer/matching/CodeFactory.java @@ -18,7 +18,7 @@ import scalac.symtab.*; import PatternNode.*; import Tree.*; -class CodeFactory extends PatternTool { +public class CodeFactory extends PatternTool { public int pos = Position.FIRSTPOS ; @@ -46,24 +46,24 @@ class CodeFactory extends PatternTool { } /** returns `List[ Tuple2[ scala.Int, <elemType> ] ]' */ - Type SeqTraceType( Type elemType ) { + public Type SeqTraceType( Type elemType ) { return defs.LIST_TYPE(pairType(defs.int_TYPE(), elemType)); } /** returns `Iterator[ elemType ]' */ - Type _seqIterType( Type elemType ) { + public Type _seqIterType( Type elemType ) { return defs.ITERATOR_TYPE(elemType); } /** returns `<seqObj.elements>' */ - Tree newIterator( Tree seqObj, Type elemType ) { + public Tree newIterator( Tree seqObj, Type elemType ) { return gen.mkApply__(gen.Select(seqObj, defs.ITERABLE_ELEMENTS())); } /** returns code `<seqObj>.elements' * the parameter needs to have type attribute `Sequence[<elemType>]' */ - Tree newIterator( Tree seqObj ) { + public Tree newIterator( Tree seqObj ) { return newIterator( seqObj, getElemType_Sequence( seqObj.getType() )); } @@ -77,7 +77,7 @@ class CodeFactory extends PatternTool { /** returns A for T <: Sequence[ A ] */ - Type getElemType_Sequence( Type tpe ) { + public Type getElemType_Sequence( Type tpe ) { //System.err.println("getElemType_Sequence("+tpe.widen()+")"); Type tpe1 = tpe.widen().baseType( defs.SEQ_CLASS ); @@ -127,24 +127,24 @@ class CodeFactory extends PatternTool { return gen.mkApply__(gen.Select(iter, defs.LIST_ISEMPTY())); } - Tree SeqTrace_headElem( Tree arg ) { // REMOVE SeqTrace + public Tree SeqTrace_headElem( Tree arg ) { // REMOVE SeqTrace Tree t = gen.mkApply__(gen.Select(arg, defs.LIST_HEAD())); return gen.mkApply__(gen.Select(t, defs.TUPLE_FIELD(2, 2))); } - Tree SeqTrace_headState( Tree arg ) { // REMOVE SeqTrace + public Tree SeqTrace_headState( Tree arg ) { // REMOVE SeqTrace Tree t = gen.mkApply__(gen.Select(arg, defs.LIST_HEAD())); return gen.mkApply__(gen.Select(t, defs.TUPLE_FIELD(2, 1))); } - Tree SeqTrace_tail( Tree arg ) { // REMOVE SeqTrace + public Tree SeqTrace_tail( Tree arg ) { // REMOVE SeqTrace return gen.mkApply__(gen.Select(arg, defs.LIST_TAIL())); } /** `<seqlist>.head()' */ - Tree SeqList_head( Tree arg ) { + public Tree SeqList_head( Tree arg ) { return gen.mkApply__(gen.Select(arg, defs.LIST_HEAD())); } @@ -157,7 +157,7 @@ class CodeFactory extends PatternTool { return gen.mkApply__(gen.Select(tree, defs.BOOLEAN_NOT())); } - protected Tree And(Tree left, Tree right) { + /*protected*/ Tree And(Tree left, Tree right) { switch (left) { case Literal(BOOLEAN(boolean value)): return value ? right : left; @@ -169,7 +169,7 @@ class CodeFactory extends PatternTool { return gen.mkApply_V(gen.Select(left, defs.BOOLEAN_AND()), new Tree[]{right}); } - protected Tree Or(Tree left, Tree right) { + /*protected*/ Tree Or(Tree left, Tree right) { switch (left) { case Literal(BOOLEAN(boolean value)): return value ? left : right; @@ -219,7 +219,7 @@ class CodeFactory extends PatternTool { return fun; } - protected Tree Equals(Tree left, Tree right) { + /*protected*/ public Tree Equals(Tree left, Tree right) { Type ltype = left.type.widen(), rtype = right.type.widen(); if (ltype.isSameAs(rtype) && (ltype.isSameAs(defs.CHAR_TYPE()) @@ -233,7 +233,7 @@ class CodeFactory extends PatternTool { return gen.mkApply_V(gen.Select(left, eqsym), new Tree[]{right}); } - protected Tree ThrowMatchError(int pos, Type type) { + /*protected*/ public Tree ThrowMatchError(int pos, Type type) { return gen.mkApplyTV( gen.mkGlobalRef(pos, defs.MATCHERROR_FAIL()), new Tree[]{gen.mkType(pos, type)}, @@ -243,7 +243,7 @@ class CodeFactory extends PatternTool { }); } - protected Tree ThrowMatchError(int pos, Type type, Tree tree) { + /*protected*/ public Tree ThrowMatchError(int pos, Type type, Tree tree) { return gen.mkApplyTV( gen.mkGlobalRef(pos, defs.MATCHERROR_REPORT()), new Tree[]{gen.mkType(pos, type)}, @@ -254,7 +254,7 @@ class CodeFactory extends PatternTool { }); } - protected Tree Error(int pos, Type type) { + /*protected*/ public Tree Error(int pos, Type type) { return gen.mkApplyTV( gen.mkGlobalRef(pos, defs.MATCHERROR_FAIL()), new Tree[]{gen.mkType(pos, type)}, @@ -269,7 +269,7 @@ class CodeFactory extends PatternTool { return defs.TUPLE_TYPE(new Type[] { left, right } ); } - Tree newPair( Tree left, Tree right ) { + public Tree newPair( Tree left, Tree right ) { return gen.New(gen.mkApplyTV( gen.mkPrimaryConstructorGlobalRef( pos, defs.TUPLE_CLASS[2]), new Type[] { left.getType(), right.getType() }, new Tree[] { left, right })); diff --git a/sources/scalac/transformer/matching/CollectVariableTraverser.java b/sources/scalac/transformer/matching/CollectVariableTraverser.java index 207eeea419..d030733924 100644 --- a/sources/scalac/transformer/matching/CollectVariableTraverser.java +++ b/sources/scalac/transformer/matching/CollectVariableTraverser.java @@ -7,7 +7,7 @@ import scalac.symtab.Symbol ; import java.util.HashSet; -class CollectVariableTraverser extends VariableTraverser { +public class CollectVariableTraverser extends VariableTraverser { protected HashSet nogeneratedVars; protected HashSet vars; @@ -29,7 +29,7 @@ class CollectVariableTraverser extends VariableTraverser { this.nogeneratedVars = new HashSet(); } - static boolean containsBinding( Tree pat ) { + public boolean containsBinding( Tree pat ) { CollectVariableTraverser cvt = new CollectVariableTraverser(); cvt.traverse( pat ); @@ -37,10 +37,9 @@ class CollectVariableTraverser extends VariableTraverser { } - static HashSet collectVars( Tree pat ) { - CollectVariableTraverser cvt = new CollectVariableTraverser(); - cvt.traverse( pat ); - return cvt.vars; + public HashSet collectVars( Tree pat ) { + traverse( pat ); + return vars; } } diff --git a/sources/scalac/transformer/matching/DetWordAutom.java b/sources/scalac/transformer/matching/DetWordAutom.java index 7691715623..c7d3487583 100644 --- a/sources/scalac/transformer/matching/DetWordAutom.java +++ b/sources/scalac/transformer/matching/DetWordAutom.java @@ -20,7 +20,7 @@ public class DetWordAutom { protected HashSet labels; /** the set of final states, here as a TreeMap */ - protected TreeMap finals; + /*protected*/ public TreeMap finals; /** dfa: HashMap trans: Object -> Integer * nfa: HashMap trans: Object -> Vector [ Integer ] @@ -161,7 +161,7 @@ public class DetWordAutom { return defaultq( i ) != NODEFAULT; } - void determinize( NondetWordAutom nfa ) { + public void determinize( NondetWordAutom nfa ) { //System.out.println("DetWordAutom:determinize"); //System.out.println("nfa:");nfa.print(); TreeSet states;// temp: Set[Set[Integer]] @@ -344,21 +344,21 @@ public class DetWordAutom { /** for a set of nfa states (that must exist), returns its transitions */ - HashMap deltaq( TreeSet nset ) { + public HashMap deltaq( TreeSet nset ) { return deltaq( (Integer) indexMap.get( nset ) ); } /** for a set of nfa states (that must exist), returns its transitions */ - Integer defaultq( TreeSet nset ) { + public Integer defaultq( TreeSet nset ) { return defaultq( (Integer) indexMap.get( nset ) ); } /** returns target of the transition from state i with label label. * null if no such transition exists. */ - Integer delta( int i, Label label ) { + public Integer delta( int i, Label label ) { Integer target; switch( label ) { case DefaultLabel: @@ -376,7 +376,7 @@ public class DetWordAutom { } } - Integer delta( Integer i, Label label ) { + public Integer delta( Integer i, Label label ) { return delta( i.intValue(), label ); } diff --git a/sources/scalac/transformer/matching/LeftTracerInScala.java b/sources/scalac/transformer/matching/LeftTracerInScala.java deleted file mode 100644 index 6e7c426c39..0000000000 --- a/sources/scalac/transformer/matching/LeftTracerInScala.java +++ /dev/null @@ -1,239 +0,0 @@ -package scalac.transformer.matching ; - -import scalac.*; -import scalac.ast.*; -import scalac.symtab.*; -import Tree.*; -import scalac.util.Name; -import scalac.util.Names; - -import java.util.* ; - -import scala.tools.util.Position; - -public class LeftTracerInScala extends TracerInScala { - - Tree selector; - - /** symbol of the accumulator ( scala.SequenceList ) - */ - Symbol accumSym; - Type accumType; - Type accumTypeArg; - - Type _accumType( Type elemType ) { - return cf.SeqTraceType( elemType ); - } - - public LeftTracerInScala( DetWordAutom dfa, - Type elementType, - Symbol owner, - Tree selector, - CodeFactory cf ) { - - super( dfa, elementType, owner, cf ); - this.selector = selector; - } - - protected void initializeSyms() { - this.funSym = owner.newLabel( pos, - cf.fresh.newName( "left" )); - - this.iterSym = owner.newVariable( pos, - Modifiers.MUTABLE, - cf.fresh.newName( "iter" )) - .setType( cf._seqIterType( elementType ) ) ; - - this.stateSym = owner.newVariable( pos, - Modifiers.MUTABLE, - cf.fresh.newName( "q" )) - .setType( defs.int_TYPE() ) ; - - this.accumType = _accumType( elementType ); - this.accumTypeArg = accumType.typeArgs()[0]; - this.accumSym = owner.newVariable( pos, // accumulator - Modifiers.MUTABLE, - cf.fresh.newName( "acc" )) - .setType( accumType ); - - //this.funSym - // .setType( new Type.MethodType( new Symbol[] { - // accumSym, iterSym, stateSym}, - // accumType)); - - this.funSym - .setType( new Type.MethodType( new Symbol[] { // dummy symbol MethodType - funSym.newVParam( pos, 0, cf.fresh.newName( "q" ), defs.int_TYPE()), - funSym.newVParam( pos, 0, cf.fresh.newName( "acc" ), accumType ) }, - accumType)); // result type = List[T] - - this.resultSym = owner.newVariable(pos, - 0, - cf.fresh.newName("trace")) - .setType( accumType ) ; - - this.curSym = owner.newVariable( pos, 0, CURRENT_ELEM ) - .setType( elementType ); - - this.hasnSym = owner.newVariable( pos, 0, HASNEXT ) - .setType( defs.boolean_TYPE() ); - - } - - /* should throw an exception here really, e.g. MatchError - */ - Tree code_fail() { - return gen.Ident( accumSym.pos, accumSym ); - } - - /** returns translation of transition with label from i. - * returns null if there is no such transition(no translation needed) - */ - Tree code_delta( int i, Label label ) { - Integer target = dfa.delta( i, label ); - - /* - System.out.println("LeftTracer:calling dfa.delta("+i+","+label+")"); - System.out.println("result: "+target); - */ - if( target == null ) - return null; - - // (optimization) that one is a dead state (does not make sense for tracer) - /* - if( target == dfa.nstates - 1 ) - return code_fail(); - */ - - /* - Tree newAcc = cf.newSeqTraceCons(new Integer(i), - currentElem(), - _ref( accumSym )); - */ - Tree hd = cf.newPair( gen.mkIntLit(cf.pos, i), currentElem() ); - Tree newAcc = gen.mkNewCons( cf.pos, - accumTypeArg, - hd, - gen.Ident( cf.pos, accumSym )); - - //return callFun( new Tree[] { newAcc , _iter(), gen.mkIntLit( cf.pos, target )} ); - return callFun( new Tree[] { gen.mkIntLit( cf.pos, target.intValue() ), newAcc } ); - } - - - public Tree code_body() { - - Tree body = code_error(); // never reached at runtime. - - // state [ nstates-1 ] is the dead state, so we skip it - - //`if( state == q ) <code_state> else {...}' - for( int i = dfa.nstates-2; i >= 0; i-- ) { - body = code_state( i, body ); - } - - return loadCurrentElem( body ); - - } - - /** return code for state i of the dfa SAME AS IN SUPER, ONLY SINK IS GONE - */ - Tree code_state( int i, Tree elseBody ) { - - Tree runFinished; // holds result of the run - int finalSwRes; - - runFinished = run_finished( i ); - - Tree stateBody ; // action(delta) for one particular label/test - - // default action (fail if there is none) - - stateBody = code_delta( i, Label.DefaultLabel); - - if( stateBody == null ) - stateBody = code_fail(); - // transitions of state i - - HashMap trans = ((HashMap[])dfa.deltaq)[ i ]; - - for( Iterator labs = ((HashMap)dfa.deltaq( i )).keySet().iterator(); - labs.hasNext() ; ) { - Object label = labs.next(); - Integer next = (Integer) trans.get( label ); - - Tree action = code_delta( i, (Label) label ); - - if( action != null ) { - stateBody = gen.If( currentMatches((Label) label), - action, - stateBody); - } - } - stateBody = gen.If( cf.Negate( gen.Ident( cf.pos, hasnSym )), - runFinished, - stateBody ); - return gen.If( cf.Equals( _state(), gen.mkIntLit(cf.pos, i )), - stateBody , - elseBody ); - } - - Tree getTrace() { - - initializeSyms(); - - return cf.gen.mkBlock( cf.pos, new Tree[] { - gen.ValDef( iterSym, cf.newIterator( selector, selector.getType() )), - gen.ValDef( stateSym, gen.mkIntLit( cf.pos, 0) ), - gen.ValDef( accumSym, gen.mkNil( cf.pos )), - gen.ValDef( resultSym, - gen.LabelDef( this.funSym, - new Ident[] { - gen.Ident( pos, stateSym ), - gen.Ident( pos, accumSym ) - }, code_body() /* code_body_new ? */ ))}, - gen.Ident( cf.pos, resultSym )); - } - - // calling the AlgebraicMatcher here - Tree _cur_match( Tree pat ) { - //return gen.mkBooleanLit(cf.pos, true); - - //System.out.println("calling algebraic matcher on type:"+pat.type); - - PartialMatcher m = new PartialMatcher( owner, - currentElem(), - defs.boolean_TYPE() ); - - if( CollectVariableTraverser.containsBinding( pat )) { - switch( pat ) { - case Sequence(Tree[] pats): - return gen.mkBooleanLit(cf.pos, true); - } - } - - am.construct( m, new CaseDef[] { - cf.gen.CaseDef( pat, - gen.mkBooleanLit( cf.pos, true )), - cf.gen.CaseDef( cf.gen.Ident( pat.pos, defs.PATTERN_WILDCARD ), - gen.mkBooleanLit( cf.pos, false)) }, - false); - Tree res = am.toTree(); - return res; - } - - - /** return the accumulator + last state - */ - Tree run_finished( int state ) { - Tree hd = cf.newPair( gen.mkIntLit( cf.pos, state ), - gen.mkDefaultValue(cf.pos, - elementType)); - //System.err.println(hd.type); - return gen.mkNewCons( cf.pos, - accumTypeArg, - hd, - gen.Ident( cf.pos, accumSym )); - } - -} diff --git a/sources/scalac/transformer/matching/NondetWordAutom.java b/sources/scalac/transformer/matching/NondetWordAutom.java index ef10b5366e..20321c62bc 100644 --- a/sources/scalac/transformer/matching/NondetWordAutom.java +++ b/sources/scalac/transformer/matching/NondetWordAutom.java @@ -410,18 +410,6 @@ public class NondetWordAutom { } - /** collects variables - * @return all variables bound by this binding nfa - */ - static Set collectVariables( NondetWordAutom nfa ) { - HashSet seqVars = new HashSet(); - for( int j = 0; j < nfa.nstates; j++ ) { - if( nfa.qbinders[ j ] != null ) - seqVars.addAll( nfa.qbinders[ j ] ); - } - return seqVars; - } - /** collapses several normalized NondetWordAutom objects into one. */ diff --git a/sources/scalac/transformer/matching/PatternMatcher.java b/sources/scalac/transformer/matching/PatternMatcher.java index e7e8b72cf4..ca0b47bf2c 100644 --- a/sources/scalac/transformer/matching/PatternMatcher.java +++ b/sources/scalac/transformer/matching/PatternMatcher.java @@ -726,7 +726,7 @@ public class PatternMatcher extends PatternTool { return gen.mkBlock(selector.pos, ts, res); } - protected Tree toTree(PatternNode node) { + /*protected*/ public Tree toTree(PatternNode node) { Tree res = gen.mkBooleanLit(node.pos, false); while (node != null) switch (node) { diff --git a/sources/scalac/transformer/matching/PatternTool.java b/sources/scalac/transformer/matching/PatternTool.java index 8673e040dc..e5f9ff5cc7 100644 --- a/sources/scalac/transformer/matching/PatternTool.java +++ b/sources/scalac/transformer/matching/PatternTool.java @@ -17,25 +17,25 @@ import scalac.symtab.*; /** this class takes care of tedious stuff which has nothing to do with * matching */ -abstract class PatternTool { +public abstract class PatternTool { public static final Name RESULT_N = Name.fromString("$result"); /** the current compilation unit */ - final CompilationUnit unit; + public final CompilationUnit unit; /** the global fresh name creator */ - final FreshNameCreator fresh; + public final FreshNameCreator fresh; /** the global definitions component */ - final Definitions defs; + public final Definitions defs; /** the global tree generation component */ - final TreeGen gen; + public final TreeGen gen; // constructor public PatternTool( CompilationUnit unit ) { diff --git a/sources/scalac/transformer/matching/RightTracerInScala.java b/sources/scalac/transformer/matching/RightTracerInScala.java deleted file mode 100644 index 0a8ea356ca..0000000000 --- a/sources/scalac/transformer/matching/RightTracerInScala.java +++ /dev/null @@ -1,503 +0,0 @@ -/** - * $Id$ - */ - -package scalac.transformer.matching ; - -import scalac.*; -import scalac.ast.*; -import scalac.symtab.*; -import Tree.*; - -import java.util.* ; -import Scope.SymbolIterator; - -import scalac.util.Name ; -import scalac.util.Names ; - -import scala.tools.util.Position; - -public class RightTracerInScala extends TracerInScala { - - Set seqVars; - Set allVars; - - Set varsToExport ; - - Symbol targetSym; - - HashMap helpMap; - HashMap helpMap2 ; - TreeList helpVarDefs; - - - /** translate right tracer to code - * @param dfa determinized left tracer - * @param left nondeterm. left tracer (only needed for variables!) - * @param cf ... - * @param pat ? - * @param elementType ... - */ - public RightTracerInScala( DetWordAutom dfa, - Set seqVars, - Symbol owner, - CodeFactory cf, - Tree pat, - Type elementType ) { - super( dfa, elementType, owner, cf ); - - this.seqVars = seqVars; // HANDLE THESE GLOBALLY INSTEAD OF LOCALLY - this.allVars = CollectVariableTraverser.collectVars( pat ); - - this.varsToExport = new HashSet(); - varsToExport.addAll( allVars ); - varsToExport.removeAll( seqVars ); - - this.helpMap = new HashMap(); - - helpMap2 = new HashMap(); - helpVarDefs = new TreeList(); - - for( Iterator it = seqVars.iterator(); it.hasNext(); ) { - makeHelpVar( (Symbol) it.next() ); - } - - for( Iterator it = allVars.iterator(); it.hasNext(); ) { - Symbol varSym = (Symbol) it.next(); - if(( varSym.name.toString().indexOf("$") == -1 ) - && ( !seqVars.contains( varSym ))) { - makeHelpVar( varSym, true ); - } - } - - //System.out.println("allVars: "+allVars); - //System.out.println("seqVars: "+seqVars); - //System.out.println("helpVarDefs now: "+helpVarDefs); - - initializeSyms(); - } - - void makeHelpVar( Symbol realVar ) { - makeHelpVar( realVar, false ); - } - - /** makes a helpvar and puts mapping into helpMap, ValDef into helpVarDefs - */ - - void makeHelpVar( Symbol realVar, boolean keepType ) { - Symbol helpVar = owner.newVariable( cf.pos, - 0, - cf.fresh.newName( realVar.name - .toString()+"RTIS" )); - Tree rhs; - - //System.out.println("RTiS making helpvar : "+realVar+" -> "+helpVar); - - if( keepType ) { - helpVar.setType( realVar.type() ); - rhs = gen.mkDefaultValue( cf.pos, realVar.type() ); - } else { - helpVar.setType( defs.LIST_TYPE(elementType) ); - rhs = gen.mkNil( cf.pos ); - } - - helpMap.put( realVar, helpVar ); - helpVar.flags |= Modifiers.MUTABLE; - Tree varDef = gen.ValDef( helpVar, rhs ); - //((ValDef) varDef).kind = Kinds.VAR; - helpVarDefs.append( varDef ); - - } - - Tree prependToHelpVar( Symbol realVar, Tree elem ) { - Tree hv = refHelpVar( realVar ); - return gen.Assign( hv, gen.mkNewCons( cf.pos, elementType, elem, hv )); - /* - return cf.Block(pos, - new Tree [] { - cf.debugPrintRuntime( "ASSIGN" ), - gen.Assign( hv, cf.newSeqCons( elem, hv )) - }, defs.UNIT_TYPE()); - */ - } - - protected void initializeSyms() { - - this.funSym = owner.newLabel( pos, - cf.fresh.newName( "right" )); - - this.iterSym = owner.newVariable( pos, - Modifiers.MUTABLE, - cf.fresh.newName("iter")) - .setType( cf.SeqTraceType( elementType )); - - this.stateSym = owner.newVariable ( pos, - Modifiers.MUTABLE, - cf.fresh.newName("q")) - .setType( defs.int_TYPE() ) ; - - this.curSym = owner.newVariable( pos, - Modifiers.MUTABLE, - cf.fresh.newName("cur")) - .setType( elementType ) ; - - this.targetSym = owner.newVariable( pos, - Modifiers.MUTABLE, - cf.fresh.newName("p")) - .setType( defs.int_TYPE() ) ; - - funSym.setType( new Type.MethodType( new Symbol[] { // dummy symbol MethodType - funSym.newVParam( pos, 0, cf.fresh.newName("iter"), cf.SeqTraceType( elementType )), - funSym.newVParam( pos, 0, cf.fresh.newName( "q" ), defs.int_TYPE()) }, - defs.void_TYPE() )); // result - - } - - // load current elem and trace - Tree loadCurrentElem( Tree body ) { - return - gen.If( cf.isEmpty( _iter() ), - run_finished( 0 ), // we are done - gen.mkBlock( new Tree[] { - gen.ValDef( this.targetSym, - cf.SeqTrace_headState( gen.Ident( pos, iterSym))), - gen.ValDef( this.curSym, - cf.SeqTrace_headElem( gen.Ident( pos, iterSym )))}, - body ) - ); - } - - /** see code_state0_NEW - */ - Tree code_state0( Tree elseBody ) { // careful, map Int to Int - - return gen.If( cf.Equals( _state(), gen.mkIntLit( cf.pos, 0 )), - code_state0_NEW(), - elseBody ); - - } - - /** this one is special, we check the first element of the trace - * and choose the next state depending only on the state part - */ - Tree code_state0_NEW() { // careful, map Int to Int - - HashMap hmap = (HashMap) dfa.deltaq( 0 ); // all the initial states - - int i = 0; - final int n = hmap.keySet().size(); // all transitions defined - - TreeMap tmapTag = new TreeMap(); - TreeMap tmapBody = new TreeMap(); - for( Iterator it = hmap.keySet().iterator(); it.hasNext(); i++) { - - Integer targetL = (Integer) it.next(); - Integer targetR = (Integer) hmap.get( targetL ); - - Integer I = new Integer( i ); - tmapTag.put( targetL, I ); - tmapBody.put( I, callFun( new Tree[] { - cf.SeqTrace_tail( _iter() ), - gen.mkIntLit( cf.pos, targetR.intValue() ) })); - } - i = 0; - int[] tags = new int[ n ]; - Tree[] targets = new Tree[ n ]; - for( Iterator it = tmapTag.keySet().iterator(); it.hasNext(); i++) { - Integer tagI = (Integer) it.next(); - tags[ i ] = tagI.intValue(); - Integer I = (Integer) tmapTag.get( tagI ); - targets[ i ] = (Tree) tmapBody.get( I ); - } - return gen.Switch( gen.Ident( pos, targetSym ), - tags, - targets, - code_error()/*cannot happen*/ ); - - } - - Tree currentMatches( Label label ) { - switch( label ) { - case Pair( Integer target, Label theLab ): - return cf.Equals( gen.mkIntLit( cf.pos, target.intValue() ), - current() ); - } - throw new ApplicationError("expected Pair label"); - } - - - Tree code_state_NEW( int i ) { // precondition i != 0 - Tree stateBody = code_delta( i, Label.DefaultLabel ); - if( stateBody == null ) - stateBody = code_error(); - HashMap trans = ((HashMap[])dfa.deltaq)[ i ]; - - TreeMap tmapTag = new TreeMap(); - TreeMap tmapBody = new TreeMap(); - int j = 0; - for( Iterator labs = dfa.labels.iterator(); labs.hasNext(); j++) { - Object label = labs.next(); - Integer next = (Integer) trans.get( label ); - - Tree action = code_delta( i, (Label) label ); - - if( action != null ) { - Integer J = new Integer( j ); - tmapTag.put( ((Label.Pair) label).state, J ); - tmapBody.put( J, action ); - - stateBody = gen.If( currentMatches((Label) label ), - action, - stateBody); - } - } - final int n = tmapTag.keySet().size(); - j = 0; - int[] tags = new int[ n ]; - Tree[] targets = new Tree[ n ]; - for( Iterator it = tmapTag.keySet().iterator(); it.hasNext(); j++) { - Integer tagI = (Integer) it.next(); - tags[ j ] = tagI.intValue(); - Integer J = (Integer) tmapTag.get( tagI ); - targets[ j ] = (Tree) tmapBody.get( J ); - } - if( n > 0 ) { - return gen.Switch( gen.Ident( pos, targetSym ), tags, targets, code_error() ); - } else - return code_error(); - } - - // calling the AlgebraicMatcher here - Tree _cur_match( Tree pat ) { - - //System.out.println("RTiS._cur_match("+pat.toString()+")"); - //System.out.println("calling algebraic matcher on type:"+pat.type); - - //System.err.println( "curT"+currentElem().type().widen() ); - PartialMatcher m = new PartialMatcher( owner,//funSym,//this.funSym, - currentElem(), - defs.boolean_TYPE() ); - - final HashMap freshenMap = new HashMap(); // sym2exp -> new sym - HashMap helpMap3 = new HashMap(); // new sym -> original sym - - // "freshening": never use the same symbol more than once - // (in later invocations of _cur_match) - - for( Iterator it = varsToExport.iterator(); it.hasNext(); ) { - Symbol key = (Symbol) it.next(); - if( key.name.toString().indexOf("$") == -1 ) { - this.helpMap2.put( key, helpMap.get( key )); - // "freshening" by appending string ( a bit dangerous ) - Symbol newSym = key.cloneSymbol().setOwner( owner /*funSym*/ ); - newSym.name = Name.fromString( key.name + "%" ); - freshenMap.put( key, newSym ); - helpMap3.put( newSym, helpMap.get( key )); - //System.out.println( "key: "+ key + " key.owner:"+key.owner()); - //System.out.println( "newsym owner:"+newSym.owner()); - } else { - freshenMap.put( key, key ); - } - } - - //System.out.println("RightTracerInScala:: -pat :"+pat.toString()); - /* -System.out.println("RightTracerInScala - the seqVars"+seqVars); - System.out.println("RightTracerInScala - the varsToExport"+varsToExport); - */ - //System.out.println("RightTracerInScala::freshenMap :"+freshenMap); - - // "freshening" - - /* TEST - */ - TreeCloner tc = new TreeCloner( cf.unit.global, freshenMap, Type.IdMap ); - - /* - Transformer tc = new Transformer(cf.unit.global) { - public Tree transform(Tree tree) { - tree = super.transform(tree); - if (tree.hasSymbol()) { - Object symbol = freshenMap.get(tree.symbol()); - if (symbol != null) tree.setSymbol((Symbol)symbol); - } - return tree; - } - }; - */ - pat = tc.transform( pat ); - - - //System.out.println("RightTracerInScala:: -pat( after subst ) :"+pat); - - - // val match { case <pat> => { <do binding>; true } - // case _ => false - - - Tree ts[] = new Tree[ helpMap3.keySet().size() ]; - int j = 0; - for( Iterator it = helpMap3.keySet().iterator(); it.hasNext(); ) { - Symbol vsym = (Symbol) it.next(); - Symbol hv = (Symbol) helpMap3.get( vsym ); - //hv.setType( defs.LIST_TYPE( elementType ) ) ; DEBUG ALARM ? - Tree refv = gen.Ident(cf.pos, vsym); - Tree refhv = gen.Ident(cf.pos, hv); - ts[ j++ ] = gen.Assign( refhv, refv ); - // System.out.println( "the assign" + res[ j - 1 ] ); - } - - Tree res = gen.mkBooleanLit( cf.pos, true ); // just `true' - Tree theBody = gen.mkBlock(ts, res); - - am.construct( m, new CaseDef[] { - - - cf.gen.CaseDef( pat, // if tree val matches pat -> update vars, return true - theBody/* "freshening */), - cf.gen.CaseDef( cf.gen.Ident( pat.pos, defs.PATTERN_WILDCARD ), - gen.mkBooleanLit( pat.pos, false )) }, // else return false - true // do binding please - ); - - return am.toTree(); - } - - /** returns translation of transition with label from i. - * returns null if there is no such transition(no translation needed) - */ - Tree code_delta( int i, Label label ) { - HashMap hmap = (HashMap) dfa.deltaq( i ); - Integer ntarget = (Integer) hmap.get( label ); - Tree algMatchTree = null; - if( ntarget == null ) - return null; - - //System.out.println("delta("+i+","+label+")" ); - Label theLab = null; - switch(label) { - case Label.Pair( Integer state, Label lab2 ): - //assert ntarget == state; - theLab = lab2; - switch( lab2 ) { - case TreeLabel( Tree pat ): - algMatchTree = _cur_match( pat ); - break; - } - break; - case DefaultLabel: - throw new ApplicationError(); // should not happen - } - assert dfa.qbinders != null : "qbinders ?"; - - Vector vars = dfa.qbinders[ i ]; - - //System.out.println("dfa.qbinders[ i ]"+vars); - - if( vars == null ) vars = new Vector(); // TODO: make this more consistent - assert vars != null; - - Tree stms[] = new Tree[ vars.size() - + ((algMatchTree != null )? 1 : 0 ) ]; - int j = 0; - for( Iterator it = vars.iterator(); it.hasNext(); ) { - Symbol var = (Symbol) it.next(); - - Tree rhs = gen.Ident( pos, curSym ); - - stms[ j++ ] = prependToHelpVar( var , rhs); - } - - if( algMatchTree != null ) - stms[ j++ ] = algMatchTree ; - - Tree value = callFun( new Tree[] { cf.SeqTrace_tail( _iter() ), - gen.mkIntLit( cf.pos, ntarget.intValue() ) } ); - - return gen.mkBlock( pos, stms, value ); - } - - Tree stateWrap(int i) { - if( i == 0 ) - return code_state0_NEW(); - return code_state_NEW( i ); - } - - /* returns statements that do the work of the right-transducer - */ - Tree getStms( Tree trace, CompilationUnit unit, Tree body ) { - - TreeList stms = new TreeList(); - Tree loopbody = code_body_NEW(); - - stms.append( gen.ValDef( iterSym, trace ) ); - stms.append( gen.ValDef( stateSym, gen.mkIntLit( cf.pos, 0 ) ) ); - stms.append( helpVarDefs ); - stms.append( gen.LabelDef( this.funSym, - new Ident[] { - gen.Ident( pos, iterSym ), - gen.Ident( pos, stateSym ) - }, loopbody )); - - // bind variables handled by this righttracer - for( Iterator it = seqVars.iterator(); it.hasNext(); ) { - stms.append( bindVar( (Symbol) it.next() ) ); - } - - Transformer treeCloner = new Transformer(unit.global) { - public Tree transform(Tree tree) { - tree = super.transform(tree); - if (tree.hasSymbol()) { - Object symbol = helpMap2.get(tree.symbol()); - if (symbol != null) tree.setSymbol((Symbol)symbol); - } - return tree; - } - }; - - return gen.mkBlock(stms.toArray(), treeCloner.transform( body )); - } - - - - /** return the accumulator. (same as in LeftTracerInScala) - * todo: move tree generation of Unit somewhere else - */ - Tree run_finished( int state ) { - return gen.mkUnitLit(Position.FIRSTPOS); - } - - Tree current() { return gen.Ident( pos, targetSym );} - - Tree refHelpVar( Symbol realVar ) { - Symbol hv = (Symbol)helpMap.get( realVar ); - assert hv != null : realVar; - return gen.Ident(Position.FIRSTPOS, hv); - } - - Tree assignToHelpVar( Symbol realVar, Tree rhs ) { - Tree hv = refHelpVar( realVar ); - return gen.Assign( hv, rhs ); - } - - Tree bindVar(Symbol realVar) { - Tree hv = refHelpVar( realVar ); - /* - System.out.println("binding realVar.name "+realVar.name+" type:"+realVar.type()+" to hv type:"+hv.type()); - realVar.setOwner( owner ); - System.out.println("is same as realVar"+realVar.type().isSameAs( elementType )); - System.out.println("is same as hv"+realVar.type().isSameAs( hv.type() )); - if( realVar.type().isSameAs( elementType )) - return gen.ValDef( realVar, cf.SeqList_head( hv )); - else - return gen.ValDef( realVar, hv ); - */ - if( realVar.type().isSameAs( hv.getType())) { - return gen.ValDef( realVar, hv ); // e.g. x @ _* - } - return gen.ValDef( realVar, cf.SeqList_head( hv )); - - } - - -} diff --git a/sources/scalac/transformer/matching/SequenceMatcher.java b/sources/scalac/transformer/matching/SequenceMatcher.java deleted file mode 100644 index 8b553e3c25..0000000000 --- a/sources/scalac/transformer/matching/SequenceMatcher.java +++ /dev/null @@ -1,155 +0,0 @@ -package scalac.transformer.matching ; - -import scalac.*; -import scalac.ast.Tree; -import Tree.*; - - //import scala.compiler.printer.XMLAutomPrinter ; // DEBUGGING\ - -import scalac.ast.* ; -import scalac.symtab.* ; - -import java.util.* ; - -import scala.tools.util.Position; - -/** constructs a matcher for a sequence pattern. plays two roles in - * described in design pattern Builder. - * is the "Director" for "Builder" class BerrySethi. - * is the "Builder" for "Director" class TransMatch. - */ - -public class SequenceMatcher extends PatternTool { - - final static Integer IGNORED = new Integer(42); - CodeFactory cf; - - PartialMatcher _m; - - BindingBerrySethi bbuild = null; - - /** translates the det/switching automaton to scala code - * precondition: pat.type() corresponds to element type - */ - Tree addBinderToBody( Tree pat, Tree body ) { - if( bbuild == null ) - bbuild = new BindingBerrySethi(unit); - - Type elementType = cf.getElemType_Sequence( pat.getType() ); - - // (a) build *binding* nfa (sequential machine) - NondetWordAutom left = bbuild.automatonFrom( pat, IGNORED ); - NondetWordAutom right = bbuild.revnfa; - - // (b) determinize + translate L - - DetWordAutom dLeft = new DetWordAutom( left ); - - LeftTracerInScala ltis = - new LeftTracerInScala( dLeft, elementType, _m.owner, _m.selector, cf); - - Tree trace = ltis.getTrace(); - - // (c) determinize + translate R - - DetWordAutom dRight = new DetWordAutom( right, left, dLeft ); - - Set seqVars = NondetWordAutom.collectVariables( left ); - //System.out.println("seqVars here are:"+seqVars); - final RightTracerInScala rtis = - new RightTracerInScala( dRight, seqVars, _m.owner, - cf, pat, elementType ); - - // !!! Tree stms2 = rtis.getStms( theTrace, unit, body ); - // !!! gen.mkBlock_( body.pos, trace, stms2 ); - Tree stms2 = rtis.getStms( trace, unit, body ); - return stms2; - } - - private NondetWordAutom[] buildNfas( Tree[] pat ) { - BerrySethi build = new BerrySethi(unit); - NondetWordAutom manyNfa[] = new NondetWordAutom[ pat.length ]; - - for( int i = 0; i < pat.length; i++ ) { - manyNfa[ i ] = build.automatonFrom( pat[ i ], - new Integer( i )); - //manyNfa[ i ].print(); - } - return manyNfa; - } - - /** constructs a word recognizer from an array of patterns which - * should all be SequencePatterns ( no wildcard * ) - * precondition: pat.type corresponds to element type - * @param _m Matcher object, holds the result - * @param pat the (Sequence) patterns - * @param body the bodies - * @param defaultCase code that is run when nothing matches. may be null, it - * becomes a ThrowMatchError then - * @param doBinding flasg that indicates whether variables should be bound - */ - public void construct( PartialMatcher _m, - Tree[] pat, - Tree[] body, - Tree defaultCase, - boolean doBinding ) { - this._m = _m; - assert body.length == pat.length; - if( defaultCase == null ) - defaultCase = cf.ThrowMatchError( cf.pos, _m.resultType ); - - this.cf = new CodeFactory( unit, _m.pos ); - - Type seqType = pat[ 0 ].getType(); - Type elementType = cf.getElemType_Sequence( seqType ); - - // STEP 1 - build nfas for each pattern - - NondetWordAutom manyNfa[] = buildNfas( pat ); - - // STEP 2 - recognizing - - // (a) merge nfas into one if necessary - NondetWordAutom nfa = - (pat.length > 1) ? new NondetWordAutom( manyNfa ) - : manyNfa[ 0 ]; - //nfa.print(); - - // (b) determinize - DetWordAutom dfa = new DetWordAutom( nfa ); - - // (c) translate to scala code - WordAutomInScala scalaAut = - new WordAutomInScala( dfa, - elementType, - _m.owner, - cf, - unit.global.target == Global.TARGET_JVM ); - scalaAut.translate(); - - // STEP 3 - binding - - Tree newbody[]; - if( !doBinding ) - newbody = body; - else { // this is done in the body of the matching case - newbody = new Tree[body.length]; - for( int i = 0; i < body.length; i++ ) - if( !CollectVariableTraverser.containsBinding( pat[ i ] ) ) - newbody[ i ] = body[ i ]; // no need for binding - else - newbody[ i ] = addBinderToBody( pat[ i ], body[ i ] ); - } - - _m.tree = scalaAut.getMatcherSwitch( _m.selector, - defaultCase, - newbody, - _m.resultType ); - } // construct (PartialMatcher, Tree[], Tree[], Tree, boolean ) - - /** constructor, invoked by AlgebraicMatcher - */ - SequenceMatcher( CompilationUnit unit ) { - super( unit ); - } -} // class SequenceMatcher diff --git a/sources/scalac/transformer/matching/TracerInScala.java b/sources/scalac/transformer/matching/TracerInScala.java deleted file mode 100644 index d5d4177b40..0000000000 --- a/sources/scalac/transformer/matching/TracerInScala.java +++ /dev/null @@ -1,22 +0,0 @@ -package scalac.transformer.matching ; - -import scalac.symtab.Symbol; -import scalac.symtab.Type; - -/** 2do: factor common things of LeftTracerInScala and RightTracerInScala - */ -public class TracerInScala extends Autom2Scala { - - protected boolean optimize = true; - - - public TracerInScala( DetWordAutom dfa, - Type elementType, - Symbol ownerSym, - CodeFactory cf ) { - super( dfa, elementType, ownerSym, cf ); - - } - -} - diff --git a/sources/scalac/transformer/matching/WordAutomInScala.java b/sources/scalac/transformer/matching/WordAutomInScala.java deleted file mode 100644 index a8b2413c9c..0000000000 --- a/sources/scalac/transformer/matching/WordAutomInScala.java +++ /dev/null @@ -1,175 +0,0 @@ -/* ____ ____ ____ ____ ______ *\ -** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala ** -** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL ** -** /_____/\____/\___/\____/____/ ** -\* */ - -// $Id$ - -package scalac.transformer.matching; - -import scala.tools.util.Position; - -import scalac.*; -import scalac.ast.Tree; -import scalac.ast.TreeGen; -import scalac.symtab.Type; -import scalac.symtab.Symbol; -import scalac.symtab.Modifiers; // test -//import scalac.typechecker.*; -import Tree.*; - -import java.util.*; - - -/** translates a recognizer to scala code - */ -public class WordAutomInScala extends Autom2Scala { - - Tree theDefDef ; - - Tree getMatcherSwitch(Tree selector, - Tree failTree, - Tree body[], - Type resultType) { - - Tree result; - - /* - boolean insane = true; // if you set this to false, you get some VerifyErrors - // seems fixed - if( insane ) { // cascading ifs - - Tree cond[] = new Tree[body.length]; - for( int i = body.length - 1; i >= 0; i-- ) { - cond[i] = cf.Equals(_swres(), gen.mkIntLit( cf.pos, i )); - } - result = cf.Switch( cond, body, failTree ); - - } else { // real switch - */ - int tags[] = new int[body.length]; - for( int i = body.length - 1; i >= 0; i-- ) { - tags[i] = i; - } - result = gen.Switch( _swres(), tags, body, failTree ); - - //} - - result = cf.gen.mkBlock( cf.pos, new Tree[] { - gen.ValDef( iterSym, cf.newIterator( selector )), - gen.ValDef( stateSym, gen.mkIntLit( cf.pos, 0) ), - gen.ValDef( resultSym, theDefDef )}, - result ); - //unit.global.debugPrinter.print( result ); - return result; - } - - protected void initializeSyms() { // TEST - - this.funSym = owner.newLabel( pos, - cf.fresh.newName( "matcher" )); - - this.iterSym = owner.newVariable( pos, - Modifiers.MUTABLE, - cf.fresh.newName("iter")) - .setType( cf._seqIterType( elementType ) ) ; - - this.stateSym = owner.newVariable( pos, - Modifiers.MUTABLE, - cf.fresh.newName("q")) - .setType( defs.int_TYPE() ) ; - - this.resultSym = owner.newVariable( pos, - Modifiers.MUTABLE, - cf.fresh.newName("swRes")) - .setType( defs.int_TYPE() ) ; - - this.funSym - .setType( new Type.MethodType( new Symbol[] { - funSym.newVParam( pos, 0, cf.fresh.newName("q"), defs.int_TYPE()) - }, defs.int_TYPE() )); - - this.curSym = owner.newVariable( pos, 0, CURRENT_ELEM ) - .setType( elementType ); - - this.hasnSym = owner.newVariable( pos, 0, HASNEXT ) - .setType( defs.boolean_TYPE() ); - - } - - /** code for the return value of the automaton translation - */ - Tree run_finished( int state ) { // T E S T - if( dfa.isFinal( state )) { - return gen.mkIntLit(Position.FIRSTPOS, ((Integer) dfa.finals.get( new Integer( state ) )).intValue() ); - } - return gen.mkIntLit( Position.FIRSTPOS, FAIL ); - } - - - // calling the /*AlgebraicMatcher*/PatternMatcher here - Tree _cur_match( Tree pat ) { // TE ST - PartialMatcher m = new PartialMatcher( this.owner, /* owner*/ - currentElem(), /* root */ - defs.boolean_TYPE() /* restype */); - - am.construct( m, new CaseDef[] { - cf.gen.CaseDef( pat, - gen.mkBooleanLit( pat.pos, true )), - cf.gen.CaseDef( cf.gen.Ident(pat.pos, defs.PATTERN_WILDCARD), - gen.mkBooleanLit( pat.pos, false )) }, - false); - return am.toTree(); - } - - - /** do the translation - */ - public void translate() { - initializeSyms(); - Tree tb = code_body_NEW(); - //theDefDef = gen.DefDef(this.funSym, tb); - theDefDef = gen.LabelDef(this.funSym, new Ident[] { /*(Ident)_iter(),*/ (Ident)_state() }, tb); - } - - /** ... - * @return returns translation of transition with label from i. - * returns null if there is no such transition - * (no translation needed) - */ - Tree code_delta(int i, Label label) { - Integer target = dfa.delta(i, label); - - if (target == null) - switch (label) { - case DefaultLabel: - return code_error(); // this may not happen ! - default: - return null; // not good - } - else if (target.intValue() == dfa.nstates - 1) // that one is a dead state - return code_fail(); - - return callFun(new Tree[] { gen.mkIntLit( cf.pos, target.intValue() )} ); - } - - /** constructor - * @param dfa the dfa that is to be translated - * @param elementType type of the objects in the sequence - * @param owner the owner of the pattern match - * @param cf code factory - * @param optim flag that indicates whether to optimize - * @return an object that translates the dfa - */ - public WordAutomInScala(DetWordAutom dfa, - Type elementType, - Symbol owner, - CodeFactory cf, - boolean optim) { - super(dfa, elementType, owner, cf); - this.optimize &= optim; - - } - -} |