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