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