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