4637dd08202bb2e0634851aabfa00191d085394b
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / StatementContextBase.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.reactor;
9
10 import com.google.common.base.MoreObjects;
11 import com.google.common.base.MoreObjects.ToStringHelper;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableCollection;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableMultimap;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Multimap;
18 import com.google.common.collect.Multimaps;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.EnumMap;
23 import java.util.EventListener;
24 import java.util.Iterator;
25 import java.util.Optional;
26 import java.util.Set;
27 import javax.annotation.Nonnull;
28 import javax.annotation.Nullable;
29 import org.opendaylight.yangtools.util.OptionalBoolean;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.common.QNameModule;
32 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
33 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
34 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
36 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
37 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
48 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
49 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
50 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
51 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
52 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
57         extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E> {
58     /**
59      * event listener when an item is added to model namespace.
60      */
61     interface OnNamespaceItemAdded extends EventListener {
62         /**
63          * @throws SourceException
64          */
65         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
66     }
67
68     /**
69      * event listener when a parsing {@link ModelProcessingPhase} is completed.
70      */
71     interface OnPhaseFinished extends EventListener {
72         /**
73          * @throws SourceException
74          */
75         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
76     }
77
78     /**
79      * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
80      */
81     interface ContextMutation {
82
83         boolean isFinished();
84     }
85
86     private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
87
88     private final StatementDefinitionContext<A, D, E> definition;
89     private final StatementSourceReference statementDeclSource;
90     private final StmtContext<?, ?, ?> originalCtx;
91     private final CopyHistory copyHistory;
92     private final String rawArgument;
93
94     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
95     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
96     private Collection<Mutable<?, ?, ?>> effective = ImmutableList.of();
97     private Collection<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
98     private StatementMap substatements = StatementMap.empty();
99
100     private boolean isSupportedToBuildEffective = true;
101     private ModelProcessingPhase completedPhase = null;
102     private D declaredInstance;
103     private E effectiveInstance;
104
105     // BooleanFields value
106     private byte supportedByFeatures;
107
108     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
109             final String rawArgument) {
110         this.definition = Preconditions.checkNotNull(def);
111         this.statementDeclSource = Preconditions.checkNotNull(ref);
112         this.rawArgument = def.internArgument(rawArgument);
113         this.copyHistory = CopyHistory.original();
114         this.originalCtx = null;
115     }
116
117     StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
118         this.definition = Preconditions.checkNotNull(original.definition,
119                 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
120         this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
121                 "Statement context statementDeclSource cannot be null copying from: %s",
122                 original.getStatementSourceReference());
123         this.rawArgument = original.rawArgument;
124         this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
125         this.originalCtx = original.getOriginalCtx().orElse(original);
126     }
127
128     @Override
129     public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
130         return effectOfStatement;
131     }
132
133     @Override
134     public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
135         if (effectOfStatement.isEmpty()) {
136             effectOfStatement = new ArrayList<>(1);
137         }
138         effectOfStatement.add(ctx);
139     }
140
141     @Override
142     public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
143         if (ctxs.isEmpty()) {
144             return;
145         }
146
147         if (effectOfStatement.isEmpty()) {
148             effectOfStatement = new ArrayList<>(ctxs.size());
149         }
150         effectOfStatement.addAll(ctxs);
151     }
152
153     @Override
154     public boolean isSupportedByFeatures() {
155         if (OptionalBoolean.isPresent(supportedByFeatures)) {
156             return OptionalBoolean.get(supportedByFeatures);
157         }
158
159         if (isIgnoringIfFeatures()) {
160             supportedByFeatures = OptionalBoolean.of(true);
161             return true;
162         }
163
164         final boolean isParentSupported = isParentSupportedByFeatures();
165         /*
166          * If parent is not supported, then this context is also not supported.
167          * So we do not need to check if-features statements of this context and
168          * we can return false immediately.
169          */
170         if (!isParentSupported) {
171             supportedByFeatures = OptionalBoolean.of(false);
172             return false;
173         }
174
175         /*
176          * If parent is supported, we need to check if-features statements of
177          * this context.
178          */
179         // If the set of supported features has not been provided, all features are supported by default.
180         final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
181                 SupportedFeatures.SUPPORTED_FEATURES);
182         final boolean ret = supportedFeatures == null ? true
183                 : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
184
185         supportedByFeatures = OptionalBoolean.of(ret);
186         return ret;
187     }
188
189     protected abstract boolean isParentSupportedByFeatures();
190
191     protected abstract boolean isIgnoringIfFeatures();
192
193     protected abstract boolean isIgnoringConfig();
194
195     @Override
196     public boolean isSupportedToBuildEffective() {
197         return isSupportedToBuildEffective;
198     }
199
200     @Override
201     public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
202         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
203     }
204
205     @Override
206     public CopyHistory getCopyHistory() {
207         return copyHistory;
208     }
209
210     @Override
211     public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
212         return Optional.ofNullable(originalCtx);
213     }
214
215     @Override
216     public ModelProcessingPhase getCompletedPhase() {
217         return completedPhase;
218     }
219
220     @Override
221     public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
222         this.completedPhase = completedPhase;
223     }
224
225     @Override
226     public abstract StatementContextBase<?, ?, ?> getParentContext();
227
228     /**
229      * @return root context of statement
230      */
231     @Nonnull
232     @Override
233     public abstract RootStatementContext<?, ?, ?> getRoot();
234
235     /**
236      * @return origin of statement
237      */
238     @Nonnull
239     @Override
240     public StatementSource getStatementSource() {
241         return statementDeclSource.getStatementSource();
242     }
243
244     /**
245      * @return reference of statement source
246      */
247     @Nonnull
248     @Override
249     public StatementSourceReference getStatementSourceReference() {
250         return statementDeclSource;
251     }
252
253     @Override
254     public final String rawStatementArgument() {
255         return rawArgument;
256     }
257
258     @Nonnull
259     @Override
260     public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
261         return substatements.values();
262     }
263
264     @Nonnull
265     @Override
266     public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
267         return substatements.values();
268     }
269
270     @Override
271     public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
272         return mutableEffectiveSubstatements();
273     }
274
275     @Nonnull
276     @Override
277     public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
278         if (effective instanceof ImmutableCollection) {
279             return effective;
280         }
281
282         return Collections.unmodifiableCollection(effective);
283     }
284
285     public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
286         if (!effective.isEmpty()) {
287             effective.removeAll(substatements);
288             shrinkEffective();
289         }
290     }
291
292     private void shrinkEffective() {
293         if (effective.isEmpty()) {
294             effective = ImmutableList.of();
295         }
296     }
297
298     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
299         if (effective.isEmpty()) {
300             return;
301         }
302
303         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
304         while (iterator.hasNext()) {
305             final StmtContext<?, ?, ?> next = iterator.next();
306             if (statementDef.equals(next.getPublicDefinition())) {
307                 iterator.remove();
308             }
309         }
310
311         shrinkEffective();
312     }
313
314     /**
315      * Removes a statement context from the effective substatements
316      * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
317      * The statement context is removed only if both statement definition and statement argument match with
318      * one of the effective substatements' statement definition and argument.
319      *
320      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
321      *
322      * @param statementDef statement definition of the statement context to remove
323      * @param statementArg statement argument of the statement context to remove
324      */
325     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
326             final String statementArg) {
327         if (statementArg == null) {
328             removeStatementFromEffectiveSubstatements(statementDef);
329         }
330
331         if (effective.isEmpty()) {
332             return;
333         }
334
335         final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
336         while (iterator.hasNext()) {
337             final Mutable<?, ?, ?> next = iterator.next();
338             if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
339                 iterator.remove();
340             }
341         }
342
343         shrinkEffective();
344     }
345
346     /**
347      * adds effective statement to collection of substatements
348      *
349      * @param substatement substatement
350      * @throws IllegalStateException
351      *             if added in declared phase
352      * @throws NullPointerException
353      *             if statement parameter is null
354      */
355     public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
356         beforeAddEffectiveStatement(1);
357         effective.add(substatement);
358     }
359
360     /**
361      * adds effective statement to collection of substatements
362      *
363      * @param substatements substatements
364      * @throws IllegalStateException
365      *             if added in declared phase
366      * @throws NullPointerException
367      *             if statement parameter is null
368      */
369     public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> substatements) {
370         if (substatements.isEmpty()) {
371             return;
372         }
373
374         substatements.forEach(Preconditions::checkNotNull);
375         beforeAddEffectiveStatement(substatements.size());
376         effective.addAll(substatements);
377     }
378
379     private void beforeAddEffectiveStatement(final int toAdd) {
380         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
381         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
382                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
383                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
384
385         if (effective.isEmpty()) {
386             effective = new ArrayList<>(toAdd);
387         }
388     }
389
390     /**
391      * Create a new substatement at the specified offset.
392      *
393      * @param offset Substatement offset
394      * @param def definition context
395      * @param ref source reference
396      * @param argument statement argument
397      * @return A new substatement
398      */
399     public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
400             final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
401             final String argument) {
402         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
403         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
404                 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
405
406         final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
407         if (implicitParent.isPresent()) {
408             return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
409                     ref, argument);
410         }
411
412         final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
413         substatements = substatements.put(offset, ret);
414         def.onStatementAdded(ret);
415         return ret;
416     }
417
418     private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
419             final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
420         final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
421         return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
422     }
423
424     /**
425      * Lookup substatement by its offset in this statement.
426      *
427      * @param offset Substatement offset
428      * @return Substatement, or null if substatement does not exist.
429      */
430     final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
431         return substatements.get(offset);
432     }
433
434     @Override
435     public D buildDeclared() {
436         Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
437                 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
438         if (declaredInstance == null) {
439             declaredInstance = definition().getFactory().createDeclared(this);
440         }
441         return declaredInstance;
442     }
443
444     @Override
445     public E buildEffective() {
446         if (effectiveInstance == null) {
447             effectiveInstance = definition().getFactory().createEffective(this);
448         }
449         return effectiveInstance;
450     }
451
452     /**
453      * tries to execute current {@link ModelProcessingPhase} of source parsing.
454      *
455      * @param phase
456      *            to be executed (completed)
457      * @return if phase was successfully completed
458      * @throws SourceException
459      *             when an error occured in source parsing
460      */
461     boolean tryToCompletePhase(final ModelProcessingPhase phase) {
462
463         boolean finished = true;
464         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
465         if (!openMutations.isEmpty()) {
466             final Iterator<ContextMutation> it = openMutations.iterator();
467             while (it.hasNext()) {
468                 final ContextMutation current = it.next();
469                 if (current.isFinished()) {
470                     it.remove();
471                 } else {
472                     finished = false;
473                 }
474             }
475
476             if (openMutations.isEmpty()) {
477                 phaseMutation.removeAll(phase);
478                 if (phaseMutation.isEmpty()) {
479                     phaseMutation = ImmutableMultimap.of();
480                 }
481             }
482         }
483
484         for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
485             finished &= child.tryToCompletePhase(phase);
486         }
487         for (final Mutable<?, ?, ?> child : effective) {
488             if (child instanceof StatementContextBase) {
489                 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
490             }
491         }
492
493         if (finished) {
494             onPhaseCompleted(phase);
495             return true;
496         }
497         return false;
498     }
499
500     /**
501      * Occurs on end of {@link ModelProcessingPhase} of source parsing.
502      *
503      * @param phase
504      *            that was to be completed (finished)
505      * @throws SourceException
506      *             when an error occurred in source parsing
507      */
508     private void onPhaseCompleted(final ModelProcessingPhase phase) {
509         completedPhase = phase;
510
511         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
512         if (listeners.isEmpty()) {
513             return;
514         }
515
516         final Iterator<OnPhaseFinished> listener = listeners.iterator();
517         while (listener.hasNext()) {
518             final OnPhaseFinished next = listener.next();
519             if (next.phaseFinished(this, phase)) {
520                 listener.remove();
521             }
522         }
523
524         if (listeners.isEmpty()) {
525             phaseListeners.removeAll(phase);
526             if (phaseListeners.isEmpty()) {
527                 phaseListeners = ImmutableMultimap.of();
528             }
529         }
530     }
531
532     /**
533      * Ends declared section of current node.
534      *
535      * @param ref
536      * @throws SourceException
537      */
538     void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
539         definition().onDeclarationFinished(this, phase);
540     }
541
542     /**
543      * @return statement definition
544      */
545     protected final StatementDefinitionContext<A, D, E> definition() {
546         return definition;
547     }
548
549     @Override
550     protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
551         definition().checkNamespaceAllowed(type);
552     }
553
554     @Override
555     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
556             final V value) {
557         // definition().onNamespaceElementAdded(this, type, key, value);
558     }
559
560     <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
561             final OnNamespaceItemAdded listener) throws SourceException {
562         final Object potential = getFromNamespace(type, key);
563         if (potential != null) {
564             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
565             listener.namespaceItemAdded(this, type, key, potential);
566             return;
567         }
568
569         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
570         Preconditions.checkArgument(behaviour instanceof NamespaceBehaviourWithListeners,
571             "Namespace {} does not support listeners", type);
572
573         final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
574         casted.addValueListener(new ValueAddedListener<K>(this, key) {
575             @Override
576             void onValueAdded(final Object key, final Object value) {
577                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
578             }
579         });
580     }
581
582     /**
583      * See {@link StatementSupport#getPublicView()}.
584      */
585     @Nonnull
586     @Override
587     public StatementDefinition getPublicDefinition() {
588         return definition().getPublicView();
589     }
590
591     @Override
592     public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
593         return getRoot().getSourceContext().newInferenceAction(phase);
594     }
595
596     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
597         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
598     }
599
600     /**
601      * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
602      *
603      * @throws SourceException
604      */
605     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
606
607         Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
608                 getStatementSourceReference());
609         Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
610                 getStatementSourceReference());
611
612         ModelProcessingPhase finishedPhase = completedPhase;
613         while (finishedPhase != null) {
614             if (phase.equals(finishedPhase)) {
615                 listener.phaseFinished(this, finishedPhase);
616                 return;
617             }
618             finishedPhase = finishedPhase.getPreviousPhase();
619         }
620         if (phaseListeners.isEmpty()) {
621             phaseListeners = newMultimap();
622         }
623
624         phaseListeners.put(phase, listener);
625     }
626
627     /**
628      * adds {@link ContextMutation} to {@link ModelProcessingPhase}
629      *
630      * @throws IllegalStateException
631      *             when the mutation was registered after phase was completed
632      */
633     void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
634         ModelProcessingPhase finishedPhase = completedPhase;
635         while (finishedPhase != null) {
636             if (phase.equals(finishedPhase)) {
637                 throw new IllegalStateException("Mutation registered after phase was completed at: "  +
638                         getStatementSourceReference());
639             }
640             finishedPhase = finishedPhase.getPreviousPhase();
641         }
642
643         if (phaseMutation.isEmpty()) {
644             phaseMutation = newMultimap();
645         }
646         phaseMutation.put(phase, mutation);
647     }
648
649     @Override
650     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
651             final KT key,final StmtContext<?, ?, ?> stmt) {
652         addContextToNamespace(namespace, key, stmt);
653     }
654
655     @Override
656     public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
657             final StmtContext<X, Y, Z> stmt, final CopyType type, final QNameModule targetModule) {
658         Preconditions.checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
659                 "Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
660
661         Preconditions.checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
662
663         final SubstatementContext<X, Y, Z> original = (SubstatementContext<X, Y, Z>)stmt;
664         final SubstatementContext<X, Y, Z> copy = new SubstatementContext<>(original, this, type, targetModule);
665
666         original.definition().onStatementAdded(copy);
667         original.copyTo(copy, type, targetModule);
668
669         return copy;
670     }
671
672     final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
673             @Nullable final QNameModule targetModule) {
674         final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
675
676         for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
677             if (stmtContext.isSupportedByFeatures()) {
678                 copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
679             }
680         }
681
682         for (final Mutable<?, ?, ?> stmtContext : effective) {
683             copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
684         }
685
686         target.addEffectiveSubstatements(buffer);
687     }
688
689     private void copySubstatement(final Mutable<?, ?, ?> stmtContext,  final Mutable<?, ?, ?> target,
690             final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
691         if (needToCopyByUses(stmtContext)) {
692             final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
693             LOG.debug("Copying substatement {} for {} as", stmtContext, this, copy);
694             buffer.add(copy);
695         } else if (isReusedByUses(stmtContext)) {
696             LOG.debug("Reusing substatement {} for {}", stmtContext, this);
697             buffer.add(stmtContext);
698         } else {
699             LOG.debug("Skipping statement {}", stmtContext);
700         }
701     }
702
703     // FIXME: revise this, as it seems to be wrong
704     private static final Set<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
705         YangStmtMapping.DESCRIPTION,
706         YangStmtMapping.REFERENCE,
707         YangStmtMapping.STATUS);
708     private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
709         YangStmtMapping.TYPE,
710         YangStmtMapping.TYPEDEF,
711         YangStmtMapping.USES);
712
713     private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
714         final StatementDefinition def = stmtContext.getPublicDefinition();
715         if (REUSED_DEF_SET.contains(def)) {
716             LOG.debug("Will reuse {} statement {}", def, stmtContext);
717             return false;
718         }
719         if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
720             return !YangStmtMapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
721         }
722
723         LOG.debug("Will copy {} statement {}", def, stmtContext);
724         return true;
725     }
726
727     private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
728         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
729     }
730
731     @Override
732     public final String toString() {
733         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
734     }
735
736     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
737         return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);
738     }
739 }