Exemplo n.º 1
0
    def __init__(self, adaptor=None, tokenNames=None, typeMap=None):
        if adaptor is None:
            self.adaptor = CommonTreeAdaptor()

        else:
            self.adaptor = adaptor

        if typeMap is None:
            self.tokenNameToTypeMap = computeTokenTypes(tokenNames)

        else:
            if tokenNames is not None:
                raise ValueError("Can't have both tokenNames and typeMap")

            self.tokenNameToTypeMap = typeMap
Exemplo n.º 2
0
    def testTreeVisitor(self):
        tree = "(PRINT (MULT ID[x] (VEC (MULT INT[9] INT[1]) INT[2] INT[3])))"
        adaptor = CommonTreeAdaptor()
        wiz = TreeWizard(adaptor, self.tokenNames)
        t = wiz.create(tree)

        found = []

        def pre(t):
            found.append("pre({})".format(t))
            return t

        def post(t):
            found.append("post({})".format(t))
            return t

        visitor = TreeVisitor(adaptor)
        visitor.visit(t, pre, post)

        expecting = [
            "pre(PRINT)", "pre(MULT)", "pre(x)", "post(x)", "pre(VEC)",
            "pre(MULT)", "pre(9)", "post(9)", "pre(1)", "post(1)",
            "post(MULT)", "pre(2)", "post(2)", "pre(3)", "post(3)",
            "post(VEC)", "post(MULT)", "post(PRINT)"
        ]

        self.assertEqual(expecting, found)
Exemplo n.º 3
0
 def testComplex(self):
     adaptor = CommonTreeAdaptor()
     wiz = TreeWizard(adaptor, self.tokens)
     t = wiz.create("(A (B (C D E) F) G)")
     it = TreeIterator(t)
     expecting = "A DOWN B DOWN C DOWN D E UP F UP G UP EOF"
     found = self.toString(it)
     self.assertEqual(expecting, found)
Exemplo n.º 4
0
 def testVerticalList(self):
     adaptor = CommonTreeAdaptor()
     wiz = TreeWizard(adaptor, self.tokens)
     t = wiz.create("(A (B C))")
     it = TreeIterator(t)
     expecting = "A DOWN B DOWN C UP UP EOF"
     found = self.toString(it)
     self.assertEqual(expecting, found)
Exemplo n.º 5
0
 def testFlatAB(self):
     adaptor = CommonTreeAdaptor()
     wiz = TreeWizard(adaptor, self.tokens)
     t = wiz.create("(nil A B)")
     it = TreeIterator(t)
     expecting = "nil DOWN A B UP EOF"
     found = self.toString(it)
     self.assertEqual(expecting, found)
Exemplo n.º 6
0
 def testNode(self):
     adaptor = CommonTreeAdaptor()
     wiz = TreeWizard(adaptor, self.tokens)
     t = wiz.create("A")
     it = TreeIterator(t)
     expecting = "A EOF"
     found = self.toString(it)
     self.assertEqual(expecting, found)
Exemplo n.º 7
0
 def testABC(self):
     adaptor = CommonTreeAdaptor()
     wiz = TreeWizard(adaptor, self.tokens)
     t = wiz.create("(A B C)")
     it = TreeIterator(t)
     expecting = "A DOWN B C UP EOF"
     found = self.toString(it)
     self.assertEquals(expecting, found)
Exemplo n.º 8
0
 def parse(self, filename):
     input = antlr3.FileStream (filename)
     lexer = MonitorLexer (input)
     tokens = antlr3.CommonTokenStream (lexer)
     parser = MonitorParser (tokens)
     adaptor = CommonTreeAdaptor()
     parser.setTreeAdaptor(adaptor)
     res = parser.description ()
     return res
Exemplo n.º 9
0
    def setUp(self):
        """Setup text fixure

        We need a tree adaptor, use CommonTreeAdaptor.
        And a constant list of token names.

        """

        self.adaptor = CommonTreeAdaptor()
        self.tokens = [
            "", "", "", "", "", "A", "B", "C", "D", "E", "ID", "VAR"
            ]
Exemplo n.º 10
0
    def toDOT(self, tree, adaptor=None, treeST=_treeST, edgeST=_edgeST):
        if adaptor is None:
            adaptor = CommonTreeAdaptor()

        treeST = treeST.getInstanceOf()

        self.nodeNumber = 0
        self.toDOTDefineNodes(tree, adaptor, treeST)

        self.nodeNumber = 0
        self.toDOTDefineEdges(tree, adaptor, treeST, edgeST)
        return treeST
Exemplo n.º 11
0
    def testNoParent(self):
        tree = "(PRINT (MULT ID[x] (VEC INT[1] INT[2] INT[3])))"
        adaptor = CommonTreeAdaptor()
        wiz = TreeWizard(adaptor, self.tokenNames)
        t = wiz.create(tree)

        labels = {}
        valid = wiz.parse(t, "(%x:PRINT (MULT ID (VEC INT INT INT)))", labels)
        self.assertTrue(valid)
        node = labels.get("x")

        expecting = False
        found = TreeParser._inContext(adaptor, self.tokenNames, node, "VEC")
        self.assertEqual(expecting, found)
Exemplo n.º 12
0
    def __init__(self, adaptor=None, tokenNames=None, typeMap=None):
        if adaptor is None:
            self.adaptor = CommonTreeAdaptor()

        else:
            self.adaptor = adaptor

        if typeMap is None:
            self.tokenNameToTypeMap = computeTokenTypes(tokenNames)

        else:
            if tokenNames is not None:
                raise ValueError("Can't have both tokenNames and typeMap")

            self.tokenNameToTypeMap = typeMap
Exemplo n.º 13
0
    def testDotDot(self):
        tree = "(PRINT (MULT ID[x] (VEC (MULT INT[9] INT[1]) INT[2] INT[3])))"
        adaptor = CommonTreeAdaptor()
        wiz = TreeWizard(adaptor, self.tokenNames)
        t = wiz.create(tree)

        labels = {}
        valid = wiz.parse(t,
                          "(PRINT (MULT ID (VEC (MULT INT %x:INT) INT INT)))",
                          labels)
        self.assertTrue(valid)
        node = labels.get("x")

        self.assertRaisesRegex(ValueError, r'invalid syntax: \.\.',
                               TreeParser._inContext, adaptor, self.tokenNames,
                               node, "PRINT .. VEC")
Exemplo n.º 14
0
    def testWildcardAtStartIgnored(self):
        tree = "(nil (ASSIGN ID[x] INT[3]) (PRINT (MULT ID[x] (VEC INT[1] INT[2] INT[3]))))"
        adaptor = CommonTreeAdaptor()
        wiz = TreeWizard(adaptor, self.tokenNames)
        t = wiz.create(tree)

        labels = {}
        valid = wiz.parse(
            t,
            "(nil (ASSIGN ID[x] INT[3]) (PRINT (MULT ID (VEC INT %x:INT INT))))",
            labels)
        self.assertTrue(valid)
        node = labels.get("x")

        expecting = True
        found = TreeParser._inContext(adaptor, self.tokenNames, node, "...VEC")
        self.assertEqual(expecting, found)
Exemplo n.º 15
0
    def testDeepAndFindRoot(self):
        tree = "(PRINT (MULT ID[x] (VEC (MULT INT[9] INT[1]) INT[2] INT[3])))"
        adaptor = CommonTreeAdaptor()
        wiz = TreeWizard(adaptor, self.tokenNames)
        t = wiz.create(tree)

        labels = {}
        valid = wiz.parse(t,
                          "(PRINT (MULT ID (VEC (MULT INT %x:INT) INT INT)))",
                          labels)
        self.assertTrue(valid)
        node = labels.get("x")

        expecting = True
        found = TreeParser._inContext(adaptor, self.tokenNames, node,
                                      "PRINT ...")
        self.assertEqual(expecting, found)
Exemplo n.º 16
0
    def testMismatch(self):
        tree = "(PRINT (MULT ID[x] (VEC (MULT INT[9] INT[1]) INT[2] INT[3])))"
        adaptor = CommonTreeAdaptor()
        wiz = TreeWizard(adaptor, self.tokenNames)
        t = wiz.create(tree)

        labels = {}
        valid = wiz.parse(t,
                          "(PRINT (MULT ID (VEC (MULT INT %x:INT) INT INT)))",
                          labels)
        self.assertTrue(valid)
        node = labels.get("x")

        expecting = False
        ## missing MULT
        found = TreeParser._inContext(adaptor, self.tokenNames, node,
                                      "PRINT VEC MULT")
        self.assertEquals(expecting, found)
