Refactor ListEffectiveStatementImpl
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / AbstractSchemaEffectiveDocumentedNode.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.parser.rfc7950.stmt;
9
10 import static com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSet;
16 import java.lang.invoke.VarHandle;
17 import java.util.Collection;
18 import java.util.LinkedHashMap;
19 import java.util.Map;
20 import java.util.Optional;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
24 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
28 import org.opendaylight.yangtools.yang.model.api.stmt.CaseEffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeAwareEffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeEffectiveStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeAwareEffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
35 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
36 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
37
38 /**
39  * An {@link AbstractEffectiveDocumentedNode} which can optionally support {@link SchemaTreeAwareEffectiveStatement}.
40  *
41  * @param <A> Argument type ({@link Void} if statement does not have argument.)
42  * @param <D> Class representing declared version of this statement.
43  * @author Robert Varga
44  */
45 @Beta
46 public abstract class AbstractSchemaEffectiveDocumentedNode<A, D extends DeclaredStatement<A>>
47         extends AbstractEffectiveDocumentedNode<A, D> {
48     private final ImmutableMap<QName, DataTreeEffectiveStatement<?>> dataTreeNamespace;
49     private final ImmutableMap<QName, SchemaTreeEffectiveStatement<?>> schemaTreeNamespace;
50
51     protected AbstractSchemaEffectiveDocumentedNode(final StmtContext<A, D, ?> ctx) {
52         super(ctx);
53
54         // This check is rather weird, but comes from our desire to lower memory footprint while providing both
55         // EffectiveStatements and SchemaNode interfaces -- which do not overlap completely where child lookups are
56         // concerned. This ensures that we have SchemaTree index available for use with child lookups.
57         if (this instanceof SchemaTreeAwareEffectiveStatement || this instanceof DataNodeContainer) {
58             schemaTreeNamespace = createSchemaTreeNamespace(ctx.getStatementSourceReference(),
59                 effectiveSubstatements());
60         } else {
61             schemaTreeNamespace = ImmutableMap.of();
62         }
63         if (this instanceof DataTreeAwareEffectiveStatement && !schemaTreeNamespace.isEmpty()) {
64             dataTreeNamespace = createDataTreeNamespace(ctx.getStatementSourceReference(), schemaTreeNamespace);
65         } else {
66             dataTreeNamespace = ImmutableMap.of();
67         }
68     }
69
70     @Override
71     @SuppressWarnings("unchecked")
72     protected <K, V, N extends IdentifierNamespace<K, V>> Optional<? extends Map<K, V>> getNamespaceContents(
73             final Class<N> namespace) {
74         if (this instanceof SchemaTreeAwareEffectiveStatement
75                 && SchemaTreeAwareEffectiveStatement.Namespace.class.equals(namespace)) {
76             return Optional.of((Map<K, V>) schemaTreeNamespace);
77         }
78         if (this instanceof DataTreeAwareEffectiveStatement
79                 && DataTreeAwareEffectiveStatement.Namespace.class.equals(namespace)) {
80             return Optional.of((Map<K, V>) dataTreeNamespace);
81         }
82         return super.getNamespaceContents(namespace);
83     }
84
85     protected final <T> @NonNull ImmutableSet<T> derivedSet(final VarHandle vh, final @NonNull Class<T> clazz) {
86         final ImmutableSet<T> existing = (ImmutableSet<T>) vh.getAcquire(this);
87         return existing != null ? existing : loadSet(vh, clazz);
88     }
89
90     /**
91      * Indexing support for {@link DataNodeContainer#findDataChildByName(QName)}.
92      */
93     protected final Optional<DataSchemaNode> findDataSchemaNode(final QName name) {
94         // Only DataNodeContainer subclasses should be calling this method
95         verify(this instanceof DataNodeContainer);
96         final SchemaTreeEffectiveStatement<?> child = schemaTreeNamespace.get(requireNonNull(name));
97         return child instanceof DataSchemaNode ? Optional.of((DataSchemaNode) child) : Optional.empty();
98     }
99
100     static @NonNull ImmutableMap<QName, SchemaTreeEffectiveStatement<?>> createSchemaTreeNamespace(
101             final StatementSourceReference ref, final Collection<? extends EffectiveStatement<?, ?>> substatements) {
102         final Map<QName, SchemaTreeEffectiveStatement<?>> schemaChildren = new LinkedHashMap<>();
103         substatements.stream().filter(SchemaTreeEffectiveStatement.class::isInstance)
104             .forEach(child -> putChild(schemaChildren, (SchemaTreeEffectiveStatement) child, ref, "schema"));
105         return ImmutableMap.copyOf(schemaChildren);
106     }
107
108     static @NonNull ImmutableMap<QName, DataTreeEffectiveStatement<?>> createDataTreeNamespace(
109             final StatementSourceReference ref,
110             final ImmutableMap<QName, SchemaTreeEffectiveStatement<?>> schemaTreeNamespace) {
111         final Map<QName, DataTreeEffectiveStatement<?>> dataChildren = new LinkedHashMap<>();
112         boolean sameAsSchema = true;
113
114         for (SchemaTreeEffectiveStatement<?> child : schemaTreeNamespace.values()) {
115             if (child instanceof DataTreeEffectiveStatement) {
116                 putChild(dataChildren, (DataTreeEffectiveStatement<?>) child, ref, "data");
117             } else {
118                 sameAsSchema = false;
119                 putChoiceDataChildren(dataChildren, ref, child);
120             }
121         }
122
123         // This is a mighty hack to lower memory usage: if we consumed all schema tree children as data nodes,
124         // the two maps are equal and hence we can share the instance.
125         return sameAsSchema ? (ImmutableMap) schemaTreeNamespace : ImmutableMap.copyOf(dataChildren);
126     }
127
128     @SuppressWarnings("unchecked")
129     private <T> @NonNull ImmutableSet<T> loadSet(final VarHandle vh, final @NonNull Class<T> clazz) {
130         final ImmutableSet<T> computed = ImmutableSet.copyOf(allSubstatementsOfType(clazz));
131         final Object witness = vh.compareAndExchangeRelease(this, null, computed);
132         return witness == null ? computed : (ImmutableSet<T>) witness;
133     }
134
135     private static <T extends SchemaTreeEffectiveStatement<?>> void putChild(final Map<QName, T> map,
136             final T child, final StatementSourceReference ref, final String tree) {
137         final QName id = child.getIdentifier();
138         final T prev = map.putIfAbsent(id, child);
139         SourceException.throwIf(prev != null, ref,
140                 "Cannot add %s tree child with name %s, a conflicting child already exists", tree, id);
141     }
142
143     private static void putChoiceDataChildren(final Map<QName, DataTreeEffectiveStatement<?>> map,
144             final StatementSourceReference ref, final SchemaTreeEffectiveStatement<?> child) {
145         // For choice statements go through all their cases and fetch their data children
146         if (child instanceof ChoiceEffectiveStatement) {
147             child.streamEffectiveSubstatements(CaseEffectiveStatement.class).forEach(
148                 caseStmt -> caseStmt.streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class).forEach(stmt -> {
149                     if (stmt instanceof DataTreeEffectiveStatement) {
150                         putChild(map, (DataTreeEffectiveStatement<?>) stmt, ref, "data");
151                     } else {
152                         putChoiceDataChildren(map, ref, stmt);
153                     }
154                 }));
155         }
156     }
157 }