BUG-6522: create a specialized CopyHistory object
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / rfc6020 / GroupingUtils.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.Preconditions;
11 import com.google.common.collect.ImmutableSet;
12 import java.util.Collection;
13 import java.util.Set;
14 import org.opendaylight.yangtools.yang.common.QName;
15 import org.opendaylight.yangtools.yang.common.QNameModule;
16 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
17 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
18 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
19 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
20 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
21 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
22 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
23 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
24 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
25 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
26 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
27 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
28 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
29 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
30 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 public final class GroupingUtils {
35
36     private static final Logger LOG = LoggerFactory.getLogger(GroupingUtils.class);
37
38     private GroupingUtils() {
39         throw new UnsupportedOperationException();
40     }
41
42     /**
43      * @param sourceGrpStmtCtx
44      *            source grouping statement context
45      * @param targetCtx
46      *            target context
47      * @param usesNode
48      *            uses node
49      * @throws SourceException
50      *             instance of SourceException
51      */
52     public static void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceGrpStmtCtx,
53             final StatementContextBase<?, ?, ?> targetCtx,
54             final StmtContext.Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode) {
55
56         final QNameModule newQNameModule = getNewQNameModule(targetCtx, sourceGrpStmtCtx);
57         copyDeclaredStmts(sourceGrpStmtCtx, targetCtx, usesNode, newQNameModule);
58         copyEffectiveStmts(sourceGrpStmtCtx, targetCtx, usesNode, newQNameModule);
59     }
60
61     public static void copyDeclaredStmts(final StatementContextBase<?, ?, ?> sourceGrpStmtCtx,
62             final StatementContextBase<?, ?, ?> targetCtx,
63             final StmtContext.Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode,
64             final QNameModule newQNameModule) {
65         for (final StatementContextBase<?, ?, ?> originalStmtCtx : sourceGrpStmtCtx.declaredSubstatements()) {
66             if (!StmtContextUtils.areFeaturesSupported(originalStmtCtx)) {
67                 continue;
68             }
69             if (needToCopyByUses(originalStmtCtx)) {
70                 final StatementContextBase<?, ?, ?> copy = originalStmtCtx.createCopy(newQNameModule, targetCtx,
71                         CopyType.ADDED_BY_USES);
72                 targetCtx.addEffectiveSubstatement(copy);
73                 usesNode.addAsEffectOfStatement(copy);
74             } else if (isReusedByUsesOnTop(originalStmtCtx)) {
75                 targetCtx.addEffectiveSubstatement(originalStmtCtx);
76                 usesNode.addAsEffectOfStatement(originalStmtCtx);
77             }
78         }
79     }
80
81     public static void copyEffectiveStmts(final StatementContextBase<?, ?, ?> sourceGrpStmtCtx,
82             final StatementContextBase<?, ?, ?> targetCtx,
83             final StmtContext.Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode,
84             final QNameModule newQNameModule) {
85         for (final StatementContextBase<?, ?, ?> originalStmtCtx : sourceGrpStmtCtx.effectiveSubstatements()) {
86             if (needToCopyByUses(originalStmtCtx)) {
87                 final StatementContextBase<?, ?, ?> copy = originalStmtCtx.createCopy(newQNameModule, targetCtx,
88                         CopyType.ADDED_BY_USES);
89                 targetCtx.addEffectiveSubstatement(copy);
90                 usesNode.addAsEffectOfStatement(copy);
91             } else if (isReusedByUsesOnTop(originalStmtCtx)) {
92                 targetCtx.addEffectiveSubstatement(originalStmtCtx);
93                 usesNode.addAsEffectOfStatement(originalStmtCtx);
94             }
95         }
96     }
97
98     public static QNameModule getNewQNameModule(final StatementContextBase<?, ?, ?> targetCtx,
99             final StmtContext<?, ?, ?> stmtContext) {
100         if (needToCreateNewQName(stmtContext.getPublicDefinition())) {
101             if (targetCtx.isRootContext()) {
102                 return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx);
103             }
104             if (targetCtx.getPublicDefinition() == Rfc6020Mapping.AUGMENT) {
105                 return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx.getRoot());
106             }
107
108             final Object targetStmtArgument = targetCtx.getStatementArgument();
109             final Object sourceStmtArgument = stmtContext.getStatementArgument();
110             if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) {
111                 return ((QName) targetStmtArgument).getModule();
112             } else {
113                 return null;
114             }
115         } else {
116             return null;
117         }
118     }
119
120     public static boolean needToCreateNewQName(final StatementDefinition publicDefinition) {
121         return true;
122     }
123
124     private static final Set<Rfc6020Mapping> NOCOPY_DEF_SET = ImmutableSet.of(Rfc6020Mapping.USES,
125             Rfc6020Mapping.TYPEDEF, Rfc6020Mapping.TYPE);
126     private static final Set<Rfc6020Mapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(Rfc6020Mapping.DESCRIPTION,
127             Rfc6020Mapping.REFERENCE, Rfc6020Mapping.STATUS);
128     private static final Set<Rfc6020Mapping> REUSED_DEF_SET = ImmutableSet.of(Rfc6020Mapping.TYPEDEF,
129             Rfc6020Mapping.TYPE, Rfc6020Mapping.USES);
130     private static final Set<Rfc6020Mapping> TOP_REUSED_DEF_SET = ImmutableSet.of(Rfc6020Mapping.TYPEDEF,
131             Rfc6020Mapping.TYPE);
132
133     public static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
134         final StatementDefinition def = stmtContext.getPublicDefinition();
135
136         return !(NOCOPY_DEF_SET.contains(def) || (NOCOPY_FROM_GROUPING_SET.contains(def) && Rfc6020Mapping.GROUPING
137                 .equals(stmtContext.getParentContext().getPublicDefinition())));
138     }
139
140     public static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
141         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
142     }
143
144     public static boolean isReusedByUsesOnTop(final StmtContext<?, ?, ?> stmtContext) {
145         return TOP_REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
146     }
147
148     public static void resolveUsesNode(
149             final Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode,
150             final StatementContextBase<?, ?, ?> targetNodeStmtCtx) {
151         for (final StatementContextBase<?, ?, ?> subStmtCtx : usesNode.declaredSubstatements()) {
152             if (StmtContextUtils.producesDeclared(subStmtCtx, RefineStatement.class)) {
153                 performRefine(subStmtCtx, targetNodeStmtCtx);
154             }
155         }
156     }
157
158     private static void performRefine(final StatementContextBase<?, ?, ?> refineCtx,
159             final StatementContextBase<?, ?, ?> usesParentCtx) {
160
161         final Object refineArgument = refineCtx.getStatementArgument();
162         Preconditions.checkArgument(refineArgument instanceof SchemaNodeIdentifier,
163                 "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier. At %s", refineArgument,
164                 refineCtx.getStatementSourceReference());
165
166         final SchemaNodeIdentifier refineTargetNodeIdentifier = (SchemaNodeIdentifier) refineArgument;
167         final StatementContextBase<?, ?, ?> refineTargetNodeCtx = Utils.findNode(usesParentCtx,
168                 refineTargetNodeIdentifier);
169         Preconditions.checkArgument(refineTargetNodeCtx != null, "Refine target node %s not found. At %s",
170                 refineTargetNodeIdentifier, refineCtx.getStatementSourceReference());
171         if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
172             LOG.debug(
173                     "Refine node '{}' in uses '{}' has target node unknown statement '{}'. Refine has been skipped. At line: {}",
174                     refineCtx.getStatementArgument(), refineCtx.getParentContext().getStatementArgument(),
175                     refineTargetNodeCtx.getStatementArgument(), refineCtx.getStatementSourceReference());
176             refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
177             return;
178         }
179
180         addOrReplaceNodes(refineCtx, refineTargetNodeCtx);
181         refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
182     }
183
184     private static void addOrReplaceNodes(final StatementContextBase<?, ?, ?> refineCtx,
185             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
186         for (final StatementContextBase<?, ?, ?> refineSubstatementCtx : refineCtx.declaredSubstatements()) {
187             if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
188                 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
189             }
190         }
191     }
192
193     private static void addOrReplaceNode(final StatementContextBase<?, ?, ?> refineSubstatementCtx,
194             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
195
196         final StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
197
198         SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
199                 refineSubstatementCtx.getStatementSourceReference(),
200                 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
201                 refineSubstatementCtx.getRoot().getStatementArgument(), refineSubstatementCtx.getParentContext()
202                         .getStatementArgument(), refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx
203                         .getPublicDefinition());
204
205         if (isAllowedToAddByRefine(refineSubstatementDef)) {
206             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
207         } else {
208             refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef);
209             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
210         }
211     }
212
213     private static final Set<Rfc6020Mapping> ALLOWED_TO_ADD_BY_REFINE_DEF_SET = ImmutableSet.of(Rfc6020Mapping.MUST);
214
215     private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
216         return ALLOWED_TO_ADD_BY_REFINE_DEF_SET.contains(publicDefinition);
217     }
218
219     private static boolean isSupportedRefineSubstatement(final StatementContextBase<?, ?, ?> refineSubstatementCtx) {
220         final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
221                 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
222
223         return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
224                 || supportedRefineSubstatements.contains(refineSubstatementCtx.getPublicDefinition())
225                 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
226     }
227
228     private static boolean isSupportedRefineTarget(final StatementContextBase<?, ?, ?> refineSubstatementCtx,
229             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
230
231         final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS
232                 .get(refineSubstatementCtx.getPublicDefinition());
233
234         return supportedRefineTargets == null || supportedRefineTargets.isEmpty()
235                 || supportedRefineTargets.contains(refineTargetNodeCtx.getPublicDefinition());
236     }
237 }