8fa166e0a47bb84dcdbd38b673f74de2795efc5c
[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 java.util.Collection;
13 import java.util.Optional;
14 import javax.annotation.Nonnull;
15 import org.opendaylight.yangtools.util.OptionalBoolean;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.common.QNameModule;
18 import org.opendaylight.yangtools.yang.common.YangVersion;
19 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
20 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
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.stmt.AugmentStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
29 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
38 import org.opendaylight.yangtools.yang.parser.spi.source.AugmentToChoiceNamespace;
39 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
40 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
41 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
42
43 final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> extends
44         StatementContextBase<A, D, E> {
45     private final StatementContextBase<?, ?, ?> parent;
46     private final A argument;
47
48     /**
49      * config statements are not all that common which means we are performing a recursive search towards the root
50      * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
51      * for the (usually non-existent) config statement.
52      *
53      * This field maintains a resolution cache, so once we have returned a result, we will keep on returning the same
54      * result without performing any lookups.
55      */
56     // BooleanField value
57     private byte configuration;
58
59     /**
60      * This field maintains a resolution cache for ignore config, so once we have returned a result, we will
61      * keep on returning the same result without performing any lookups.
62      */
63     // BooleanField value
64     private byte ignoreConfig;
65
66     /**
67      * This field maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
68      * keep on returning the same result without performing any lookups.
69      */
70     // BooleanField value
71     private byte ignoreIfFeature;
72
73     private volatile SchemaPath schemaPath;
74
75     SubstatementContext(final StatementContextBase<?, ?, ?> parent, final StatementDefinitionContext<A, D, E> def,
76             final StatementSourceReference ref, final String rawArgument) {
77         super(def, ref, rawArgument);
78         this.parent = Preconditions.checkNotNull(parent, "Parent must not be null");
79         this.argument = def.parseArgumentValue(this, rawStatementArgument());
80     }
81
82     SubstatementContext(final StatementContextBase<A, D, E> original, final StatementContextBase<?, ?, ?> parent,
83             final CopyType copyType, final QNameModule targetModule) {
84         super(original, copyType);
85         this.parent = Preconditions.checkNotNull(parent);
86         this.argument = targetModule == null ? original.getStatementArgument()
87                 : original.definition().adaptArgumentValue(original, targetModule);
88     }
89
90     @Override
91     public StatementContextBase<?, ?, ?> getParentContext() {
92         return parent;
93     }
94
95     @Override
96     public StorageNodeType getStorageNodeType() {
97         return StorageNodeType.STATEMENT_LOCAL;
98     }
99
100     @Override
101     public NamespaceStorageNode getParentNamespaceStorage() {
102         return parent;
103     }
104
105     @Override
106     public Registry getBehaviourRegistry() {
107         return parent.getBehaviourRegistry();
108     }
109
110     @Nonnull
111     @Override
112     public RootStatementContext<?, ?, ?> getRoot() {
113         return parent.getRoot();
114     }
115
116     @Override
117     public A getStatementArgument() {
118         return argument;
119     }
120
121     private boolean isSupportedAsShorthandCase() {
122         final Collection<?> supportedCaseShorthands = getFromNamespace(ValidationBundlesNamespace.class,
123                 ValidationBundleType.SUPPORTED_CASE_SHORTHANDS);
124         return supportedCaseShorthands == null || supportedCaseShorthands.contains(getPublicDefinition());
125     }
126
127     private SchemaPath createSchemaPath() {
128         final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
129         Verify.verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
130         final SchemaPath parentPath = maybeParentPath.get();
131
132         if (StmtContextUtils.isUnknownStatement(this)) {
133             return parentPath.createChild(getPublicDefinition().getStatementName());
134         }
135         if (argument instanceof QName) {
136             final QName qname = (QName) argument;
137             if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
138                 return maybeParentPath.orElse(null);
139             }
140
141             final SchemaPath path;
142             if ((StmtContextUtils.producesDeclared(getParentContext(), ChoiceStatement.class)
143                     || Boolean.TRUE.equals(parent.getFromNamespace(AugmentToChoiceNamespace.class, parent)))
144                     && isSupportedAsShorthandCase()) {
145                 path = parentPath.createChild(qname);
146             } else {
147                 path = parentPath;
148             }
149             return path.createChild(qname);
150         }
151         if (argument instanceof String) {
152             // FIXME: This may yield illegal argument exceptions
153             final Optional<StmtContext<?, ?, ?>> originalCtx = getOriginalCtx();
154             final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
155             return parentPath.createChild(qname);
156         }
157         if (argument instanceof SchemaNodeIdentifier
158                 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class)
159                         || StmtContextUtils.producesDeclared(this, RefineStatement.class)
160                         || StmtContextUtils.producesDeclared(this, DeviationStatement.class))) {
161
162             return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
163         }
164
165         // FIXME: this does not look right
166         return maybeParentPath.orElse(null);
167     }
168
169     @Nonnull
170     @Override
171     public Optional<SchemaPath> getSchemaPath() {
172         SchemaPath local = schemaPath;
173         if (local == null) {
174             synchronized (this) {
175                 local = schemaPath;
176                 if (local == null) {
177                     local = createSchemaPath();
178                     schemaPath = local;
179                 }
180             }
181         }
182
183         return Optional.ofNullable(local);
184     }
185
186     @Override
187     public boolean isConfiguration() {
188         if (isIgnoringConfig()) {
189             return true;
190         }
191
192         if (OptionalBoolean.isPresent(configuration)) {
193             return OptionalBoolean.get(configuration);
194         }
195
196         final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
197             ConfigStatement.class);
198         final boolean parentIsConfig = parent.isConfiguration();
199
200         final boolean isConfig;
201         if (configStatement != null) {
202             isConfig = configStatement.getStatementArgument();
203
204             // Validity check: if parent is config=false this cannot be a config=true
205             InferenceException.throwIf(isConfig && !parentIsConfig, getStatementSourceReference(),
206                     "Parent node has config=false, this node must not be specifed as config=true");
207         } else {
208             // If "config" statement is not specified, the default is the same as the parent's "config" value.
209             isConfig = parentIsConfig;
210         }
211
212         // Resolved, make sure we cache this return
213         configuration = OptionalBoolean.of(isConfig);
214         return isConfig;
215     }
216
217     @Override
218     public boolean isEnabledSemanticVersioning() {
219         return parent.isEnabledSemanticVersioning();
220     }
221
222     @Override
223     public YangVersion getRootVersion() {
224         return getRoot().getRootVersion();
225     }
226
227     @Override
228     public void setRootVersion(final YangVersion version) {
229         getRoot().setRootVersion(version);
230     }
231
232     @Override
233     public void addMutableStmtToSeal(final MutableStatement mutableStatement) {
234         getRoot().addMutableStmtToSeal(mutableStatement);
235     }
236
237     @Override
238     public void addRequiredModule(final ModuleIdentifier dependency) {
239         getRoot().addRequiredModule(dependency);
240     }
241
242     @Override
243     public void setRootIdentifier(final ModuleIdentifier identifier) {
244         getRoot().setRootIdentifier(identifier);
245     }
246
247     @Override
248     protected boolean isIgnoringIfFeatures() {
249         if (OptionalBoolean.isPresent(ignoreIfFeature)) {
250             return OptionalBoolean.get(ignoreIfFeature);
251         }
252
253         final boolean ret = definition().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures();
254         ignoreIfFeature = OptionalBoolean.of(ret);
255
256         return ret;
257     }
258
259     @Override
260     protected boolean isIgnoringConfig() {
261         if (OptionalBoolean.isPresent(ignoreConfig)) {
262             return OptionalBoolean.get(ignoreConfig);
263         }
264
265         final boolean ret = definition().isIgnoringConfig() || parent.isIgnoringConfig();
266         ignoreConfig = OptionalBoolean.of(ret);
267
268         return ret;
269     }
270
271     @Override
272     protected boolean isParentSupportedByFeatures() {
273         return parent.isSupportedByFeatures();
274     }
275 }