Bug 6669: Mandatory nodes cannot be added to node from another module via augment
[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 com.google.common.collect.Iterables;
14 import java.util.Collection;
15 import java.util.List;
16 import java.util.Objects;
17 import java.util.Set;
18 import org.opendaylight.yangtools.yang.common.QName;
19 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
20 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
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.StmtContextUtils;
26 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
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 CopyType typeOfCopy = sourceCtx.getParentContext().getPublicDefinition()
48                 .getDeclaredRepresentationClass().equals(UsesStatement.class) ? CopyType.ADDED_BY_USES_AUGMENTATION
49                 : CopyType.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 CopyType typeOfCopy = sourceCtx.getParentContext().getPublicDefinition()
69                 .getDeclaredRepresentationClass().equals(UsesStatement.class) ? CopyType.ADDED_BY_USES_AUGMENTATION
70                 : CopyType.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 CopyType typeOfCopy) {
86
87         if (sourceCtx.getPublicDefinition().getDeclaredRepresentationClass().equals(WhenStatement.class)) {
88             return;
89         }
90
91         if (typeOfCopy == CopyType.ADDED_BY_AUGMENTATION && reguiredCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
92             checkForMandatoryNodes(sourceCtx);
93         }
94
95         final List<StatementContextBase<?, ?, ?>> targetSubStatements = new Builder<StatementContextBase<?, ?, ?>>()
96                 .addAll(targetCtx.declaredSubstatements()).addAll(targetCtx.effectiveSubstatements()).build();
97
98         for (final StatementContextBase<?, ?, ?> subStatement : targetSubStatements) {
99
100             final boolean sourceIsDataNode = DataDefinitionStatement.class.isAssignableFrom(sourceCtx
101                     .getPublicDefinition().getDeclaredRepresentationClass());
102             final boolean targetIsDataNode = DataDefinitionStatement.class.isAssignableFrom(subStatement
103                     .getPublicDefinition().getDeclaredRepresentationClass());
104             final boolean qNamesEqual = sourceIsDataNode && targetIsDataNode
105                     && Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument());
106
107             InferenceException.throwIf(qNamesEqual, sourceCtx.getStatementSourceReference(),
108                     "An augment cannot add node named '%s' because this name is already used in target",
109                     sourceCtx.rawStatementArgument());
110         }
111     }
112
113     private static void checkForMandatoryNodes(final StatementContextBase<?, ?, ?> sourceCtx) {
114         if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
115             /*
116              * We need to iterate over both declared and effective sub-statements,
117              * because a mandatory node can be:
118              * a) declared in augment body
119              * b) added to augment body also via uses of a grouping and
120              * such sub-statements are stored in effective sub-statements collection.
121              */
122             for (final StatementContextBase<?, ?, ?> sourceSubStatement : Iterables.concat(
123                     sourceCtx.declaredSubstatements(), sourceCtx.declaredSubstatements())) {
124                 checkForMandatoryNodes(sourceSubStatement);
125             }
126         }
127
128         InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx),
129                 sourceCtx.getStatementSourceReference(),
130                 "An augment cannot add node '%s' because it is mandatory and in module different than target",
131                 sourceCtx.rawStatementArgument());
132     }
133
134     private static boolean reguiredCheckOfMandatoryNodes(final StatementContextBase<?, ?, ?> sourceCtx,
135             StatementContextBase<?, ?, ?> targetCtx) {
136         /*
137          * If the statement argument is not QName, it cannot be mandatory
138          * statement, therefore return false and skip mandatory nodes validation
139          */
140         if (!(sourceCtx.getStatementArgument() instanceof QName)) {
141             return false;
142         }
143         final QName sourceStmtQName = (QName) sourceCtx.getStatementArgument();
144
145         final RootStatementContext<?, ?, ?> root = targetCtx.getRoot();
146         do {
147             Verify.verify(targetCtx.getStatementArgument() instanceof QName,
148                     "Argument of augment target statement must be QName.");
149             final QName targetStmtQName = (QName) targetCtx.getStatementArgument();
150             /*
151              * If target is from another module, return true and perform
152              * mandatory nodes validation
153              */
154             if (!Utils.belongsToTheSameModule(targetStmtQName, sourceStmtQName)) {
155                 return true;
156             } else {
157                 /*
158                  * If target or one of its parent is a presence container from
159                  * the same module, return false and skip mandatory nodes
160                  * validation
161                  */
162                 if (StmtContextUtils.isPresenceContainer(targetCtx)) {
163                     return false;
164                 }
165             }
166         } while ((targetCtx = targetCtx.getParentContext()) != root);
167
168         /*
169          * All target node's parents belong to the same module as source node,
170          * therefore return false and skip mandatory nodes validation.
171          */
172         return false;
173     }
174
175     private static final Set<Rfc6020Mapping> NOCOPY_DEF_SET = ImmutableSet.of(Rfc6020Mapping.USES, Rfc6020Mapping.WHEN,
176             Rfc6020Mapping.DESCRIPTION, Rfc6020Mapping.REFERENCE, Rfc6020Mapping.STATUS);
177
178     public static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
179         return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
180     }
181
182     private static final Set<Rfc6020Mapping> REUSED_DEF_SET = ImmutableSet.of(Rfc6020Mapping.TYPEDEF);
183
184     public static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
185         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
186     }
187
188     static boolean isSupportedAugmentTarget(final StatementContextBase<?, ?, ?> substatementCtx) {
189
190         /*
191          * :TODO Substatement must be allowed augment target type e.g.
192          * Container, etc... and must not be for example grouping, identity etc.
193          * It is problem in case when more than one substatements have the same
194          * QName, for example Grouping and Container are siblings and they have
195          * the same QName. We must find the Container and the Grouping must be
196          * ignored as disallowed augment target.
197          */
198
199         final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(ValidationBundlesNamespace.class,
200                 ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
201
202         // if no allowed target is returned we consider all targets allowed
203         return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
204                 || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());
205     }
206 }