d2e5c733d3bf63c44bb213db9afc5d895746ce58
[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.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> extends
54         StatementContextBase<A, D, E> {
55     private static final Logger LOG = LoggerFactory.getLogger(SubstatementContext.class);
56
57     private final StatementContextBase<?, ?, ?> parent;
58     private final A argument;
59
60     /**
61      * config statements are not all that common which means we are performing a recursive search towards the root
62      * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
63      * for the (usually non-existent) config statement.
64      *
65      * This field maintains a resolution cache, so once we have returned a result, we will keep on returning the same
66      * result without performing any lookups.
67      */
68     private boolean haveConfiguration;
69     private boolean configuration;
70
71     private volatile SchemaPath schemaPath;
72
73     SubstatementContext(final StatementContextBase<?, ?, ?> parent, final StatementDefinitionContext<A, D, E> def,
74             final StatementSourceReference ref, final String rawArgument) {
75         super(def, ref, rawArgument);
76         this.parent = Preconditions.checkNotNull(parent, "Parent must not be null");
77         this.argument = def.parseArgumentValue(this, rawStatementArgument());
78     }
79
80     @SuppressWarnings("unchecked")
81     SubstatementContext(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
82             final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
83         super(original);
84         this.parent = newParent;
85
86         if (newQNameModule != null) {
87             final A originalArg = original.argument;
88             if (originalArg instanceof QName) {
89                 final QName originalQName = (QName) originalArg;
90                 this.argument = (A) getFromNamespace(QNameCacheNamespace.class,
91                         QName.create(newQNameModule, originalQName.getLocalName()));
92             } else if (StmtContextUtils.producesDeclared(original, KeyStatement.class)) {
93                 this.argument = (A) StmtContextUtils.replaceModuleQNameForKey(
94                         (StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?>) original, newQNameModule);
95             } else {
96                 this.argument = original.argument;
97             }
98         } else {
99             this.argument = original.argument;
100         }
101     }
102
103     @Override
104     public StatementContextBase<?, ?, ?> getParentContext() {
105         return parent;
106     }
107
108     @Override
109     public StorageNodeType getStorageNodeType() {
110         return StorageNodeType.STATEMENT_LOCAL;
111     }
112
113     @Override
114     public NamespaceStorageNode getParentNamespaceStorage() {
115         return parent;
116     }
117
118     @Override
119     public Registry getBehaviourRegistry() {
120         return parent.getBehaviourRegistry();
121     }
122
123     @Nonnull
124     @Override
125     public RootStatementContext<?, ?, ?> getRoot() {
126         return parent.getRoot();
127     }
128
129     @Override
130     public A getStatementArgument() {
131         return argument;
132     }
133
134     @Override
135     public StatementContextBase<?, ?, ?> createCopy(final StatementContextBase<?, ?, ?> newParent,
136             final CopyType typeOfCopy) {
137         return createCopy(null, newParent, typeOfCopy);
138     }
139
140     @Override
141     public StatementContextBase<A, D, E> createCopy(final QNameModule newQNameModule,
142             final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
143         Preconditions.checkState(getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
144                 "Attempted to copy statement %s which has completed phase %s", this, getCompletedPhase());
145
146         final SubstatementContext<A, D, E> copy = new SubstatementContext<>(this, newQNameModule, newParent, typeOfCopy);
147
148         copy.appendCopyHistory(typeOfCopy, this.getCopyHistory());
149
150         if (this.getOriginalCtx() != null) {
151             copy.setOriginalCtx(this.getOriginalCtx());
152         } else {
153             copy.setOriginalCtx(this);
154         }
155
156         definition().onStatementAdded(copy);
157
158         copy.copyStatements(this, newQNameModule, typeOfCopy);
159         return copy;
160     }
161
162     private void copyStatements(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
163             final CopyType typeOfCopy) {
164         final Collection<StatementContextBase<?, ?, ?>> declared = original.declaredSubstatements();
165         final Collection<StatementContextBase<?, ?, ?>> effective = original.effectiveSubstatements();
166         final Collection<StatementContextBase<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
167
168         for (final StatementContextBase<?, ?, ?> stmtContext : declared) {
169             if (StmtContextUtils.areFeaturesSupported(stmtContext)) {
170                 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
171             }
172         }
173
174         for (final StatementContextBase<?, ?, ?> stmtContext : effective) {
175             copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
176         }
177
178         addEffectiveSubstatements(buffer);
179     }
180
181     private void copySubstatement(final StatementContextBase<?, ?, ?> stmtContext,
182             final QNameModule newQNameModule, final CopyType typeOfCopy,
183             final Collection<StatementContextBase<?, ?, ?>> buffer) {
184         if (needToCopyByUses(stmtContext)) {
185             final StatementContextBase<?, ?, ?> 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 (Utils.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 StatementContextBase<?, ?, ?> originalCtx = getOriginalCtx();
257             final QName qname = originalCtx != null ? Utils.qNameFromArgument(originalCtx, (String) argument) : Utils
258                     .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 (haveConfiguration) {
299             return configuration;
300         }
301
302         final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
303             ConfigStatement.class);
304         final boolean parentIsConfig = parent.isConfiguration();
305
306         final boolean isConfig;
307         if (configStatement != null) {
308             isConfig = configStatement.getStatementArgument();
309
310             // Validity check: if parent is config=false this cannot be a config=true
311             InferenceException.throwIf(isConfig && !parentIsConfig, getStatementSourceReference(),
312                     "Parent node has config=false, this node must not be specifed as config=true");
313         } else {
314             // If "config" statement is not specified, the default is the same as the parent's "config" value.
315             isConfig = parentIsConfig;
316         }
317
318         // Resolved, make sure we cache this return
319         configuration = isConfig;
320         haveConfiguration = true;
321         return isConfig;
322     }
323
324     @Override
325     public boolean isEnabledSemanticVersioning() {
326         return parent.isEnabledSemanticVersioning();
327     }
328
329     @Override
330     public YangVersion getRootVersion() {
331         return getRoot().getRootVersion();
332     }
333
334     @Override
335     public void setRootVersion(final YangVersion version) {
336         getRoot().setRootVersion(version);
337     }
338
339     @Override
340     public void addMutableStmtToSeal(final MutableStatement mutableStatement) {
341         getRoot().addMutableStmtToSeal(mutableStatement);
342     }
343
344     @Override
345     public void addRequiredModule(final ModuleIdentifier dependency) {
346         getRoot().addRequiredModule(dependency);
347     }
348
349     @Override
350     public void setRootIdentifier(final ModuleIdentifier identifier) {
351         getRoot().setRootIdentifier(identifier);
352     }
353 }