BUG-6972: Consolidate copy operations
[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         for (final StatementContextBase<?, ?, ?> original : sourceGrpStmtCtx.declaredSubstatements()) {
58             if (StmtContextUtils.areFeaturesSupported(original)) {
59                 copyStatement(original, targetCtx, usesNode, newQNameModule);
60             }
61         }
62
63         for (final StatementContextBase<?, ?, ?> original : sourceGrpStmtCtx.effectiveSubstatements()) {
64             copyStatement(original, targetCtx, usesNode, newQNameModule);
65         }
66     }
67
68     private static void copyStatement(final StatementContextBase<?, ?, ?> original,
69             final StatementContextBase<?, ?, ?> targetCtx,
70             final StmtContext.Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> targetUses,
71             final QNameModule targetModule) {
72         if (needToCopyByUses(original)) {
73             final StatementContextBase<?, ?, ?> copy = original.createCopy(targetModule, targetCtx,
74                     CopyType.ADDED_BY_USES);
75             targetCtx.addEffectiveSubstatement(copy);
76             targetUses.addAsEffectOfStatement(copy);
77         } else if (isReusedByUsesOnTop(original)) {
78             targetCtx.addEffectiveSubstatement(original);
79             targetUses.addAsEffectOfStatement(original);
80         }
81     }
82
83     public static QNameModule getNewQNameModule(final StatementContextBase<?, ?, ?> targetCtx,
84             final StmtContext<?, ?, ?> stmtContext) {
85         if (needToCreateNewQName(stmtContext.getPublicDefinition())) {
86             if (targetCtx.isRootContext()) {
87                 return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx);
88             }
89             if (targetCtx.getPublicDefinition() == Rfc6020Mapping.AUGMENT) {
90                 return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx.getRoot());
91             }
92
93             final Object targetStmtArgument = targetCtx.getStatementArgument();
94             final Object sourceStmtArgument = stmtContext.getStatementArgument();
95             if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) {
96                 return ((QName) targetStmtArgument).getModule();
97             } else {
98                 return null;
99             }
100         } else {
101             return null;
102         }
103     }
104
105     public static boolean needToCreateNewQName(final StatementDefinition publicDefinition) {
106         return true;
107     }
108
109     private static final Set<Rfc6020Mapping> NOCOPY_DEF_SET = ImmutableSet.of(Rfc6020Mapping.USES,
110             Rfc6020Mapping.TYPEDEF, Rfc6020Mapping.TYPE);
111     private static final Set<Rfc6020Mapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(Rfc6020Mapping.DESCRIPTION,
112             Rfc6020Mapping.REFERENCE, Rfc6020Mapping.STATUS);
113     private static final Set<Rfc6020Mapping> REUSED_DEF_SET = ImmutableSet.of(Rfc6020Mapping.TYPEDEF,
114             Rfc6020Mapping.TYPE, Rfc6020Mapping.USES);
115     private static final Set<Rfc6020Mapping> TOP_REUSED_DEF_SET = ImmutableSet.of(Rfc6020Mapping.TYPEDEF,
116             Rfc6020Mapping.TYPE);
117
118     public static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
119         final StatementDefinition def = stmtContext.getPublicDefinition();
120
121         return !(NOCOPY_DEF_SET.contains(def) || (NOCOPY_FROM_GROUPING_SET.contains(def) && Rfc6020Mapping.GROUPING
122                 .equals(stmtContext.getParentContext().getPublicDefinition())));
123     }
124
125     public static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
126         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
127     }
128
129     public static boolean isReusedByUsesOnTop(final StmtContext<?, ?, ?> stmtContext) {
130         return TOP_REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
131     }
132
133     public static void resolveUsesNode(
134             final Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode,
135             final StatementContextBase<?, ?, ?> targetNodeStmtCtx) {
136         for (final StatementContextBase<?, ?, ?> subStmtCtx : usesNode.declaredSubstatements()) {
137             if (StmtContextUtils.producesDeclared(subStmtCtx, RefineStatement.class)) {
138                 performRefine(subStmtCtx, targetNodeStmtCtx);
139             }
140         }
141     }
142
143     private static void performRefine(final StatementContextBase<?, ?, ?> refineCtx,
144             final StatementContextBase<?, ?, ?> usesParentCtx) {
145
146         final Object refineArgument = refineCtx.getStatementArgument();
147         Preconditions.checkArgument(refineArgument instanceof SchemaNodeIdentifier,
148                 "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier. At %s", refineArgument,
149                 refineCtx.getStatementSourceReference());
150
151         final SchemaNodeIdentifier refineTargetNodeIdentifier = (SchemaNodeIdentifier) refineArgument;
152         final StatementContextBase<?, ?, ?> refineTargetNodeCtx = Utils.findNode(usesParentCtx,
153                 refineTargetNodeIdentifier);
154         Preconditions.checkArgument(refineTargetNodeCtx != null, "Refine target node %s not found. At %s",
155                 refineTargetNodeIdentifier, refineCtx.getStatementSourceReference());
156         if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
157             LOG.debug(
158                     "Refine node '{}' in uses '{}' has target node unknown statement '{}'. Refine has been skipped. At line: {}",
159                     refineCtx.getStatementArgument(), refineCtx.getParentContext().getStatementArgument(),
160                     refineTargetNodeCtx.getStatementArgument(), refineCtx.getStatementSourceReference());
161             refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
162             return;
163         }
164
165         addOrReplaceNodes(refineCtx, refineTargetNodeCtx);
166         refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
167     }
168
169     private static void addOrReplaceNodes(final StatementContextBase<?, ?, ?> refineCtx,
170             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
171         for (final StatementContextBase<?, ?, ?> refineSubstatementCtx : refineCtx.declaredSubstatements()) {
172             if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
173                 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
174             }
175         }
176     }
177
178     private static void addOrReplaceNode(final StatementContextBase<?, ?, ?> refineSubstatementCtx,
179             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
180
181         final StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
182
183         SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
184                 refineSubstatementCtx.getStatementSourceReference(),
185                 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
186                 refineSubstatementCtx.getRoot().getStatementArgument(), refineSubstatementCtx.getParentContext()
187                         .getStatementArgument(), refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx
188                         .getPublicDefinition());
189
190         if (isAllowedToAddByRefine(refineSubstatementDef)) {
191             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
192         } else {
193             refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef);
194             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
195         }
196     }
197
198     private static final Set<Rfc6020Mapping> ALLOWED_TO_ADD_BY_REFINE_DEF_SET = ImmutableSet.of(Rfc6020Mapping.MUST);
199
200     private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
201         return ALLOWED_TO_ADD_BY_REFINE_DEF_SET.contains(publicDefinition);
202     }
203
204     private static boolean isSupportedRefineSubstatement(final StatementContextBase<?, ?, ?> refineSubstatementCtx) {
205         final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
206                 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
207
208         return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
209                 || supportedRefineSubstatements.contains(refineSubstatementCtx.getPublicDefinition())
210                 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
211     }
212
213     private static boolean isSupportedRefineTarget(final StatementContextBase<?, ?, ?> refineSubstatementCtx,
214             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
215
216         final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS
217                 .get(refineSubstatementCtx.getPublicDefinition());
218
219         return supportedRefineTargets == null || supportedRefineTargets.isEmpty()
220                 || supportedRefineTargets.contains(refineTargetNodeCtx.getPublicDefinition());
221     }
222 }