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