Exemplo n.º 17
0
    def testDotDot(self):
        tree = "(PRINT (MULT ID[x] (VEC (MULT INT[9] INT[1]) INT[2] INT[3])))"
        adaptor = CommonTreeAdaptor()
        wiz = TreeWizard(adaptor, self.tokenNames)
        t = wiz.create(tree)

        labels = {}
        valid = wiz.parse(t,
                          "(PRINT (MULT ID (VEC (MULT INT %x:INT) INT INT)))",
                          labels)
        self.assertTrue(valid)
        node = labels.get("x")

        try:
            TreeParser._inContext(adaptor, self.tokenNames, node,
                                  "PRINT .. VEC")
            self.fail()
        except ValueError, exc:
            expecting = "invalid syntax: .."
            found = str(exc)
            self.assertEquals(expecting, found)
Exemplo n.º 18
0
class TreeWizard(object):
    """
    Build and navigate trees with this object.  Must know about the names
    of tokens so you have to pass in a map or array of token names (from which
    this class can build the map).  I.e., Token DECL means nothing unless the
    class can translate it to a token type.

    In order to create nodes and navigate, this class needs a TreeAdaptor.

    This class can build a token type -> node index for repeated use or for
    iterating over the various nodes with a particular type.

    This class works in conjunction with the TreeAdaptor rather than moving
    all this functionality into the adaptor.  An adaptor helps build and
    navigate trees using methods.  This class helps you do it with string
    patterns like "(A B C)".  You can create a tree from that pattern or
    match subtrees against it.
    """

    def __init__(self, adaptor=None, tokenNames=None, typeMap=None):
        if adaptor is None:
            self.adaptor = CommonTreeAdaptor()

        else:
            self.adaptor = adaptor

        if typeMap is None:
            self.tokenNameToTypeMap = computeTokenTypes(tokenNames)

        else:
            if tokenNames is not None:
                raise ValueError("Can't have both tokenNames and typeMap")

            self.tokenNameToTypeMap = typeMap


    def getTokenType(self, tokenName):
        """Using the map of token names to token types, return the type."""

        try:
            return self.tokenNameToTypeMap[tokenName]
        except KeyError:
            return INVALID_TOKEN_TYPE


    def create(self, pattern):
        """
        Create a tree or node from the indicated tree pattern that closely
        follows ANTLR tree grammar tree element syntax:

        (root child1 ... child2).

        You can also just pass in a node: ID

        Any node can have a text argument: ID[foo]
        (notice there are no quotes around foo--it's clear it's a string).

        nil is a special name meaning "give me a nil node".  Useful for
        making lists: (nil A B C) is a list of A B C.
        """

        tokenizer = TreePatternLexer(pattern)
        parser = TreePatternParser(tokenizer, self, self.adaptor)
        return parser.pattern()


    def index(self, tree):
        """Walk the entire tree and make a node name to nodes mapping.

        For now, use recursion but later nonrecursive version may be
        more efficient.  Returns a dict int -> list where the list is
        of your AST node type.  The int is the token type of the node.
        """

        m = {}
        self._index(tree, m)
        return m


    def _index(self, t, m):
        """Do the work for index"""

        if t is None:
            return

        ttype = self.adaptor.getType(t)
        elements = m.get(ttype)
        if elements is None:
            m[ttype] = elements = []

        elements.append(t)
        for i in range(self.adaptor.getChildCount(t)):
            child = self.adaptor.getChild(t, i)
            self._index(child, m)


    def find(self, tree, what):
        """Return a list of matching token.

        what may either be an integer specifzing the token type to find or
        a string with a pattern that must be matched.

        """

        if isinstance(what, (int, long)):
            return self._findTokenType(tree, what)

        elif isinstance(what, basestring):
            return self._findPattern(tree, what)

        else:
            raise TypeError("'what' must be string or integer")


    def _findTokenType(self, t, ttype):
        """Return a List of tree nodes with token type ttype"""

        nodes = []

        def visitor(tree, parent, childIndex, labels):
            nodes.append(tree)

        self.visit(t, ttype, visitor)

        return nodes


    def _findPattern(self, t, pattern):
        """Return a List of subtrees matching pattern."""

        subtrees = []

        # Create a TreePattern from the pattern
        tokenizer = TreePatternLexer(pattern)
        parser = TreePatternParser(tokenizer, self, TreePatternTreeAdaptor())
        tpattern = parser.pattern()

        # don't allow invalid patterns
        if (tpattern is None or tpattern.isNil()
            or isinstance(tpattern, WildcardTreePattern)):
            return None

        rootTokenType = tpattern.getType()

        def visitor(tree, parent, childIndex, label):
            if self._parse(tree, tpattern, None):
                subtrees.append(tree)

        self.visit(t, rootTokenType, visitor)

        return subtrees


    def visit(self, tree, what, visitor):
        """Visit every node in tree matching what, invoking the visitor.

        If what is a string, it is parsed as a pattern and only matching
        subtrees will be visited.
        The implementation uses the root node of the pattern in combination
        with visit(t, ttype, visitor) so nil-rooted patterns are not allowed.
        Patterns with wildcard roots are also not allowed.

        If what is an integer, it is used as a token type and visit will match
        all nodes of that type (this is faster than the pattern match).
        The labels arg of the visitor action method is never set (it's None)
        since using a token type rather than a pattern doesn't let us set a
        label.
        """

        if isinstance(what, (int, long)):
            self._visitType(tree, None, 0, what, visitor)

        elif isinstance(what, basestring):
            self._visitPattern(tree, what, visitor)

        else:
            raise TypeError("'what' must be string or integer")


    def _visitType(self, t, parent, childIndex, ttype, visitor):
        """Do the recursive work for visit"""

        if t is None:
            return

        if self.adaptor.getType(t) == ttype:
            visitor(t, parent, childIndex, None)

        for i in range(self.adaptor.getChildCount(t)):
            child = self.adaptor.getChild(t, i)
            self._visitType(child, t, i, ttype, visitor)


    def _visitPattern(self, tree, pattern, visitor):
        """
        For all subtrees that match the pattern, execute the visit action.
        """

        # Create a TreePattern from the pattern
        tokenizer = TreePatternLexer(pattern)
        parser = TreePatternParser(tokenizer, self, TreePatternTreeAdaptor())
        tpattern = parser.pattern()

        # don't allow invalid patterns
        if (tpattern is None or tpattern.isNil()
            or isinstance(tpattern, WildcardTreePattern)):
            return

        rootTokenType = tpattern.getType()

        def rootvisitor(tree, parent, childIndex, labels):
            labels = {}
            if self._parse(tree, tpattern, labels):
                visitor(tree, parent, childIndex, labels)

        self.visit(tree, rootTokenType, rootvisitor)


    def parse(self, t, pattern, labels=None):
        """
        Given a pattern like (ASSIGN %lhs:ID %rhs:.) with optional labels
        on the various nodes and '.' (dot) as the node/subtree wildcard,
        return true if the pattern matches and fill the labels Map with
        the labels pointing at the appropriate nodes.  Return false if
        the pattern is malformed or the tree does not match.

        If a node specifies a text arg in pattern, then that must match
        for that node in t.
        """

        tokenizer = TreePatternLexer(pattern)
        parser = TreePatternParser(tokenizer, self, TreePatternTreeAdaptor())
        tpattern = parser.pattern()

        return self._parse(t, tpattern, labels)


    def _parse(self, t1, tpattern, labels):
        """
        Do the work for parse. Check to see if the tpattern fits the
        structure and token types in t1.  Check text if the pattern has
        text arguments on nodes.  Fill labels map with pointers to nodes
        in tree matched against nodes in pattern with labels.
	"""

        # make sure both are non-null
        if t1 is None or tpattern is None:
            return False

        # check roots (wildcard matches anything)
        if not isinstance(tpattern, WildcardTreePattern):
            if self.adaptor.getType(t1) != tpattern.getType():
                return False

            # if pattern has text, check node text
            if (tpattern.hasTextArg
                and self.adaptor.getText(t1) != tpattern.getText()):
                return False

        if tpattern.label is not None and labels is not None:
            # map label in pattern to node in t1
            labels[tpattern.label] = t1

        # check children
        n1 = self.adaptor.getChildCount(t1)
        n2 = tpattern.getChildCount()
        if n1 != n2:
            return False

        for i in range(n1):
            child1 = self.adaptor.getChild(t1, i)
            child2 = tpattern.getChild(i)
            if not self._parse(child1, child2, labels):
                return False

        return True


    def equals(self, t1, t2, adaptor=None):
        """
        Compare t1 and t2; return true if token types/text, structure match
        exactly.
        The trees are examined in their entirety so that (A B) does not match
        (A B C) nor (A (B C)).
        """

        if adaptor is None:
            adaptor = self.adaptor

        return self._equals(t1, t2, adaptor)


    def _equals(self, t1, t2, adaptor):
        # make sure both are non-null
        if t1 is None or t2 is None:
            return False

        # check roots
        if adaptor.getType(t1) != adaptor.getType(t2):
            return False

        if adaptor.getText(t1) != adaptor.getText(t2):
            return False

        # check children
        n1 = adaptor.getChildCount(t1)
        n2 = adaptor.getChildCount(t2)
        if n1 != n2:
            return False

        for i in range(n1):
            child1 = adaptor.getChild(t1, i)
            child2 = adaptor.getChild(t2, i)
            if not self._equals(child1, child2, adaptor):
                return False

        return True
