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