Do not expand schema tree values
[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         final Map<QName, SchemaTreeEffectiveStatement<?>> schemaTree;
58         if (this instanceof SchemaTreeAwareEffectiveStatement || this instanceof DataNodeContainer) {
59             schemaTree = createSchemaTreeNamespace(ctx.getStatementSourceReference(),
60                 effectiveSubstatements());
61         } else {
62             schemaTree = ImmutableMap.of();
63         }
64         schemaTreeNamespace = ImmutableMap.copyOf(schemaTree);
65
66         if (this instanceof DataTreeAwareEffectiveStatement && !schemaTree.isEmpty()) {
67             dataTreeNamespace = createDataTreeNamespace(ctx.getStatementSourceReference(), schemaTree.values(),
68                 schemaTreeNamespace);
69         } else {
70             dataTreeNamespace = ImmutableMap.of();
71         }
72     }
73
74     @Override
75     @SuppressWarnings("unchecked")
76     protected <K, V, N extends IdentifierNamespace<K, V>> Optional<? extends Map<K, V>> getNamespaceContents(
77             final Class<N> namespace) {
78         if (this instanceof SchemaTreeAwareEffectiveStatement
79                 && SchemaTreeAwareEffectiveStatement.Namespace.class.equals(namespace)) {
80             return Optional.of((Map<K, V>) schemaTreeNamespace);
81         }
82         if (this instanceof DataTreeAwareEffectiveStatement
83                 && DataTreeAwareEffectiveStatement.Namespace.class.equals(namespace)) {
84             return Optional.of((Map<K, V>) dataTreeNamespace);
85         }
86         return super.getNamespaceContents(namespace);
87     }
88
89     protected final <T> @NonNull ImmutableSet<T> derivedSet(final VarHandle vh, final @NonNull Class<T> clazz) {
90         final ImmutableSet<T> existing = (ImmutableSet<T>) vh.getAcquire(this);
91         return existing != null ? existing : loadSet(vh, clazz);
92     }
93
94     /**
95      * Indexing support for {@link DataNodeContainer#findDataChildByName(QName)}.
96      */
97     protected final Optional<DataSchemaNode> findDataSchemaNode(final QName name) {
98         // Only DataNodeContainer subclasses should be calling this method
99         verify(this instanceof DataNodeContainer);
100         final SchemaTreeEffectiveStatement<?> child = schemaTreeNamespace.get(requireNonNull(name));
101         return child instanceof DataSchemaNode ? Optional.of((DataSchemaNode) child) : Optional.empty();
102     }
103
104     static @NonNull Map<QName, SchemaTreeEffectiveStatement<?>> createSchemaTreeNamespace(
105             final StatementSourceReference ref, final Collection<? extends EffectiveStatement<?, ?>> substatements) {
106         final Map<QName, SchemaTreeEffectiveStatement<?>> schemaChildren = new LinkedHashMap<>();
107         substatements.stream().filter(SchemaTreeEffectiveStatement.class::isInstance)
108             .forEach(child -> putChild(schemaChildren, (SchemaTreeEffectiveStatement) child, ref, "schema"));
109         return schemaChildren;
110     }
111
112     static @NonNull ImmutableMap<QName, DataTreeEffectiveStatement<?>> createDataTreeNamespace(
113             final StatementSourceReference ref,
114             final Collection<SchemaTreeEffectiveStatement<?>> schemaTreeStatements,
115             // Note: this dance is needed to not retain ImmutableMap$Values
116             final ImmutableMap<QName, SchemaTreeEffectiveStatement<?>> schemaTreeNamespace) {
117         final Map<QName, DataTreeEffectiveStatement<?>> dataChildren = new LinkedHashMap<>();
118         boolean sameAsSchema = true;
119
120         for (SchemaTreeEffectiveStatement<?> child : schemaTreeStatements) {
121             if (child instanceof DataTreeEffectiveStatement) {
122                 putChild(dataChildren, (DataTreeEffectiveStatement<?>) child, ref, "data");
123             } else {
124                 sameAsSchema = false;
125                 putChoiceDataChildren(dataChildren, ref, child);
126             }
127         }
128
129         // This is a mighty hack to lower memory usage: if we consumed all schema tree children as data nodes,
130         // the two maps are equal and hence we can share the instance.
131         return sameAsSchema ? (ImmutableMap) schemaTreeNamespace : ImmutableMap.copyOf(dataChildren);
132     }
133
134     @SuppressWarnings("unchecked")
135     private <T> @NonNull ImmutableSet<T> loadSet(final VarHandle vh, final @NonNull Class<T> clazz) {
136         final ImmutableSet<T> computed = ImmutableSet.copyOf(allSubstatementsOfType(clazz));
137         final Object witness = vh.compareAndExchangeRelease(this, null, computed);
138         return witness == null ? computed : (ImmutableSet<T>) witness;
139     }
140
141     private static <T extends SchemaTreeEffectiveStatement<?>> void putChild(final Map<QName, T> map,
142             final T child, final StatementSourceReference ref, final String tree) {
143         final QName id = child.getIdentifier();
144         final T prev = map.putIfAbsent(id, child);
145         SourceException.throwIf(prev != null, ref,
146                 "Cannot add %s tree child with name %s, a conflicting child already exists", tree, id);
147     }
148
149     private static void putChoiceDataChildren(final Map<QName, DataTreeEffectiveStatement<?>> map,
150             final StatementSourceReference ref, final SchemaTreeEffectiveStatement<?> child) {
151         // For choice statements go through all their cases and fetch their data children
152         if (child instanceof ChoiceEffectiveStatement) {
153             child.streamEffectiveSubstatements(CaseEffectiveStatement.class).forEach(
154                 caseStmt -> caseStmt.streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class).forEach(stmt -> {
155                     if (stmt instanceof DataTreeEffectiveStatement) {
156                         putChild(map, (DataTreeEffectiveStatement<?>) stmt, ref, "data");
157                     } else {
158                         putChoiceDataChildren(map, ref, stmt);
159                     }
160                 }));
161         }
162     }
163 }