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