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