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