Bug 6158: Optimization of if-feaures resolution during SchemaContext assembly
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / rfc6020 / AugmentUtils.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.rfc6020;
9
10 import com.google.common.base.Verify;
11 import com.google.common.collect.ImmutableList.Builder;
12 import com.google.common.collect.ImmutableSet;
13 import java.util.Collection;
14 import java.util.List;
15 import java.util.Objects;
16 import java.util.Set;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
19 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
20 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
21 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
22 import org.opendaylight.yangtools.yang.model.api.stmt.WhenStatement;
23 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
24 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
25 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.TypeOfCopy;
26 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
27 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
28 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
29 import org.opendaylight.yangtools.yang.parser.stmt.reactor.RootStatementContext;
30 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
31
32 // FIXME: Move this to the AugmentStatementDefinition#ApplyAction
33 public final class AugmentUtils {
34     private AugmentUtils() {
35     }
36
37     public static void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
38             final StatementContextBase<?, ?, ?> targetCtx) {
39         copyDeclaredStmts(sourceCtx, targetCtx);
40         copyEffectiveStmts(sourceCtx, targetCtx);
41     }
42
43     // FIXME: Declared statements should not be copied.
44     private static void copyDeclaredStmts(final StatementContextBase<?, ?, ?> sourceCtx,
45             final StatementContextBase<?, ?, ?> targetCtx) {
46
47         final TypeOfCopy typeOfCopy = sourceCtx.getParentContext().getPublicDefinition()
48                 .getDeclaredRepresentationClass().equals(UsesStatement.class) ? TypeOfCopy.ADDED_BY_USES_AUGMENTATION
49                 : TypeOfCopy.ADDED_BY_AUGMENTATION;
50
51         for (final StatementContextBase<?, ?, ?> originalStmtCtx : sourceCtx.declaredSubstatements()) {
52             if (!StmtContextUtils.areFeaturesSupported(originalStmtCtx)) {
53                 continue;
54             }
55             if (needToCopyByAugment(originalStmtCtx)) {
56                 validateNodeCanBeCopiedByAugment(originalStmtCtx, targetCtx, typeOfCopy);
57
58                 final StatementContextBase<?, ?, ?> copy = originalStmtCtx.createCopy(targetCtx, typeOfCopy);
59                 targetCtx.addEffectiveSubstatement(copy);
60             } else if (isReusedByAugment(originalStmtCtx)) {
61                 targetCtx.addEffectiveSubstatement(originalStmtCtx);
62             }
63         }
64     }
65
66     private static void copyEffectiveStmts(final StatementContextBase<?, ?, ?> sourceCtx,
67             final StatementContextBase<?, ?, ?> targetCtx) {
68         final TypeOfCopy typeOfCopy = sourceCtx.getParentContext().getPublicDefinition()
69                 .getDeclaredRepresentationClass().equals(UsesStatement.class) ? TypeOfCopy.ADDED_BY_USES_AUGMENTATION
70                 : TypeOfCopy.ADDED_BY_AUGMENTATION;
71
72         for (final StatementContextBase<?, ?, ?> originalStmtCtx : sourceCtx.effectiveSubstatements()) {
73             if (needToCopyByAugment(originalStmtCtx)) {
74                 validateNodeCanBeCopiedByAugment(originalStmtCtx, targetCtx, typeOfCopy);
75
76                 final StatementContextBase<?, ?, ?> copy = originalStmtCtx.createCopy(targetCtx, typeOfCopy);
77                 targetCtx.addEffectiveSubstatement(copy);
78             } else if (isReusedByAugment(originalStmtCtx)) {
79                 targetCtx.addEffectiveSubstatement(originalStmtCtx);
80             }
81         }
82     }
83
84     private static void validateNodeCanBeCopiedByAugment(final StatementContextBase<?, ?, ?> sourceCtx,
85             final StatementContextBase<?, ?, ?> targetCtx, final TypeOfCopy typeOfCopy) {
86
87         if (sourceCtx.getPublicDefinition().getDeclaredRepresentationClass().equals(WhenStatement.class)) {
88             return;
89         }
90
91         if (typeOfCopy == TypeOfCopy.ADDED_BY_AUGMENTATION && reguiredCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
92             final List<StatementContextBase<?, ?, ?>> sourceSubStatements = new Builder<StatementContextBase<?, ?, ?>>()
93                     .addAll(sourceCtx.declaredSubstatements()).addAll(sourceCtx.effectiveSubstatements()).build();
94
95             for (final StatementContextBase<?, ?, ?> sourceSubStatement : sourceSubStatements) {
96                 InferenceException.throwIf(MandatoryStatement.class.equals(sourceSubStatement.getPublicDefinition()
97                         .getDeclaredRepresentationClass()), sourceCtx.getStatementSourceReference(),
98                         "An augment cannot add node '%s' because it is mandatory and in module different from target",
99                         sourceCtx.rawStatementArgument());
100             }
101         }
102
103         final List<StatementContextBase<?, ?, ?>> targetSubStatements = new Builder<StatementContextBase<?, ?, ?>>()
104                 .addAll(targetCtx.declaredSubstatements()).addAll(targetCtx.effectiveSubstatements()).build();
105
106         for (final StatementContextBase<?, ?, ?> subStatement : targetSubStatements) {
107
108             final boolean sourceIsDataNode = DataDefinitionStatement.class.isAssignableFrom(sourceCtx
109                     .getPublicDefinition().getDeclaredRepresentationClass());
110             final boolean targetIsDataNode = DataDefinitionStatement.class.isAssignableFrom(subStatement
111                     .getPublicDefinition().getDeclaredRepresentationClass());
112             final boolean qNamesEqual = sourceIsDataNode && targetIsDataNode
113                     && Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument());
114
115             InferenceException.throwIf(qNamesEqual, sourceCtx.getStatementSourceReference(),
116                     "An augment cannot add node named '%s' because this name is already used in target",
117                     sourceCtx.rawStatementArgument());
118         }
119     }
120
121     private static boolean reguiredCheckOfMandatoryNodes(final StatementContextBase<?, ?, ?> sourceCtx,
122             StatementContextBase<?, ?, ?> targetCtx) {
123         /*
124          * If the statement argument is not QName, it cannot be mandatory
125          * statement, therefore return false and skip mandatory nodes validation
126          */
127         if (!(sourceCtx.getStatementArgument() instanceof QName)) {
128             return false;
129         }
130         final QName sourceStmtQName = (QName) sourceCtx.getStatementArgument();
131
132         final RootStatementContext<?, ?, ?> root = targetCtx.getRoot();
133         do {
134             Verify.verify(targetCtx.getStatementArgument() instanceof QName,
135                     "Argument of augment target statement must be QName.");
136             final QName targetStmtQName = (QName) targetCtx.getStatementArgument();
137             /*
138              * If target is from another module, return true and perform
139              * mandatory nodes validation
140              */
141             if (!Utils.belongsToTheSameModule(targetStmtQName, sourceStmtQName)) {
142                 return true;
143             } else {
144                 /*
145                  * If target or one of its parent is a presence container from
146                  * the same module, return false and skip mandatory nodes
147                  * validation
148                  */
149                 if (Utils.isPresenceContainer(targetCtx)) {
150                     return false;
151                 }
152             }
153         } while ((targetCtx = targetCtx.getParentContext()) != root);
154
155         /*
156          * All target node's parents belong to the same module as source node,
157          * therefore return false and skip mandatory nodes validation.
158          */
159         return false;
160     }
161
162     private static final Set<Rfc6020Mapping> NOCOPY_DEF_SET = ImmutableSet.of(Rfc6020Mapping.USES, Rfc6020Mapping.WHEN,
163             Rfc6020Mapping.DESCRIPTION, Rfc6020Mapping.REFERENCE, Rfc6020Mapping.STATUS);
164
165     public static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
166         return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
167     }
168
169     private static final Set<Rfc6020Mapping> REUSED_DEF_SET = ImmutableSet.of(Rfc6020Mapping.TYPEDEF);
170
171     public static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
172         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
173     }
174
175     static boolean isSupportedAugmentTarget(final StatementContextBase<?, ?, ?> substatementCtx) {
176
177         /*
178          * :TODO Substatement must be allowed augment target type e.g.
179          * Container, etc... and must not be for example grouping, identity etc.
180          * It is problem in case when more than one substatements have the same
181          * QName, for example Grouping and Container are siblings and they have
182          * the same QName. We must find the Container and the Grouping must be
183          * ignored as disallowed augment target.
184          */
185
186         final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(ValidationBundlesNamespace.class,
187                 ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
188
189         // if no allowed target is returned we consider all targets allowed
190         return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
191                 || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());
192     }
193 }