Make getOriginalCtx() give out an Optional
[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.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.collect.ImmutableSet;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Optional;
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.common.YangVersion;
21 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
22 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
23 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
24 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
25 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
27 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
34 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.QNameCacheNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
45 import org.opendaylight.yangtools.yang.parser.spi.source.AugmentToChoiceNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
47 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> extends
53         StatementContextBase<A, D, E> {
54     private static final Logger LOG = LoggerFactory.getLogger(SubstatementContext.class);
55
56     private final StatementContextBase<?, ?, ?> parent;
57     private final A argument;
58
59     /**
60      * config statements are not all that common which means we are performing a recursive search towards the root
61      * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
62      * for the (usually non-existent) config statement.
63      *
64      * This field maintains a resolution cache, so once we have returned a result, we will keep on returning the same
65      * result without performing any lookups.
66      */
67     private boolean haveConfiguration;
68     private boolean configuration;
69     private boolean wasCheckedIfInYangDataExtensionBody;
70     private boolean isInYangDataExtensionBody;
71
72     private volatile SchemaPath schemaPath;
73
74     SubstatementContext(final StatementContextBase<?, ?, ?> parent, final StatementDefinitionContext<A, D, E> def,
75             final StatementSourceReference ref, final String rawArgument) {
76         super(def, ref, rawArgument);
77         this.parent = Preconditions.checkNotNull(parent, "Parent must not be null");
78         this.argument = def.parseArgumentValue(this, rawStatementArgument());
79     }
80
81     @SuppressWarnings("unchecked")
82     private SubstatementContext(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
83             final StatementContextBase<?, ?, ?> newParent, final CopyType copyType) {
84         super(original, copyType);
85         this.parent = Preconditions.checkNotNull(newParent);
86
87         if (newQNameModule != null) {
88             final A originalArg = original.argument;
89             if (originalArg instanceof QName) {
90                 final QName originalQName = (QName) originalArg;
91                 this.argument = (A) getFromNamespace(QNameCacheNamespace.class,
92                         QName.create(newQNameModule, originalQName.getLocalName()));
93             } else if (StmtContextUtils.producesDeclared(original, KeyStatement.class)) {
94                 this.argument = (A) StmtContextUtils.replaceModuleQNameForKey(
95                         (StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?>) original, newQNameModule);
96             } else {
97                 this.argument = original.argument;
98             }
99         } else {
100             this.argument = original.argument;
101         }
102     }
103
104     @Override
105     public StatementContextBase<?, ?, ?> getParentContext() {
106         return parent;
107     }
108
109     @Override
110     public StorageNodeType getStorageNodeType() {
111         return StorageNodeType.STATEMENT_LOCAL;
112     }
113
114     @Override
115     public NamespaceStorageNode getParentNamespaceStorage() {
116         return parent;
117     }
118
119     @Override
120     public Registry getBehaviourRegistry() {
121         return parent.getBehaviourRegistry();
122     }
123
124     @Nonnull
125     @Override
126     public RootStatementContext<?, ?, ?> getRoot() {
127         return parent.getRoot();
128     }
129
130     @Override
131     public A getStatementArgument() {
132         return argument;
133     }
134
135     @Override
136     public StatementContextBase<A, D, E> createCopy(final StatementContextBase<?, ?, ?> newParent,
137             final CopyType typeOfCopy) {
138         return createCopy(null, newParent, typeOfCopy);
139     }
140
141     @Override
142     public StatementContextBase<A, D, E> createCopy(final QNameModule newQNameModule,
143             final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
144         Preconditions.checkState(getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
145                 "Attempted to copy statement %s which has completed phase %s", this, getCompletedPhase());
146
147         final SubstatementContext<A, D, E> copy = new SubstatementContext<>(this, newQNameModule, newParent, typeOfCopy);
148
149         definition().onStatementAdded(copy);
150
151         copy.copyStatements(this, newQNameModule, typeOfCopy);
152         return copy;
153     }
154
155     private void copyStatements(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
156             final CopyType typeOfCopy) {
157         final Collection<? extends Mutable<?, ?, ?>> declared = original.mutableDeclaredSubstatements();
158         final Collection<? extends Mutable<?, ?, ?>> effective = original.mutableEffectiveSubstatements();
159         final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
160
161         for (final Mutable<?, ?, ?> stmtContext : declared) {
162             if (stmtContext.isSupportedByFeatures()) {
163                 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
164             }
165         }
166
167         for (final Mutable<?, ?, ?> stmtContext : effective) {
168             copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
169         }
170
171         addEffectiveSubstatements(buffer);
172     }
173
174     private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final QNameModule newQNameModule,
175             final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer) {
176         if (needToCopyByUses(stmtContext)) {
177             final Mutable<?, ?, ?> copy = stmtContext.createCopy(newQNameModule, this, typeOfCopy);
178             LOG.debug("Copying substatement {} for {} as", stmtContext, this, copy);
179             buffer.add(copy);
180         } else if (isReusedByUses(stmtContext)) {
181             LOG.debug("Reusing substatement {} for {}", stmtContext, this);
182             buffer.add(stmtContext);
183         } else {
184             LOG.debug("Skipping statement {}", stmtContext);
185         }
186     }
187
188     // FIXME: revise this, as it seems to be wrong
189     private static final Set<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
190         YangStmtMapping.DESCRIPTION,
191         YangStmtMapping.REFERENCE,
192         YangStmtMapping.STATUS);
193     private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
194         YangStmtMapping.TYPE,
195         YangStmtMapping.TYPEDEF,
196         YangStmtMapping.USES);
197
198     private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
199         final StatementDefinition def = stmtContext.getPublicDefinition();
200         if (REUSED_DEF_SET.contains(def)) {
201             LOG.debug("Will reuse {} statement {}", def, stmtContext);
202             return false;
203         }
204         if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
205             return !YangStmtMapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
206         }
207
208         LOG.debug("Will copy {} statement {}", def, stmtContext);
209         return true;
210     }
211
212     private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
213         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
214     }
215
216     private boolean isSupportedAsShorthandCase() {
217         final Collection<?> supportedCaseShorthands = getFromNamespace(ValidationBundlesNamespace.class,
218                 ValidationBundleType.SUPPORTED_CASE_SHORTHANDS);
219         return supportedCaseShorthands == null || supportedCaseShorthands.contains(getPublicDefinition());
220     }
221
222     private SchemaPath createSchemaPath() {
223         final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
224         Verify.verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
225         final SchemaPath parentPath = maybeParentPath.get();
226
227         if (StmtContextUtils.isUnknownNode(this)) {
228             return parentPath.createChild(getPublicDefinition().getStatementName());
229         }
230         if (argument instanceof QName) {
231             final QName qname = (QName) argument;
232             if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
233                 return maybeParentPath.orElse(null);
234             }
235
236             final SchemaPath path;
237             if ((StmtContextUtils.producesDeclared(getParentContext(), ChoiceStatement.class)
238                     || Boolean.TRUE.equals(parent.getFromNamespace(AugmentToChoiceNamespace.class, parent)))
239                     && isSupportedAsShorthandCase()) {
240                 path = parentPath.createChild(qname);
241             } else {
242                 path = parentPath;
243             }
244             return path.createChild(qname);
245         }
246         if (argument instanceof String) {
247             // FIXME: This may yield illegal argument exceptions
248             final Optional<StmtContext<?, ?, ?>> originalCtx = getOriginalCtx();
249             final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
250             return parentPath.createChild(qname);
251         }
252         if (argument instanceof SchemaNodeIdentifier
253                 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class)
254                         || StmtContextUtils.producesDeclared(this, RefineStatement.class)
255                         || StmtContextUtils.producesDeclared(this, DeviationStatement.class))) {
256
257             return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
258         }
259
260         // FIXME: this does not look right
261         return maybeParentPath.orElse(null);
262     }
263
264     @Nonnull
265     @Override
266     public Optional<SchemaPath> getSchemaPath() {
267         SchemaPath local = schemaPath;
268         if (local == null) {
269             synchronized (this) {
270                 local = schemaPath;
271                 if (local == null) {
272                     local = createSchemaPath();
273                     schemaPath = local;
274                 }
275             }
276
277         }
278
279         return Optional.ofNullable(local);
280     }
281
282     @Override
283     public boolean isConfiguration() {
284         // if this statement is within a 'yang-data' extension body, config substatements are ignored as if
285         // they were not declared. As 'yang-data' is always a top-level node, all configs that are within it are
286         // automatically true
287         if (isInYangDataExtensionBody()) {
288             return true;
289         }
290
291         if (haveConfiguration) {
292             return configuration;
293         }
294
295         final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
296             ConfigStatement.class);
297         final boolean parentIsConfig = parent.isConfiguration();
298
299         final boolean isConfig;
300         if (configStatement != null) {
301             isConfig = configStatement.getStatementArgument();
302
303             // Validity check: if parent is config=false this cannot be a config=true
304             InferenceException.throwIf(isConfig && !parentIsConfig, getStatementSourceReference(),
305                     "Parent node has config=false, this node must not be specifed as config=true");
306         } else {
307             // If "config" statement is not specified, the default is the same as the parent's "config" value.
308             isConfig = parentIsConfig;
309         }
310
311         // Resolved, make sure we cache this return
312         configuration = isConfig;
313         haveConfiguration = true;
314         return isConfig;
315     }
316
317     @Override
318     public boolean isInYangDataExtensionBody() {
319         if (wasCheckedIfInYangDataExtensionBody) {
320             return isInYangDataExtensionBody;
321         }
322
323         final boolean parentIsInYangDataExtensionBody = parent.isInYangDataExtensionBody();
324         if (parentIsInYangDataExtensionBody) {
325             isInYangDataExtensionBody = parentIsInYangDataExtensionBody;
326         } else {
327             isInYangDataExtensionBody = StmtContextUtils.hasYangDataExtensionParent(this);
328         }
329
330         wasCheckedIfInYangDataExtensionBody = true;
331         return isInYangDataExtensionBody;
332     }
333
334     @Override
335     public boolean isEnabledSemanticVersioning() {
336         return parent.isEnabledSemanticVersioning();
337     }
338
339     @Override
340     public YangVersion getRootVersion() {
341         return getRoot().getRootVersion();
342     }
343
344     @Override
345     public void setRootVersion(final YangVersion version) {
346         getRoot().setRootVersion(version);
347     }
348
349     @Override
350     public void addMutableStmtToSeal(final MutableStatement mutableStatement) {
351         getRoot().addMutableStmtToSeal(mutableStatement);
352     }
353
354     @Override
355     public void addRequiredModule(final ModuleIdentifier dependency) {
356         getRoot().addRequiredModule(dependency);
357     }
358
359     @Override
360     public void setRootIdentifier(final ModuleIdentifier identifier) {
361         getRoot().setRootIdentifier(identifier);
362     }
363 }