Exemplo n.º 19
0
    def setUp(self):
        """Setup test fixure"""

        self.adaptor = CommonTreeAdaptor()
Exemplo n.º 20
0
class TestCommonTree(unittest.TestCase):
    """Test case for the CommonTree class."""

    def setUp(self):
        """Setup test fixure"""

        self.adaptor = CommonTreeAdaptor()

    def testSingleNode(self):
        t = CommonTree(CommonToken(101))
        self.failUnless(t.parent is None)
        self.failUnlessEqual(-1, t.childIndex)

    def test4Nodes(self):
        # ^(101 ^(102 103) 104)
        r0 = CommonTree(CommonToken(101))
        r0.addChild(CommonTree(CommonToken(102)))
        r0.getChild(0).addChild(CommonTree(CommonToken(103)))
        r0.addChild(CommonTree(CommonToken(104)))

        self.failUnless(r0.parent is None)
        self.failUnlessEqual(-1, r0.childIndex)

    def testList(self):
        # ^(nil 101 102 103)
        r0 = CommonTree(None)
        c0 = CommonTree(CommonToken(101))
        r0.addChild(c0)
        c1 = CommonTree(CommonToken(102))
        r0.addChild(c1)
        c2 = CommonTree(CommonToken(103))
        r0.addChild(c2)

        self.failUnless(r0.parent is None)
        self.failUnlessEqual(-1, r0.childIndex)
        self.failUnlessEqual(r0, c0.parent)
        self.failUnlessEqual(0, c0.childIndex)
        self.failUnlessEqual(r0, c1.parent)
        self.failUnlessEqual(1, c1.childIndex)
        self.failUnlessEqual(r0, c2.parent)
        self.failUnlessEqual(2, c2.childIndex)

    def testList2(self):
        # Add child ^(nil 101 102 103) to root 5
        # should pull 101 102 103 directly to become 5's child list
        root = CommonTree(CommonToken(5))

        # child tree
        r0 = CommonTree(None)
        c0 = CommonTree(CommonToken(101))
        r0.addChild(c0)
        c1 = CommonTree(CommonToken(102))
        r0.addChild(c1)
        c2 = CommonTree(CommonToken(103))
        r0.addChild(c2)

        root.addChild(r0)

        self.failUnless(root.parent is None)
        self.failUnlessEqual(-1, root.childIndex)
        # check children of root all point at root
        self.failUnlessEqual(root, c0.parent)
        self.failUnlessEqual(0, c0.childIndex)
        self.failUnlessEqual(root, c0.parent)
        self.failUnlessEqual(1, c1.childIndex)
        self.failUnlessEqual(root, c0.parent)
        self.failUnlessEqual(2, c2.childIndex)

    def testAddListToExistChildren(self):
        # Add child ^(nil 101 102 103) to root ^(5 6)
        # should add 101 102 103 to end of 5's child list
        root = CommonTree(CommonToken(5))
        root.addChild(CommonTree(CommonToken(6)))

        # child tree
        r0 = CommonTree(None)
        c0 = CommonTree(CommonToken(101))
        r0.addChild(c0)
        c1 = CommonTree(CommonToken(102))
        r0.addChild(c1)
        c2 = CommonTree(CommonToken(103))
        r0.addChild(c2)

        root.addChild(r0)

        self.failUnless(root.parent is None)
        self.failUnlessEqual(-1, root.childIndex)
        # check children of root all point at root
        self.failUnlessEqual(root, c0.parent)
        self.failUnlessEqual(1, c0.childIndex)
        self.failUnlessEqual(root, c0.parent)
        self.failUnlessEqual(2, c1.childIndex)
        self.failUnlessEqual(root, c0.parent)
        self.failUnlessEqual(3, c2.childIndex)

    def testDupTree(self):
        # ^(101 ^(102 103 ^(106 107) ) 104 105)
        r0 = CommonTree(CommonToken(101))
        r1 = CommonTree(CommonToken(102))
        r0.addChild(r1)
        r1.addChild(CommonTree(CommonToken(103)))
        r2 = CommonTree(CommonToken(106))
        r2.addChild(CommonTree(CommonToken(107)))
        r1.addChild(r2)
        r0.addChild(CommonTree(CommonToken(104)))
        r0.addChild(CommonTree(CommonToken(105)))

        dup = self.adaptor.dupTree(r0)

        self.failUnless(dup.parent is None)
        self.failUnlessEqual(-1, dup.childIndex)
        dup.sanityCheckParentAndChildIndexes()

    def testBecomeRoot(self):
        # 5 becomes root of ^(nil 101 102 103)
        newRoot = CommonTree(CommonToken(5))

        oldRoot = CommonTree(None)
        oldRoot.addChild(CommonTree(CommonToken(101)))
        oldRoot.addChild(CommonTree(CommonToken(102)))
        oldRoot.addChild(CommonTree(CommonToken(103)))

        self.adaptor.becomeRoot(newRoot, oldRoot)
        newRoot.sanityCheckParentAndChildIndexes()

    def testBecomeRoot2(self):
        # 5 becomes root of ^(101 102 103)
        newRoot = CommonTree(CommonToken(5))

        oldRoot = CommonTree(CommonToken(101))
        oldRoot.addChild(CommonTree(CommonToken(102)))
        oldRoot.addChild(CommonTree(CommonToken(103)))

        self.adaptor.becomeRoot(newRoot, oldRoot)
        newRoot.sanityCheckParentAndChildIndexes()

    def testBecomeRoot3(self):
        # ^(nil 5) becomes root of ^(nil 101 102 103)
        newRoot = CommonTree(None)
        newRoot.addChild(CommonTree(CommonToken(5)))

        oldRoot = CommonTree(None)
        oldRoot.addChild(CommonTree(CommonToken(101)))
        oldRoot.addChild(CommonTree(CommonToken(102)))
        oldRoot.addChild(CommonTree(CommonToken(103)))

        self.adaptor.becomeRoot(newRoot, oldRoot)
        newRoot.sanityCheckParentAndChildIndexes()

    def testBecomeRoot5(self):
        # ^(nil 5) becomes root of ^(101 102 103)
        newRoot = CommonTree(None)
        newRoot.addChild(CommonTree(CommonToken(5)))

        oldRoot = CommonTree(CommonToken(101))
        oldRoot.addChild(CommonTree(CommonToken(102)))
        oldRoot.addChild(CommonTree(CommonToken(103)))

        self.adaptor.becomeRoot(newRoot, oldRoot)
        newRoot.sanityCheckParentAndChildIndexes()

    def testBecomeRoot6(self):
        # emulates construction of ^(5 6)
        root_0 = self.adaptor.nil()
        root_1 = self.adaptor.nil()
        root_1 = self.adaptor.becomeRoot(CommonTree(CommonToken(5)), root_1)

        self.adaptor.addChild(root_1, CommonTree(CommonToken(6)))

        self.adaptor.addChild(root_0, root_1)

        root_0.sanityCheckParentAndChildIndexes()

    # Test replaceChildren

    def testReplaceWithNoChildren(self):
        t = CommonTree(CommonToken(101))
        newChild = CommonTree(CommonToken(5))
        error = False
        try:
            t.replaceChildren(0, 0, newChild)

        except IndexError:
            error = True

        self.failUnless(error)

    def testReplaceWithOneChildren(self):
        # assume token type 99 and use text
        t = CommonTree(CommonToken(99, text="a"))
        c0 = CommonTree(CommonToken(99, text="b"))
        t.addChild(c0)

        newChild = CommonTree(CommonToken(99, text="c"))
        t.replaceChildren(0, 0, newChild)
        expecting = "(a c)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceInMiddle(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))  # index 1
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChild = CommonTree(CommonToken(99, text="x"))
        t.replaceChildren(1, 1, newChild)
        expecting = "(a b x d)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceAtLeft(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))  # index 0
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChild = CommonTree(CommonToken(99, text="x"))
        t.replaceChildren(0, 0, newChild)
        expecting = "(a x c d)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceAtRight(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))  # index 2

        newChild = CommonTree(CommonToken(99, text="x"))
        t.replaceChildren(2, 2, newChild)
        expecting = "(a b c x)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceOneWithTwoAtLeft(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChildren = self.adaptor.nil()
        newChildren.addChild(CommonTree(CommonToken(99, text="x")))
        newChildren.addChild(CommonTree(CommonToken(99, text="y")))

        t.replaceChildren(0, 0, newChildren)
        expecting = "(a x y c d)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceOneWithTwoAtRight(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChildren = self.adaptor.nil()
        newChildren.addChild(CommonTree(CommonToken(99, text="x")))
        newChildren.addChild(CommonTree(CommonToken(99, text="y")))

        t.replaceChildren(2, 2, newChildren)
        expecting = "(a b c x y)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceOneWithTwoInMiddle(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChildren = self.adaptor.nil()
        newChildren.addChild(CommonTree(CommonToken(99, text="x")))
        newChildren.addChild(CommonTree(CommonToken(99, text="y")))

        t.replaceChildren(1, 1, newChildren)
        expecting = "(a b x y d)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceTwoWithOneAtLeft(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChild = CommonTree(CommonToken(99, text="x"))

        t.replaceChildren(0, 1, newChild)
        expecting = "(a x d)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceTwoWithOneAtRight(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChild = CommonTree(CommonToken(99, text="x"))

        t.replaceChildren(1, 2, newChild)
        expecting = "(a b x)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceAllWithOne(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChild = CommonTree(CommonToken(99, text="x"))

        t.replaceChildren(0, 2, newChild)
        expecting = "(a x)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceAllWithTwo(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChildren = self.adaptor.nil()
        newChildren.addChild(CommonTree(CommonToken(99, text="x")))
        newChildren.addChild(CommonTree(CommonToken(99, text="y")))

        t.replaceChildren(0, 2, newChildren)
        expecting = "(a x y)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()
