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