b736a23c2821c699618816a9042623e9c68ef4d5
[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.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     SubstatementContext(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
83             final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
84         super(original);
85         this.parent = 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         copy.appendCopyHistory(typeOfCopy, this.getCopyHistory());
150
151         if (this.getOriginalCtx() != null) {
152             copy.setOriginalCtx(this.getOriginalCtx());
153         } else {
154             copy.setOriginalCtx(this);
155         }
156
157         definition().onStatementAdded(copy);
158
159         copy.copyStatements(this, newQNameModule, typeOfCopy);
160         return copy;
161     }
162
163     private void copyStatements(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
164             final CopyType typeOfCopy) {
165         final Collection<? extends Mutable<?, ?, ?>> declared = original.mutableDeclaredSubstatements();
166         final Collection<? extends Mutable<?, ?, ?>> effective = original.mutableEffectiveSubstatements();
167         final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
168
169         for (final Mutable<?, ?, ?> stmtContext : declared) {
170             if (stmtContext.isSupportedByFeatures()) {
171                 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
172             }
173         }
174
175         for (final Mutable<?, ?, ?> stmtContext : effective) {
176             copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
177         }
178
179         addEffectiveSubstatements(buffer);
180     }
181
182     private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final QNameModule newQNameModule,
183             final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer) {
184         if (needToCopyByUses(stmtContext)) {
185             final Mutable<?, ?, ?> copy = stmtContext.createCopy(newQNameModule, this, typeOfCopy);
186             LOG.debug("Copying substatement {} for {} as", stmtContext, this, copy);
187             buffer.add(copy);
188         } else if (isReusedByUses(stmtContext)) {
189             LOG.debug("Reusing substatement {} for {}", stmtContext, this);
190             buffer.add(stmtContext);
191         } else {
192             LOG.debug("Skipping statement {}", stmtContext);
193         }
194     }
195
196     // FIXME: revise this, as it seems to be wrong
197     private static final Set<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
198         YangStmtMapping.DESCRIPTION,
199         YangStmtMapping.REFERENCE,
200         YangStmtMapping.STATUS);
201     private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
202         YangStmtMapping.TYPE,
203         YangStmtMapping.TYPEDEF,
204         YangStmtMapping.USES);
205
206     private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
207         final StatementDefinition def = stmtContext.getPublicDefinition();
208         if (REUSED_DEF_SET.contains(def)) {
209             LOG.debug("Will reuse {} statement {}", def, stmtContext);
210             return false;
211         }
212         if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
213             return !YangStmtMapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
214         }
215
216         LOG.debug("Will copy {} statement {}", def, stmtContext);
217         return true;
218     }
219
220     private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
221         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
222     }
223
224     private boolean isSupportedAsShorthandCase() {
225         final Collection<?> supportedCaseShorthands = getFromNamespace(ValidationBundlesNamespace.class,
226                 ValidationBundleType.SUPPORTED_CASE_SHORTHANDS);
227         return supportedCaseShorthands == null || supportedCaseShorthands.contains(getPublicDefinition());
228     }
229
230     private SchemaPath createSchemaPath() {
231         final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
232         Verify.verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
233         final SchemaPath parentPath = maybeParentPath.get();
234
235         if (StmtContextUtils.isUnknownNode(this)) {
236             return parentPath.createChild(getPublicDefinition().getStatementName());
237         }
238         if (argument instanceof QName) {
239             final QName qname = (QName) argument;
240             if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
241                 return maybeParentPath.orNull();
242             }
243
244             final SchemaPath path;
245             if ((StmtContextUtils.producesDeclared(getParentContext(), ChoiceStatement.class)
246                     || Boolean.TRUE.equals(parent.getFromNamespace(AugmentToChoiceNamespace.class, parent)))
247                     && isSupportedAsShorthandCase()) {
248                 path = parentPath.createChild(qname);
249             } else {
250                 path = parentPath;
251             }
252             return path.createChild(qname);
253         }
254         if (argument instanceof String) {
255             // FIXME: This may yield illegal argument exceptions
256             final StmtContext<?, ?, ?> originalCtx = getOriginalCtx();
257             final QName qname = originalCtx != null ? StmtContextUtils.qnameFromArgument(originalCtx, (String) argument)
258                     : StmtContextUtils.qnameFromArgument(this, (String) argument);
259             return parentPath.createChild(qname);
260         }
261         if (argument instanceof SchemaNodeIdentifier
262                 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class) || StmtContextUtils
263                         .producesDeclared(this, RefineStatement.class) || StmtContextUtils
264                 .producesDeclared(this, DeviationStatement.class))) {
265
266             return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
267         }
268
269         // FIXME: this does not look right
270         return maybeParentPath.orNull();
271     }
272
273     @Nonnull
274     @Override
275     public Optional<SchemaPath> getSchemaPath() {
276         SchemaPath local = schemaPath;
277         if (local == null) {
278             synchronized (this) {
279                 local = schemaPath;
280                 if (local == null) {
281                     local = createSchemaPath();
282                     schemaPath = local;
283                 }
284             }
285
286         }
287
288         return Optional.fromNullable(local);
289     }
290
291     @Override
292     public boolean isRootContext() {
293         return false;
294     }
295
296     @Override
297     public boolean isConfiguration() {
298         // if this statement is within a 'yang-data' extension body, config substatements are ignored as if
299         // they were not declared. As 'yang-data' is always a top-level node, all configs that are within it are
300         // automatically true
301         if (isInYangDataExtensionBody()) {
302             return true;
303         }
304
305         if (haveConfiguration) {
306             return configuration;
307         }
308
309         final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
310             ConfigStatement.class);
311         final boolean parentIsConfig = parent.isConfiguration();
312
313         final boolean isConfig;
314         if (configStatement != null) {
315             isConfig = configStatement.getStatementArgument();
316
317             // Validity check: if parent is config=false this cannot be a config=true
318             InferenceException.throwIf(isConfig && !parentIsConfig, getStatementSourceReference(),
319                     "Parent node has config=false, this node must not be specifed as config=true");
320         } else {
321             // If "config" statement is not specified, the default is the same as the parent's "config" value.
322             isConfig = parentIsConfig;
323         }
324
325         // Resolved, make sure we cache this return
326         configuration = isConfig;
327         haveConfiguration = true;
328         return isConfig;
329     }
330
331     @Override
332     public boolean isInYangDataExtensionBody() {
333         if (wasCheckedIfInYangDataExtensionBody) {
334             return isInYangDataExtensionBody;
335         }
336
337         final boolean parentIsInYangDataExtensionBody = parent.isInYangDataExtensionBody();
338         if (parentIsInYangDataExtensionBody) {
339             isInYangDataExtensionBody = parentIsInYangDataExtensionBody;
340         } else {
341             isInYangDataExtensionBody = StmtContextUtils.hasYangDataExtensionParent(this);
342         }
343
344         wasCheckedIfInYangDataExtensionBody = true;
345         return isInYangDataExtensionBody;
346     }
347
348     @Override
349     public boolean isEnabledSemanticVersioning() {
350         return parent.isEnabledSemanticVersioning();
351     }
352
353     @Override
354     public YangVersion getRootVersion() {
355         return getRoot().getRootVersion();
356     }
357
358     @Override
359     public void setRootVersion(final YangVersion version) {
360         getRoot().setRootVersion(version);
361     }
362
363     @Override
364     public void addMutableStmtToSeal(final MutableStatement mutableStatement) {
365         getRoot().addMutableStmtToSeal(mutableStatement);
366     }
367
368     @Override
369     public void addRequiredModule(final ModuleIdentifier dependency) {
370         getRoot().addRequiredModule(dependency);
371     }
372
373     @Override
374     public void setRootIdentifier(final ModuleIdentifier identifier) {
375         getRoot().setRootIdentifier(identifier);
376     }
377 }