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