Propagate @Nonnull and @Nullable annotations
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / SubstatementContext.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. 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.stmt.reactor;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Verify;
13 import com.google.common.collect.ImmutableSet;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Set;
17 import javax.annotation.Nonnull;
18 import org.opendaylight.yangtools.yang.common.QName;
19 import org.opendaylight.yangtools.yang.common.QNameModule;
20 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
21 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
22 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
23 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
24 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
25 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
31 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.QNameCacheNamespace;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
40 import org.opendaylight.yangtools.yang.parser.spi.source.AugmentToChoiceNamespace;
41 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
42 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
43 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> extends
48         StatementContextBase<A, D, E> {
49     private static final Logger LOG = LoggerFactory.getLogger(SubstatementContext.class);
50
51     private final StatementContextBase<?, ?, ?> parent;
52     private final A argument;
53     private volatile SchemaPath schemaPath;
54
55     SubstatementContext(final StatementContextBase<?, ?, ?> parent, final ContextBuilder<A, D, E> builder) {
56         super(builder);
57         this.parent = Preconditions.checkNotNull(parent, "Parent must not be null");
58         this.argument = builder.getDefinition().parseArgumentValue(this, builder.getRawArgument());
59     }
60
61     @SuppressWarnings("unchecked")
62     SubstatementContext(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
63             final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
64         super(original);
65         this.parent = newParent;
66
67         if (newQNameModule != null) {
68             final A originalArg = original.argument;
69             if (originalArg instanceof QName) {
70                 final QName originalQName = (QName) originalArg;
71                 this.argument = (A) getFromNamespace(QNameCacheNamespace.class,
72                         QName.create(newQNameModule, originalQName.getLocalName()));
73             } else if (StmtContextUtils.producesDeclared(original, KeyStatement.class)) {
74                 this.argument = (A) StmtContextUtils.replaceModuleQNameForKey(
75                         (StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?>) original, newQNameModule);
76             } else {
77                 this.argument = original.argument;
78             }
79         } else {
80             this.argument = original.argument;
81         }
82     }
83
84     @Override
85     public StatementContextBase<?, ?, ?> getParentContext() {
86         return parent;
87     }
88
89     @Override
90     public NamespaceStorageNode getParentNamespaceStorage() {
91         return parent;
92     }
93
94     @Override
95     public Registry getBehaviourRegistry() {
96         return parent.getBehaviourRegistry();
97     }
98
99     @Nonnull
100     @Override
101     public RootStatementContext<?, ?, ?> getRoot() {
102         return parent.getRoot();
103     }
104
105     @Override
106     public A getStatementArgument() {
107         return argument;
108     }
109
110     @Override
111     public StatementContextBase<?, ?, ?> createCopy(final StatementContextBase<?, ?, ?> newParent,
112             final CopyType typeOfCopy) {
113         return createCopy(null, newParent, typeOfCopy);
114     }
115
116     @Override
117     public StatementContextBase<A, D, E> createCopy(final QNameModule newQNameModule,
118             final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
119         Preconditions.checkState(getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
120                 "Attempted to copy statement {} which has completed phase {}", this, getCompletedPhase());
121
122         final SubstatementContext<A, D, E> copy = new SubstatementContext<>(this, newQNameModule, newParent, typeOfCopy);
123
124         copy.appendCopyHistory(typeOfCopy, this.getCopyHistory());
125
126         if (this.getOriginalCtx() != null) {
127             copy.setOriginalCtx(this.getOriginalCtx());
128         } else {
129             copy.setOriginalCtx(this);
130         }
131
132         definition().onStatementAdded(copy);
133
134         copy.copyStatements(this, newQNameModule, typeOfCopy);
135         return copy;
136     }
137
138     private void copyStatements(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
139             final CopyType typeOfCopy) {
140         final Collection<StatementContextBase<?, ?, ?>> declared = original.declaredSubstatements();
141         final Collection<StatementContextBase<?, ?, ?>> effective = original.effectiveSubstatements();
142         final Collection<StatementContextBase<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
143
144         for (final StatementContextBase<?, ?, ?> stmtContext : declared) {
145             if (StmtContextUtils.areFeaturesSupported(stmtContext)) {
146                 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
147             }
148         }
149
150         for (final StatementContextBase<?, ?, ?> stmtContext : effective) {
151             copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
152         }
153
154         addEffectiveSubstatements(buffer);
155     }
156
157     private void copySubstatement(final StatementContextBase<?, ?, ?> stmtContext,
158             final QNameModule newQNameModule, final CopyType typeOfCopy,
159             final Collection<StatementContextBase<?, ?, ?>> buffer) {
160         if (needToCopyByUses(stmtContext)) {
161             final StatementContextBase<?, ?, ?> copy = stmtContext.createCopy(newQNameModule, this, typeOfCopy);
162             LOG.debug("Copying substatement {} for {} as", stmtContext, this, copy);
163             buffer.add(copy);
164         } else if (isReusedByUses(stmtContext)) {
165             LOG.debug("Reusing substatement {} for {}", stmtContext, this);
166             buffer.add(stmtContext);
167         } else {
168             LOG.debug("Skipping statement {}", stmtContext);
169         }
170     }
171
172     // FIXME: revise this, as it seems to be wrong
173     private static final Set<Rfc6020Mapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
174         Rfc6020Mapping.DESCRIPTION,
175         Rfc6020Mapping.REFERENCE,
176         Rfc6020Mapping.STATUS);
177     private static final Set<Rfc6020Mapping> REUSED_DEF_SET = ImmutableSet.of(
178         Rfc6020Mapping.TYPE,
179         Rfc6020Mapping.TYPEDEF,
180         Rfc6020Mapping.USES);
181
182     private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
183         final StatementDefinition def = stmtContext.getPublicDefinition();
184         if (REUSED_DEF_SET.contains(def)) {
185             LOG.debug("Will reuse {} statement {}", def, stmtContext);
186             return false;
187         }
188         if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
189             return !Rfc6020Mapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
190         }
191
192         LOG.debug("Will copy {} statement {}", def, stmtContext);
193         return true;
194     }
195
196     private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
197         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
198     }
199
200     private boolean isSupportedAsShorthandCase() {
201         final Collection<?> supportedCaseShorthands = getFromNamespace(ValidationBundlesNamespace.class,
202                 ValidationBundleType.SUPPORTED_CASE_SHORTHANDS);
203         return supportedCaseShorthands == null || supportedCaseShorthands.contains(getPublicDefinition());
204     }
205
206     private SchemaPath createSchemaPath() {
207         final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
208         Verify.verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
209         final SchemaPath parentPath = maybeParentPath.get();
210
211         if (argument instanceof QName) {
212             final QName qname = (QName) argument;
213             if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
214                 return maybeParentPath.orNull();
215             }
216
217             final SchemaPath path;
218             if ((StmtContextUtils.producesDeclared(getParentContext(), ChoiceStatement.class)
219                     || Boolean.TRUE.equals(parent.getFromNamespace(AugmentToChoiceNamespace.class, parent)))
220                     && isSupportedAsShorthandCase()) {
221                 path = parentPath.createChild(qname);
222             } else {
223                 path = parentPath;
224             }
225             return path.createChild(qname);
226         }
227         if (argument instanceof String) {
228             // FIXME: This may yield illegal argument exceptions
229             final StatementContextBase<?, ?, ?> originalCtx = getOriginalCtx();
230             final QName qname = (originalCtx != null) ? Utils.qNameFromArgument(originalCtx, (String) argument) : Utils
231                     .qNameFromArgument(this, (String) argument);
232             return parentPath.createChild(qname);
233         }
234         if (argument instanceof SchemaNodeIdentifier
235                 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class) || StmtContextUtils
236                         .producesDeclared(this, RefineStatement.class))) {
237
238             return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
239         }
240         if (Utils.isUnknownNode(this)) {
241             return parentPath.createChild(getPublicDefinition().getStatementName());
242         }
243
244         // FIXME: this does not look right
245         return maybeParentPath.orNull();
246     }
247
248     @Nonnull
249     @Override
250     public Optional<SchemaPath> getSchemaPath() {
251         SchemaPath local = schemaPath;
252         if (local == null) {
253             synchronized (this) {
254                 local = schemaPath;
255                 if (local == null) {
256                     local = createSchemaPath();
257                     schemaPath = local;
258                 }
259             }
260
261         }
262
263         return Optional.fromNullable(local);
264     }
265
266     @Override
267     public boolean isRootContext() {
268         return false;
269     }
270
271     @Override
272     public boolean isConfiguration() {
273         final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
274                 ConfigStatement.class);
275
276         /*
277          * If "config" statement is not specified, the default is the same as
278          * the parent schema node's "config" value.
279          */
280         if (configStatement == null) {
281             return parent.isConfiguration();
282         }
283
284         /*
285          * If a parent node has "config" set to "true", the node underneath it
286          * can have "config" set to "true" or "false".
287          */
288         if (parent.isConfiguration()) {
289             return configStatement.getStatementArgument();
290         }
291
292         /*
293          * If a parent node has "config" set to "false", no node underneath it
294          * can have "config" set to "true", therefore only "false" is permitted.
295          */
296         if (!configStatement.getStatementArgument()) {
297             return false;
298         }
299
300         throw new InferenceException(
301                 "Parent node has config statement set to false, therefore no node underneath it can have config set to true",
302                 getStatementSourceReference());
303     }
304
305     @Override
306     public boolean isEnabledSemanticVersioning() {
307         return parent.isEnabledSemanticVersioning();
308     }
309 }