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