Exemplo n.º 21
0
 def setUp(self):
     self.adaptor = CommonTreeAdaptor()
Exemplo n.º 22
0
class TestTreeNodeStream(unittest.TestCase):
    """Test case for the TreeNodeStream class."""

    def setUp(self):
        self.adaptor = CommonTreeAdaptor()

    def newStream(self, t):
        """Build new stream; let's us override to test other streams."""
        return CommonTreeNodeStream(t)

    def testSingleNode(self):
        t = CommonTree(CommonToken(101))

        stream = self.newStream(t)
        expecting = "101"
        found = self.toNodesOnlyString(stream)
        self.failUnlessEqual(expecting, found)

        expecting = "101"
        found = str(stream)
        self.failUnlessEqual(expecting, found)

    def testTwoChildrenOfNilRoot(self):
        class V(CommonTree):
            def __init__(self, token=None, ttype=None, x=None):
                if x is not None:
                    self.x = x

                if ttype is not None and token is None:
                    self.token = CommonToken(type=ttype)

                if token is not None:
                    self.token = token

            def __str__(self):
                if self.token is not None:
                    txt = self.token.text
                else:
                    txt = ""

                txt += "<V>"
                return txt

        root_0 = self.adaptor.nil()
        t = V(ttype=101, x=2)
        u = V(token=CommonToken(type=102, text="102"))
        self.adaptor.addChild(root_0, t)
        self.adaptor.addChild(root_0, u)
        self.assert_(root_0.parent is None)
        self.assertEquals(-1, root_0.childIndex)
        self.assertEquals(0, t.childIndex)
        self.assertEquals(1, u.childIndex)

    def test4Nodes(self):
        # ^(101 ^(102 103) 104)
        t = CommonTree(CommonToken(101))
        t.addChild(CommonTree(CommonToken(102)))
        t.getChild(0).addChild(CommonTree(CommonToken(103)))
        t.addChild(CommonTree(CommonToken(104)))

        stream = self.newStream(t)
        expecting = "101 102 103 104"
        found = self.toNodesOnlyString(stream)
        self.failUnlessEqual(expecting, found)

        expecting = "101 2 102 2 103 3 104 3"
        found = str(stream)
        self.failUnlessEqual(expecting, found)

    def testList(self):
        root = CommonTree(None)

        t = CommonTree(CommonToken(101))
        t.addChild(CommonTree(CommonToken(102)))
        t.getChild(0).addChild(CommonTree(CommonToken(103)))
        t.addChild(CommonTree(CommonToken(104)))

        u = CommonTree(CommonToken(105))

        root.addChild(t)
        root.addChild(u)

        stream = CommonTreeNodeStream(root)
        expecting = "101 102 103 104 105"
        found = self.toNodesOnlyString(stream)
        self.failUnlessEqual(expecting, found)

        expecting = "101 2 102 2 103 3 104 3 105"
        found = str(stream)
        self.failUnlessEqual(expecting, found)

    def testFlatList(self):
        root = CommonTree(None)

        root.addChild(CommonTree(CommonToken(101)))
        root.addChild(CommonTree(CommonToken(102)))
        root.addChild(CommonTree(CommonToken(103)))

        stream = CommonTreeNodeStream(root)
        expecting = "101 102 103"
        found = self.toNodesOnlyString(stream)
        self.failUnlessEqual(expecting, found)

        expecting = "101 102 103"
        found = str(stream)
        self.failUnlessEqual(expecting, found)

    def testListWithOneNode(self):
        root = CommonTree(None)

        root.addChild(CommonTree(CommonToken(101)))

        stream = CommonTreeNodeStream(root)
        expecting = "101"
        found = self.toNodesOnlyString(stream)
        self.failUnlessEqual(expecting, found)

        expecting = "101"
        found = str(stream)
        self.failUnlessEqual(expecting, found)

    def testAoverB(self):
        t = CommonTree(CommonToken(101))
        t.addChild(CommonTree(CommonToken(102)))

        stream = self.newStream(t)
        expecting = "101 102"
        found = self.toNodesOnlyString(stream)
        self.failUnlessEqual(expecting, found)

        expecting = "101 2 102 3"
        found = str(stream)
        self.failUnlessEqual(expecting, found)

    def testLT(self):
        # ^(101 ^(102 103) 104)
        t = CommonTree(CommonToken(101))
        t.addChild(CommonTree(CommonToken(102)))
        t.getChild(0).addChild(CommonTree(CommonToken(103)))
        t.addChild(CommonTree(CommonToken(104)))

        stream = self.newStream(t)
        self.failUnlessEqual(101, stream.LT(1).getType())
        self.failUnlessEqual(DOWN, stream.LT(2).getType())
        self.failUnlessEqual(102, stream.LT(3).getType())
        self.failUnlessEqual(DOWN, stream.LT(4).getType())
        self.failUnlessEqual(103, stream.LT(5).getType())
        self.failUnlessEqual(UP, stream.LT(6).getType())
        self.failUnlessEqual(104, stream.LT(7).getType())
        self.failUnlessEqual(UP, stream.LT(8).getType())
        self.failUnlessEqual(EOF, stream.LT(9).getType())
        # check way ahead
        self.failUnlessEqual(EOF, stream.LT(100).getType())

    def testMarkRewindEntire(self):
        # ^(101 ^(102 103 ^(106 107) ) 104 105)
        # stream has 7 real + 6 nav nodes
        # Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF
        r0 = CommonTree(CommonToken(101))
        r1 = CommonTree(CommonToken(102))
        r0.addChild(r1)
        r1.addChild(CommonTree(CommonToken(103)))
        r2 = CommonTree(CommonToken(106))
        r2.addChild(CommonTree(CommonToken(107)))
        r1.addChild(r2)
        r0.addChild(CommonTree(CommonToken(104)))
        r0.addChild(CommonTree(CommonToken(105)))

        stream = CommonTreeNodeStream(r0)
        m = stream.mark()  # MARK
        for _ in range(13):  # consume til end
            stream.LT(1)
            stream.consume()

        self.failUnlessEqual(EOF, stream.LT(1).getType())
        self.failUnlessEqual(UP, stream.LT(-1).getType())
        stream.rewind(m)  # REWIND

        # consume til end again :)
        for _ in range(13):  # consume til end
            stream.LT(1)
            stream.consume()

        self.failUnlessEqual(EOF, stream.LT(1).getType())
        self.failUnlessEqual(UP, stream.LT(-1).getType())

    def testMarkRewindInMiddle(self):
        # ^(101 ^(102 103 ^(106 107) ) 104 105)
        # stream has 7 real + 6 nav nodes
        # Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF
        r0 = CommonTree(CommonToken(101))
        r1 = CommonTree(CommonToken(102))
        r0.addChild(r1)
        r1.addChild(CommonTree(CommonToken(103)))
        r2 = CommonTree(CommonToken(106))
        r2.addChild(CommonTree(CommonToken(107)))
        r1.addChild(r2)
        r0.addChild(CommonTree(CommonToken(104)))
        r0.addChild(CommonTree(CommonToken(105)))

        stream = CommonTreeNodeStream(r0)
        for _ in range(7):  # consume til middle
            # System.out.println(tream.LT(1).getType())
            stream.consume()

        self.failUnlessEqual(107, stream.LT(1).getType())
        m = stream.mark()  # MARK
        stream.consume()  # consume 107
        stream.consume()  # consume UP
        stream.consume()  # consume UP
        stream.consume()  # consume 104
        stream.rewind(m)  # REWIND

        self.failUnlessEqual(107, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(UP, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(UP, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(104, stream.LT(1).getType())
        stream.consume()
        # now we're past rewind position
        self.failUnlessEqual(105, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(UP, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(EOF, stream.LT(1).getType())
        self.failUnlessEqual(UP, stream.LT(-1).getType())

    def testMarkRewindNested(self):
        # ^(101 ^(102 103 ^(106 107) ) 104 105)
        # stream has 7 real + 6 nav nodes
        # Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF
        r0 = CommonTree(CommonToken(101))
        r1 = CommonTree(CommonToken(102))
        r0.addChild(r1)
        r1.addChild(CommonTree(CommonToken(103)))
        r2 = CommonTree(CommonToken(106))
        r2.addChild(CommonTree(CommonToken(107)))
        r1.addChild(r2)
        r0.addChild(CommonTree(CommonToken(104)))
        r0.addChild(CommonTree(CommonToken(105)))

        stream = CommonTreeNodeStream(r0)
        m = stream.mark()  # MARK at start
        stream.consume()  # consume 101
        stream.consume()  # consume DN
        m2 = stream.mark()  # MARK on 102
        stream.consume()  # consume 102
        stream.consume()  # consume DN
        stream.consume()  # consume 103
        stream.consume()  # consume 106
        stream.rewind(m2)  # REWIND to 102
        self.failUnlessEqual(102, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(DOWN, stream.LT(1).getType())
        stream.consume()
        # stop at 103 and rewind to start
        stream.rewind(m)  # REWIND to 101
        self.failUnlessEqual(101, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(DOWN, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(102, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(DOWN, stream.LT(1).getType())

    def testSeek(self):
        # ^(101 ^(102 103 ^(106 107) ) 104 105)
        # stream has 7 real + 6 nav nodes
        # Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF
        r0 = CommonTree(CommonToken(101))
        r1 = CommonTree(CommonToken(102))
        r0.addChild(r1)
        r1.addChild(CommonTree(CommonToken(103)))
        r2 = CommonTree(CommonToken(106))
        r2.addChild(CommonTree(CommonToken(107)))
        r1.addChild(r2)
        r0.addChild(CommonTree(CommonToken(104)))
        r0.addChild(CommonTree(CommonToken(105)))

        stream = CommonTreeNodeStream(r0)
        stream.consume()  # consume 101
        stream.consume()  # consume DN
        stream.consume()  # consume 102
        stream.seek(7)  # seek to 107
        self.failUnlessEqual(107, stream.LT(1).getType())
        stream.consume()  # consume 107
        stream.consume()  # consume UP
        stream.consume()  # consume UP
        self.failUnlessEqual(104, stream.LT(1).getType())

    def testSeekFromStart(self):
        # ^(101 ^(102 103 ^(106 107) ) 104 105)
        # stream has 7 real + 6 nav nodes
        # Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF
        r0 = CommonTree(CommonToken(101))
        r1 = CommonTree(CommonToken(102))
        r0.addChild(r1)
        r1.addChild(CommonTree(CommonToken(103)))
        r2 = CommonTree(CommonToken(106))
        r2.addChild(CommonTree(CommonToken(107)))
        r1.addChild(r2)
        r0.addChild(CommonTree(CommonToken(104)))
        r0.addChild(CommonTree(CommonToken(105)))

        stream = CommonTreeNodeStream(r0)
        stream.seek(7)  # seek to 107
        self.failUnlessEqual(107, stream.LT(1).getType())
        stream.consume()  # consume 107
        stream.consume()  # consume UP
        stream.consume()  # consume UP
        self.failUnlessEqual(104, stream.LT(1).getType())

    def toNodesOnlyString(self, nodes):
        buf = []
        for i in range(nodes.size()):
            t = nodes.LT(i + 1)
            type = nodes.getTreeAdaptor().getType(t)
            if not (type == DOWN or type == UP):
                buf.append(str(type))

        return " ".join(buf)
Exemplo n.º 23
0
    def __init__(self, adaptor=None):
        super(TraceDebugEventListener, self).__init__()

        if adaptor is None:
            adaptor = CommonTreeAdaptor()
        self.adaptor = adaptor
Exemplo n.º 24
0
 def rulePostProcessing(self, root):
     root = CommonTreeAdaptor.rulePostProcessing(self, root)
     if root is not None:
         if root.token and root.token.type == BakefileParser.LIST_OR_CONCAT:
             root = self.filter_list_or_concat(root)
     return root
Exemplo n.º 25
0
class TreeWizard(object):
    """
    Build and navigate trees with this object.  Must know about the names
    of tokens so you have to pass in a map or array of token names (from which
    this class can build the map).  I.e., Token DECL means nothing unless the
    class can translate it to a token type.

    In order to create nodes and navigate, this class needs a TreeAdaptor.

    This class can build a token type -> node index for repeated use or for
    iterating over the various nodes with a particular type.

    This class works in conjunction with the TreeAdaptor rather than moving
    all this functionality into the adaptor.  An adaptor helps build and
    navigate trees using methods.  This class helps you do it with string
    patterns like "(A B C)".  You can create a tree from that pattern or
    match subtrees against it.
    """
    def __init__(self, adaptor=None, tokenNames=None, typeMap=None):
        if adaptor is None:
            self.adaptor = CommonTreeAdaptor()

        else:
            self.adaptor = adaptor

        if typeMap is None:
            self.tokenNameToTypeMap = computeTokenTypes(tokenNames)

        else:
            if tokenNames is not None:
                raise ValueError("Can't have both tokenNames and typeMap")

            self.tokenNameToTypeMap = typeMap

    def getTokenType(self, tokenName):
        """Using the map of token names to token types, return the type."""

        try:
            return self.tokenNameToTypeMap[tokenName]
        except KeyError:
            return INVALID_TOKEN_TYPE

    def create(self, pattern):
        """
        Create a tree or node from the indicated tree pattern that closely
        follows ANTLR tree grammar tree element syntax:

        (root child1 ... child2).

        You can also just pass in a node: ID

        Any node can have a text argument: ID[foo]
        (notice there are no quotes around foo--it's clear it's a string).

        nil is a special name meaning "give me a nil node".  Useful for
        making lists: (nil A B C) is a list of A B C.
        """

        tokenizer = TreePatternLexer(pattern)
        parser = TreePatternParser(tokenizer, self, self.adaptor)
        return parser.pattern()

    def index(self, tree):
        """Walk the entire tree and make a node name to nodes mapping.

        For now, use recursion but later nonrecursive version may be
        more efficient.  Returns a dict int -> list where the list is
        of your AST node type.  The int is the token type of the node.
        """

        m = {}
        self._index(tree, m)
        return m

    def _index(self, t, m):
        """Do the work for index"""

        if t is None:
            return

        ttype = self.adaptor.getType(t)
        elements = m.get(ttype)
        if elements is None:
            m[ttype] = elements = []

        elements.append(t)
        for i in range(self.adaptor.getChildCount(t)):
            child = self.adaptor.getChild(t, i)
            self._index(child, m)

    def find(self, tree, what):
        """Return a list of matching token.

        what may either be an integer specifzing the token type to find or
        a string with a pattern that must be matched.

        """

        if isinstance(what, (int, long)):
            return self._findTokenType(tree, what)

        elif isinstance(what, basestring):
            return self._findPattern(tree, what)

        else:
            raise TypeError("'what' must be string or integer")

    def _findTokenType(self, t, ttype):
        """Return a List of tree nodes with token type ttype"""

        nodes = []

        def visitor(tree, parent, childIndex, labels):
            nodes.append(tree)

        self.visit(t, ttype, visitor)

        return nodes

    def _findPattern(self, t, pattern):
        """Return a List of subtrees matching pattern."""

        subtrees = []

        # Create a TreePattern from the pattern
        tokenizer = TreePatternLexer(pattern)
        parser = TreePatternParser(tokenizer, self, TreePatternTreeAdaptor())
        tpattern = parser.pattern()

        # don't allow invalid patterns
        if (tpattern is None or tpattern.isNil()
                or isinstance(tpattern, WildcardTreePattern)):
            return None

        rootTokenType = tpattern.getType()

        def visitor(tree, parent, childIndex, label):
            if self._parse(tree, tpattern, None):
                subtrees.append(tree)

        self.visit(t, rootTokenType, visitor)

        return subtrees

    def visit(self, tree, what, visitor):
        """Visit every node in tree matching what, invoking the visitor.

        If what is a string, it is parsed as a pattern and only matching
        subtrees will be visited.
        The implementation uses the root node of the pattern in combination
        with visit(t, ttype, visitor) so nil-rooted patterns are not allowed.
        Patterns with wildcard roots are also not allowed.

        If what is an integer, it is used as a token type and visit will match
        all nodes of that type (this is faster than the pattern match).
        The labels arg of the visitor action method is never set (it's None)
        since using a token type rather than a pattern doesn't let us set a
        label.
        """

        if isinstance(what, (int, long)):
            self._visitType(tree, None, 0, what, visitor)

        elif isinstance(what, basestring):
            self._visitPattern(tree, what, visitor)

        else:
            raise TypeError("'what' must be string or integer")

    def _visitType(self, t, parent, childIndex, ttype, visitor):
        """Do the recursive work for visit"""

        if t is None:
            return

        if self.adaptor.getType(t) == ttype:
            visitor(t, parent, childIndex, None)

        for i in range(self.adaptor.getChildCount(t)):
            child = self.adaptor.getChild(t, i)
            self._visitType(child, t, i, ttype, visitor)

    def _visitPattern(self, tree, pattern, visitor):
        """
        For all subtrees that match the pattern, execute the visit action.
        """

        # Create a TreePattern from the pattern
        tokenizer = TreePatternLexer(pattern)
        parser = TreePatternParser(tokenizer, self, TreePatternTreeAdaptor())
        tpattern = parser.pattern()

        # don't allow invalid patterns
        if (tpattern is None or tpattern.isNil()
                or isinstance(tpattern, WildcardTreePattern)):
            return

        rootTokenType = tpattern.getType()

        def rootvisitor(tree, parent, childIndex, labels):
            labels = {}
            if self._parse(tree, tpattern, labels):
                visitor(tree, parent, childIndex, labels)

        self.visit(tree, rootTokenType, rootvisitor)

    def parse(self, t, pattern, labels=None):
        """
        Given a pattern like (ASSIGN %lhs:ID %rhs:.) with optional labels
        on the various nodes and '.' (dot) as the node/subtree wildcard,
        return true if the pattern matches and fill the labels Map with
        the labels pointing at the appropriate nodes.  Return false if
        the pattern is malformed or the tree does not match.

        If a node specifies a text arg in pattern, then that must match
        for that node in t.
        """

        tokenizer = TreePatternLexer(pattern)
        parser = TreePatternParser(tokenizer, self, TreePatternTreeAdaptor())
        tpattern = parser.pattern()

        return self._parse(t, tpattern, labels)

    def _parse(self, t1, tpattern, labels):
        """
        Do the work for parse. Check to see if the tpattern fits the
        structure and token types in t1.  Check text if the pattern has
        text arguments on nodes.  Fill labels map with pointers to nodes
        in tree matched against nodes in pattern with labels.
	"""

        # make sure both are non-null
        if t1 is None or tpattern is None:
            return False

        # check roots (wildcard matches anything)
        if not isinstance(tpattern, WildcardTreePattern):
            if self.adaptor.getType(t1) != tpattern.getType():
                return False

            # if pattern has text, check node text
            if (tpattern.hasTextArg
                    and self.adaptor.getText(t1) != tpattern.getText()):
                return False

        if tpattern.label is not None and labels is not None:
            # map label in pattern to node in t1
            labels[tpattern.label] = t1

        # check children
        n1 = self.adaptor.getChildCount(t1)
        n2 = tpattern.getChildCount()
        if n1 != n2:
            return False

        for i in range(n1):
            child1 = self.adaptor.getChild(t1, i)
            child2 = tpattern.getChild(i)
            if not self._parse(child1, child2, labels):
                return False

        return True

    def equals(self, t1, t2, adaptor=None):
        """
        Compare t1 and t2; return true if token types/text, structure match
        exactly.
        The trees are examined in their entirety so that (A B) does not match
        (A B C) nor (A (B C)).
        """

        if adaptor is None:
            adaptor = self.adaptor

        return self._equals(t1, t2, adaptor)

    def _equals(self, t1, t2, adaptor):
        # make sure both are non-null
        if t1 is None or t2 is None:
            return False

        # check roots
        if adaptor.getType(t1) != adaptor.getType(t2):
            return False

        if adaptor.getText(t1) != adaptor.getText(t2):
            return False

        # check children
        n1 = adaptor.getChildCount(t1)
        n2 = adaptor.getChildCount(t2)
        if n1 != n2:
            return False

        for i in range(n1):
            child1 = adaptor.getChild(t1, i)
            child2 = adaptor.getChild(t2, i)
            if not self._equals(child1, child2, adaptor):
                return False

        return True
Exemplo n.º 26
0
    def setUp(self):
        """Setup test fixure"""

        self.adaptor = CommonTreeAdaptor()
Exemplo n.º 27
0
class TestCommonTree(unittest.TestCase):
    """Test case for the CommonTree class."""
    def setUp(self):
        """Setup test fixure"""

        self.adaptor = CommonTreeAdaptor()

    def testSingleNode(self):
        t = CommonTree(CommonToken(101))
        self.failUnless(t.parent is None)
        self.failUnlessEqual(-1, t.childIndex)

    def test4Nodes(self):
        # ^(101 ^(102 103) 104)
        r0 = CommonTree(CommonToken(101))
        r0.addChild(CommonTree(CommonToken(102)))
        r0.getChild(0).addChild(CommonTree(CommonToken(103)))
        r0.addChild(CommonTree(CommonToken(104)))

        self.failUnless(r0.parent is None)
        self.failUnlessEqual(-1, r0.childIndex)

    def testList(self):
        # ^(nil 101 102 103)
        r0 = CommonTree(None)
        c0 = CommonTree(CommonToken(101))
        r0.addChild(c0)
        c1 = CommonTree(CommonToken(102))
        r0.addChild(c1)
        c2 = CommonTree(CommonToken(103))
        r0.addChild(c2)

        self.failUnless(r0.parent is None)
        self.failUnlessEqual(-1, r0.childIndex)
        self.failUnlessEqual(r0, c0.parent)
        self.failUnlessEqual(0, c0.childIndex)
        self.failUnlessEqual(r0, c1.parent)
        self.failUnlessEqual(1, c1.childIndex)
        self.failUnlessEqual(r0, c2.parent)
        self.failUnlessEqual(2, c2.childIndex)

    def testList2(self):
        # Add child ^(nil 101 102 103) to root 5
        # should pull 101 102 103 directly to become 5's child list
        root = CommonTree(CommonToken(5))

        # child tree
        r0 = CommonTree(None)
        c0 = CommonTree(CommonToken(101))
        r0.addChild(c0)
        c1 = CommonTree(CommonToken(102))
        r0.addChild(c1)
        c2 = CommonTree(CommonToken(103))
        r0.addChild(c2)

        root.addChild(r0)

        self.failUnless(root.parent is None)
        self.failUnlessEqual(-1, root.childIndex)
        # check children of root all point at root
        self.failUnlessEqual(root, c0.parent)
        self.failUnlessEqual(0, c0.childIndex)
        self.failUnlessEqual(root, c0.parent)
        self.failUnlessEqual(1, c1.childIndex)
        self.failUnlessEqual(root, c0.parent)
        self.failUnlessEqual(2, c2.childIndex)

    def testAddListToExistChildren(self):
        # Add child ^(nil 101 102 103) to root ^(5 6)
        # should add 101 102 103 to end of 5's child list
        root = CommonTree(CommonToken(5))
        root.addChild(CommonTree(CommonToken(6)))

        # child tree
        r0 = CommonTree(None)
        c0 = CommonTree(CommonToken(101))
        r0.addChild(c0)
        c1 = CommonTree(CommonToken(102))
        r0.addChild(c1)
        c2 = CommonTree(CommonToken(103))
        r0.addChild(c2)

        root.addChild(r0)

        self.failUnless(root.parent is None)
        self.failUnlessEqual(-1, root.childIndex)
        # check children of root all point at root
        self.failUnlessEqual(root, c0.parent)
        self.failUnlessEqual(1, c0.childIndex)
        self.failUnlessEqual(root, c0.parent)
        self.failUnlessEqual(2, c1.childIndex)
        self.failUnlessEqual(root, c0.parent)
        self.failUnlessEqual(3, c2.childIndex)

    def testDupTree(self):
        # ^(101 ^(102 103 ^(106 107) ) 104 105)
        r0 = CommonTree(CommonToken(101))
        r1 = CommonTree(CommonToken(102))
        r0.addChild(r1)
        r1.addChild(CommonTree(CommonToken(103)))
        r2 = CommonTree(CommonToken(106))
        r2.addChild(CommonTree(CommonToken(107)))
        r1.addChild(r2)
        r0.addChild(CommonTree(CommonToken(104)))
        r0.addChild(CommonTree(CommonToken(105)))

        dup = self.adaptor.dupTree(r0)

        self.failUnless(dup.parent is None)
        self.failUnlessEqual(-1, dup.childIndex)
        dup.sanityCheckParentAndChildIndexes()

    def testBecomeRoot(self):
        # 5 becomes root of ^(nil 101 102 103)
        newRoot = CommonTree(CommonToken(5))

        oldRoot = CommonTree(None)
        oldRoot.addChild(CommonTree(CommonToken(101)))
        oldRoot.addChild(CommonTree(CommonToken(102)))
        oldRoot.addChild(CommonTree(CommonToken(103)))

        self.adaptor.becomeRoot(newRoot, oldRoot)
        newRoot.sanityCheckParentAndChildIndexes()

    def testBecomeRoot2(self):
        # 5 becomes root of ^(101 102 103)
        newRoot = CommonTree(CommonToken(5))

        oldRoot = CommonTree(CommonToken(101))
        oldRoot.addChild(CommonTree(CommonToken(102)))
        oldRoot.addChild(CommonTree(CommonToken(103)))

        self.adaptor.becomeRoot(newRoot, oldRoot)
        newRoot.sanityCheckParentAndChildIndexes()

    def testBecomeRoot3(self):
        # ^(nil 5) becomes root of ^(nil 101 102 103)
        newRoot = CommonTree(None)
        newRoot.addChild(CommonTree(CommonToken(5)))

        oldRoot = CommonTree(None)
        oldRoot.addChild(CommonTree(CommonToken(101)))
        oldRoot.addChild(CommonTree(CommonToken(102)))
        oldRoot.addChild(CommonTree(CommonToken(103)))

        self.adaptor.becomeRoot(newRoot, oldRoot)
        newRoot.sanityCheckParentAndChildIndexes()

    def testBecomeRoot5(self):
        # ^(nil 5) becomes root of ^(101 102 103)
        newRoot = CommonTree(None)
        newRoot.addChild(CommonTree(CommonToken(5)))

        oldRoot = CommonTree(CommonToken(101))
        oldRoot.addChild(CommonTree(CommonToken(102)))
        oldRoot.addChild(CommonTree(CommonToken(103)))

        self.adaptor.becomeRoot(newRoot, oldRoot)
        newRoot.sanityCheckParentAndChildIndexes()

    def testBecomeRoot6(self):
        # emulates construction of ^(5 6)
        root_0 = self.adaptor.nil()
        root_1 = self.adaptor.nil()
        root_1 = self.adaptor.becomeRoot(CommonTree(CommonToken(5)), root_1)

        self.adaptor.addChild(root_1, CommonTree(CommonToken(6)))

        self.adaptor.addChild(root_0, root_1)

        root_0.sanityCheckParentAndChildIndexes()

    # Test replaceChildren

    def testReplaceWithNoChildren(self):
        t = CommonTree(CommonToken(101))
        newChild = CommonTree(CommonToken(5))
        error = False
        try:
            t.replaceChildren(0, 0, newChild)

        except IndexError:
            error = True

        self.failUnless(error)

    def testReplaceWithOneChildren(self):
        # assume token type 99 and use text
        t = CommonTree(CommonToken(99, text="a"))
        c0 = CommonTree(CommonToken(99, text="b"))
        t.addChild(c0)

        newChild = CommonTree(CommonToken(99, text="c"))
        t.replaceChildren(0, 0, newChild)
        expecting = "(a c)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceInMiddle(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))  # index 1
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChild = CommonTree(CommonToken(99, text="x"))
        t.replaceChildren(1, 1, newChild)
        expecting = "(a b x d)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceAtLeft(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))  # index 0
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChild = CommonTree(CommonToken(99, text="x"))
        t.replaceChildren(0, 0, newChild)
        expecting = "(a x c d)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceAtRight(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))  # index 2

        newChild = CommonTree(CommonToken(99, text="x"))
        t.replaceChildren(2, 2, newChild)
        expecting = "(a b c x)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceOneWithTwoAtLeft(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChildren = self.adaptor.nil()
        newChildren.addChild(CommonTree(CommonToken(99, text="x")))
        newChildren.addChild(CommonTree(CommonToken(99, text="y")))

        t.replaceChildren(0, 0, newChildren)
        expecting = "(a x y c d)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceOneWithTwoAtRight(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChildren = self.adaptor.nil()
        newChildren.addChild(CommonTree(CommonToken(99, text="x")))
        newChildren.addChild(CommonTree(CommonToken(99, text="y")))

        t.replaceChildren(2, 2, newChildren)
        expecting = "(a b c x y)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceOneWithTwoInMiddle(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChildren = self.adaptor.nil()
        newChildren.addChild(CommonTree(CommonToken(99, text="x")))
        newChildren.addChild(CommonTree(CommonToken(99, text="y")))

        t.replaceChildren(1, 1, newChildren)
        expecting = "(a b x y d)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceTwoWithOneAtLeft(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChild = CommonTree(CommonToken(99, text="x"))

        t.replaceChildren(0, 1, newChild)
        expecting = "(a x d)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceTwoWithOneAtRight(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChild = CommonTree(CommonToken(99, text="x"))

        t.replaceChildren(1, 2, newChild)
        expecting = "(a b x)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceAllWithOne(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChild = CommonTree(CommonToken(99, text="x"))

        t.replaceChildren(0, 2, newChild)
        expecting = "(a x)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()

    def testReplaceAllWithTwo(self):
        t = CommonTree(CommonToken(99, text="a"))
        t.addChild(CommonTree(CommonToken(99, text="b")))
        t.addChild(CommonTree(CommonToken(99, text="c")))
        t.addChild(CommonTree(CommonToken(99, text="d")))

        newChildren = self.adaptor.nil()
        newChildren.addChild(CommonTree(CommonToken(99, text="x")))
        newChildren.addChild(CommonTree(CommonToken(99, text="y")))

        t.replaceChildren(0, 2, newChildren)
        expecting = "(a x y)"
        self.failUnlessEqual(expecting, t.toStringTree())
        t.sanityCheckParentAndChildIndexes()
Exemplo n.º 28
0
 def setUp(self):
     self.adaptor = CommonTreeAdaptor()
Exemplo n.º 29
0
class TestTreeNodeStream(unittest.TestCase):
    """Test case for the TreeNodeStream class."""
    def setUp(self):
        self.adaptor = CommonTreeAdaptor()

    def newStream(self, t):
        """Build new stream; let's us override to test other streams."""
        return CommonTreeNodeStream(t)

    def testSingleNode(self):
        t = CommonTree(CommonToken(101))

        stream = self.newStream(t)
        expecting = "101"
        found = self.toNodesOnlyString(stream)
        self.failUnlessEqual(expecting, found)

        expecting = "101"
        found = str(stream)
        self.failUnlessEqual(expecting, found)

    def testTwoChildrenOfNilRoot(self):
        class V(CommonTree):
            def __init__(self, token=None, ttype=None, x=None):
                if x is not None:
                    self.x = x

                if ttype is not None and token is None:
                    self.token = CommonToken(type=ttype)

                if token is not None:
                    self.token = token

            def __str__(self):
                if self.token is not None:
                    txt = self.token.text
                else:
                    txt = ""

                txt += "<V>"
                return txt

        root_0 = self.adaptor.nil()
        t = V(ttype=101, x=2)
        u = V(token=CommonToken(type=102, text="102"))
        self.adaptor.addChild(root_0, t)
        self.adaptor.addChild(root_0, u)
        self.assert_(root_0.parent is None)
        self.assertEquals(-1, root_0.childIndex)
        self.assertEquals(0, t.childIndex)
        self.assertEquals(1, u.childIndex)

    def test4Nodes(self):
        # ^(101 ^(102 103) 104)
        t = CommonTree(CommonToken(101))
        t.addChild(CommonTree(CommonToken(102)))
        t.getChild(0).addChild(CommonTree(CommonToken(103)))
        t.addChild(CommonTree(CommonToken(104)))

        stream = self.newStream(t)
        expecting = "101 102 103 104"
        found = self.toNodesOnlyString(stream)
        self.failUnlessEqual(expecting, found)

        expecting = "101 2 102 2 103 3 104 3"
        found = str(stream)
        self.failUnlessEqual(expecting, found)

    def testList(self):
        root = CommonTree(None)

        t = CommonTree(CommonToken(101))
        t.addChild(CommonTree(CommonToken(102)))
        t.getChild(0).addChild(CommonTree(CommonToken(103)))
        t.addChild(CommonTree(CommonToken(104)))

        u = CommonTree(CommonToken(105))

        root.addChild(t)
        root.addChild(u)

        stream = CommonTreeNodeStream(root)
        expecting = "101 102 103 104 105"
        found = self.toNodesOnlyString(stream)
        self.failUnlessEqual(expecting, found)

        expecting = "101 2 102 2 103 3 104 3 105"
        found = str(stream)
        self.failUnlessEqual(expecting, found)

    def testFlatList(self):
        root = CommonTree(None)

        root.addChild(CommonTree(CommonToken(101)))
        root.addChild(CommonTree(CommonToken(102)))
        root.addChild(CommonTree(CommonToken(103)))

        stream = CommonTreeNodeStream(root)
        expecting = "101 102 103"
        found = self.toNodesOnlyString(stream)
        self.failUnlessEqual(expecting, found)

        expecting = "101 102 103"
        found = str(stream)
        self.failUnlessEqual(expecting, found)

    def testListWithOneNode(self):
        root = CommonTree(None)

        root.addChild(CommonTree(CommonToken(101)))

        stream = CommonTreeNodeStream(root)
        expecting = "101"
        found = self.toNodesOnlyString(stream)
        self.failUnlessEqual(expecting, found)

        expecting = "101"
        found = str(stream)
        self.failUnlessEqual(expecting, found)

    def testAoverB(self):
        t = CommonTree(CommonToken(101))
        t.addChild(CommonTree(CommonToken(102)))

        stream = self.newStream(t)
        expecting = "101 102"
        found = self.toNodesOnlyString(stream)
        self.failUnlessEqual(expecting, found)

        expecting = "101 2 102 3"
        found = str(stream)
        self.failUnlessEqual(expecting, found)

    def testLT(self):
        # ^(101 ^(102 103) 104)
        t = CommonTree(CommonToken(101))
        t.addChild(CommonTree(CommonToken(102)))
        t.getChild(0).addChild(CommonTree(CommonToken(103)))
        t.addChild(CommonTree(CommonToken(104)))

        stream = self.newStream(t)
        self.failUnlessEqual(101, stream.LT(1).getType())
        self.failUnlessEqual(DOWN, stream.LT(2).getType())
        self.failUnlessEqual(102, stream.LT(3).getType())
        self.failUnlessEqual(DOWN, stream.LT(4).getType())
        self.failUnlessEqual(103, stream.LT(5).getType())
        self.failUnlessEqual(UP, stream.LT(6).getType())
        self.failUnlessEqual(104, stream.LT(7).getType())
        self.failUnlessEqual(UP, stream.LT(8).getType())
        self.failUnlessEqual(EOF, stream.LT(9).getType())
        # check way ahead
        self.failUnlessEqual(EOF, stream.LT(100).getType())

    def testMarkRewindEntire(self):
        # ^(101 ^(102 103 ^(106 107) ) 104 105)
        # stream has 7 real + 6 nav nodes
        # Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF
        r0 = CommonTree(CommonToken(101))
        r1 = CommonTree(CommonToken(102))
        r0.addChild(r1)
        r1.addChild(CommonTree(CommonToken(103)))
        r2 = CommonTree(CommonToken(106))
        r2.addChild(CommonTree(CommonToken(107)))
        r1.addChild(r2)
        r0.addChild(CommonTree(CommonToken(104)))
        r0.addChild(CommonTree(CommonToken(105)))

        stream = CommonTreeNodeStream(r0)
        m = stream.mark()  # MARK
        for _ in range(13):  # consume til end
            stream.LT(1)
            stream.consume()

        self.failUnlessEqual(EOF, stream.LT(1).getType())
        self.failUnlessEqual(UP, stream.LT(-1).getType())
        stream.rewind(m)  # REWIND

        # consume til end again :)
        for _ in range(13):  # consume til end
            stream.LT(1)
            stream.consume()

        self.failUnlessEqual(EOF, stream.LT(1).getType())
        self.failUnlessEqual(UP, stream.LT(-1).getType())

    def testMarkRewindInMiddle(self):
        # ^(101 ^(102 103 ^(106 107) ) 104 105)
        # stream has 7 real + 6 nav nodes
        # Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF
        r0 = CommonTree(CommonToken(101))
        r1 = CommonTree(CommonToken(102))
        r0.addChild(r1)
        r1.addChild(CommonTree(CommonToken(103)))
        r2 = CommonTree(CommonToken(106))
        r2.addChild(CommonTree(CommonToken(107)))
        r1.addChild(r2)
        r0.addChild(CommonTree(CommonToken(104)))
        r0.addChild(CommonTree(CommonToken(105)))

        stream = CommonTreeNodeStream(r0)
        for _ in range(7):  # consume til middle
            #System.out.println(tream.LT(1).getType())
            stream.consume()

        self.failUnlessEqual(107, stream.LT(1).getType())
        m = stream.mark()  # MARK
        stream.consume()  # consume 107
        stream.consume()  # consume UP
        stream.consume()  # consume UP
        stream.consume()  # consume 104
        stream.rewind(m)  # REWIND

        self.failUnlessEqual(107, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(UP, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(UP, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(104, stream.LT(1).getType())
        stream.consume()
        # now we're past rewind position
        self.failUnlessEqual(105, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(UP, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(EOF, stream.LT(1).getType())
        self.failUnlessEqual(UP, stream.LT(-1).getType())

    def testMarkRewindNested(self):
        # ^(101 ^(102 103 ^(106 107) ) 104 105)
        # stream has 7 real + 6 nav nodes
        # Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF
        r0 = CommonTree(CommonToken(101))
        r1 = CommonTree(CommonToken(102))
        r0.addChild(r1)
        r1.addChild(CommonTree(CommonToken(103)))
        r2 = CommonTree(CommonToken(106))
        r2.addChild(CommonTree(CommonToken(107)))
        r1.addChild(r2)
        r0.addChild(CommonTree(CommonToken(104)))
        r0.addChild(CommonTree(CommonToken(105)))

        stream = CommonTreeNodeStream(r0)
        m = stream.mark()  # MARK at start
        stream.consume()  # consume 101
        stream.consume()  # consume DN
        m2 = stream.mark()  # MARK on 102
        stream.consume()  # consume 102
        stream.consume()  # consume DN
        stream.consume()  # consume 103
        stream.consume()  # consume 106
        stream.rewind(m2)  # REWIND to 102
        self.failUnlessEqual(102, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(DOWN, stream.LT(1).getType())
        stream.consume()
        # stop at 103 and rewind to start
        stream.rewind(m)  # REWIND to 101
        self.failUnlessEqual(101, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(DOWN, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(102, stream.LT(1).getType())
        stream.consume()
        self.failUnlessEqual(DOWN, stream.LT(1).getType())

    def testSeek(self):
        # ^(101 ^(102 103 ^(106 107) ) 104 105)
        # stream has 7 real + 6 nav nodes
        # Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF
        r0 = CommonTree(CommonToken(101))
        r1 = CommonTree(CommonToken(102))
        r0.addChild(r1)
        r1.addChild(CommonTree(CommonToken(103)))
        r2 = CommonTree(CommonToken(106))
        r2.addChild(CommonTree(CommonToken(107)))
        r1.addChild(r2)
        r0.addChild(CommonTree(CommonToken(104)))
        r0.addChild(CommonTree(CommonToken(105)))

        stream = CommonTreeNodeStream(r0)
        stream.consume()  # consume 101
        stream.consume()  # consume DN
        stream.consume()  # consume 102
        stream.seek(7)  # seek to 107
        self.failUnlessEqual(107, stream.LT(1).getType())
        stream.consume()  # consume 107
        stream.consume()  # consume UP
        stream.consume()  # consume UP
        self.failUnlessEqual(104, stream.LT(1).getType())

    def testSeekFromStart(self):
        # ^(101 ^(102 103 ^(106 107) ) 104 105)
        # stream has 7 real + 6 nav nodes
        # Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF
        r0 = CommonTree(CommonToken(101))
        r1 = CommonTree(CommonToken(102))
        r0.addChild(r1)
        r1.addChild(CommonTree(CommonToken(103)))
        r2 = CommonTree(CommonToken(106))
        r2.addChild(CommonTree(CommonToken(107)))
        r1.addChild(r2)
        r0.addChild(CommonTree(CommonToken(104)))
        r0.addChild(CommonTree(CommonToken(105)))

        stream = CommonTreeNodeStream(r0)
        stream.seek(7)  # seek to 107
        self.failUnlessEqual(107, stream.LT(1).getType())
        stream.consume()  # consume 107
        stream.consume()  # consume UP
        stream.consume()  # consume UP
        self.failUnlessEqual(104, stream.LT(1).getType())

    def toNodesOnlyString(self, nodes):
        buf = []
        for i in range(nodes.size()):
            t = nodes.LT(i + 1)
            type = nodes.getTreeAdaptor().getType(t)
            if not (type == DOWN or type == UP):
                buf.append(str(type))

        return ' '.join(buf)
 def setUp(self):
     self.adaptor = CommonTreeAdaptor()
     self.tokens = [
         "", "", "", "", "", "A", "B", "C", "D", "E", "ID", "VAR"
         ]
     self.wiz = TreeWizard(self.adaptor, self.tokens)