Remove yang.parser.spi.meta.AbstractDeclaredStatement
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / AbstractEffectiveStatement.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, 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 java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableMap;
15 import java.util.Collection;
16 import java.util.LinkedHashMap;
17 import java.util.Map;
18 import java.util.Optional;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
22 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
23 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
24 import org.opendaylight.yangtools.yang.model.api.stmt.CaseEffectiveStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeEffectiveStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
28 import org.opendaylight.yangtools.yang.model.spi.meta.AbstractModelStatement;
29
30 /**
31  * Baseline stateless implementation of an EffectiveStatement. This class adds a few default implementations and
32  * namespace dispatch, but does not actually force any state on its subclasses. This approach adds requirements for an
33  * implementation, but it leaves it up to the final class to provide object layout.
34  *
35  * <p>
36  * This finds immense value in catering the common case, for example effective statements which can, but typically
37  * do not, contain substatements.
38  *
39  * @param <A> Argument type ({@link Void} if statement does not have argument.)
40  * @param <D> Class representing declared version of this statement.
41  */
42 @Beta
43 public abstract class AbstractEffectiveStatement<A, D extends DeclaredStatement<A>>
44         extends AbstractModelStatement<A> implements EffectiveStatement<A, D> {
45     @Override
46     public final <K, V, N extends IdentifierNamespace<K, V>> Optional<? extends V> get(final Class<N> namespace,
47             final K identifier) {
48         return Optional.ofNullable(getAll(namespace).get(requireNonNull(identifier)));
49     }
50
51     @Override
52     public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAll(final Class<N> namespace) {
53         final Optional<? extends Map<K, V>> ret = getNamespaceContents(requireNonNull(namespace));
54         return ret.isPresent() ? ret.get() : ImmutableMap.of();
55     }
56
57     @Override
58     public Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements() {
59         return ImmutableList.of();
60     }
61
62     /**
63      * Return the statement-specific contents of specified namespace, if available.
64      *
65      * @param namespace Requested namespace
66      * @return Namespace contents, if available.
67      */
68     protected <K, V, N extends IdentifierNamespace<K, V>> Optional<? extends Map<K, V>> getNamespaceContents(
69             final @NonNull Class<N> namespace) {
70         return Optional.empty();
71     }
72
73     /**
74      * Utility method for recovering singleton lists squashed by {@link #maskList(ImmutableList)}.
75      *
76      * @param masked list to unmask
77      * @return Unmasked list
78      * @throws NullPointerException if masked is null
79      * @throws ClassCastException if masked object does not match EffectiveStatement
80      */
81     @SuppressWarnings({ "rawtypes", "unchecked" })
82     protected static final @NonNull ImmutableList<? extends @NonNull EffectiveStatement<?, ?>> unmaskList(
83             final @NonNull Object masked) {
84         return (ImmutableList) unmaskList(masked, EffectiveStatement.class);
85     }
86
87     // TODO: below methods need to find a better place, this is just a temporary hideout as their public class is on
88     //       its way out
89     static @NonNull Map<QName, SchemaTreeEffectiveStatement<?>> createSchemaTreeNamespace(
90             final Collection<? extends EffectiveStatement<?, ?>> substatements) {
91         final Map<QName, SchemaTreeEffectiveStatement<?>> schemaChildren = new LinkedHashMap<>();
92         substatements.stream().filter(SchemaTreeEffectiveStatement.class::isInstance)
93             .forEach(child -> putChild(schemaChildren, (SchemaTreeEffectiveStatement<?>) child, "schema"));
94         return schemaChildren;
95     }
96
97     static @NonNull ImmutableMap<QName, DataTreeEffectiveStatement<?>> createDataTreeNamespace(
98             final Collection<SchemaTreeEffectiveStatement<?>> schemaTreeStatements,
99             // Note: this dance is needed to not retain ImmutableMap$Values
100             final ImmutableMap<QName, SchemaTreeEffectiveStatement<?>> schemaTreeNamespace) {
101         final Map<QName, DataTreeEffectiveStatement<?>> dataChildren = new LinkedHashMap<>();
102         boolean sameAsSchema = true;
103
104         for (SchemaTreeEffectiveStatement<?> child : schemaTreeStatements) {
105             if (child instanceof DataTreeEffectiveStatement) {
106                 putChild(dataChildren, (DataTreeEffectiveStatement<?>) child, "data");
107             } else {
108                 sameAsSchema = false;
109                 putChoiceDataChildren(dataChildren, child);
110             }
111         }
112
113         // This is a mighty hack to lower memory usage: if we consumed all schema tree children as data nodes,
114         // the two maps are equal and hence we can share the instance.
115         return sameAsSchema ? (ImmutableMap) schemaTreeNamespace : ImmutableMap.copyOf(dataChildren);
116     }
117
118     private static <T extends SchemaTreeEffectiveStatement<?>> void putChild(final Map<QName, T> map, final T child,
119             final String tree) {
120         final QName id = child.getIdentifier();
121         final T prev = map.putIfAbsent(id, child);
122         if (prev != null) {
123             throw new SubstatementIndexingException(
124                 "Cannot add " + tree + " tree child with name " + id + ", a conflicting child already exists");
125         }
126     }
127
128     private static void putChoiceDataChildren(final Map<QName, DataTreeEffectiveStatement<?>> map,
129             final SchemaTreeEffectiveStatement<?> child) {
130         // For choice statements go through all their cases and fetch their data children
131         if (child instanceof ChoiceEffectiveStatement) {
132             child.streamEffectiveSubstatements(CaseEffectiveStatement.class).forEach(
133                 caseStmt -> caseStmt.streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class).forEach(stmt -> {
134                     if (stmt instanceof DataTreeEffectiveStatement) {
135                         putChild(map, (DataTreeEffectiveStatement<?>) stmt, "data");
136                     } else {
137                         putChoiceDataChildren(map, stmt);
138                     }
139                 }));
140         }
141     }
142 }