001/*
002 * Copyright (C) 2009-2011 Mathias Doenitz
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.parboiled.trees;
018
019import java.util.List;
020
021/**
022 * An {@link ImmutableGraphNode} specialization representing a tree node with a parent field linking back to the nodes
023 * (only) parent.
024 *
025 * @param <T> the actual implementation type of this ImmutableTreeNode
026 */
027public class ImmutableTreeNode<T extends TreeNode<T>> extends ImmutableGraphNode<T> implements TreeNode<T> {
028
029    // we cannot make the parent field final since otherwise we can't create a tree hierarchy with parents linking to
030    // their children and vice versa. So we design this for a bottom up tree construction strategy were children
031    // are created first and then "acquired" by their parents
032    private T parent;
033
034    public ImmutableTreeNode() {
035    }
036
037    public ImmutableTreeNode(List<T> children) {
038        super(children);
039        acquireChildren();
040    }
041
042    public T getParent() {
043        return parent;
044    }
045
046    @SuppressWarnings({"unchecked"})
047    protected void acquireChildren() {
048        for (T children : getChildren()) {
049            ((ImmutableTreeNode) children).parent = this;
050        }
051    }
052}