BUG-6522: grow StatementContext collections lazily
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / SubstatementContext.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.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Verify;
13 import com.google.common.collect.ImmutableSet;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Set;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.common.QNameModule;
19 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
20 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
21 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
22 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
23 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
24 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
30 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.QNameCacheNamespace;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
38 import org.opendaylight.yangtools.yang.parser.spi.source.AugmentToChoiceNamespace;
39 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
41 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> extends
46         StatementContextBase<A, D, E> {
47     private static final Logger LOG = LoggerFactory.getLogger(SubstatementContext.class);
48
49     private final StatementContextBase<?, ?, ?> parent;
50     private final A argument;
51     private volatile SchemaPath schemaPath;
52
53     SubstatementContext(final StatementContextBase<?, ?, ?> parent, final ContextBuilder<A, D, E> builder) {
54         super(builder);
55         this.parent = Preconditions.checkNotNull(parent, "Parent must not be null");
56         this.argument = builder.getDefinition().parseArgumentValue(this, builder.getRawArgument());
57     }
58
59     @SuppressWarnings("unchecked")
60     SubstatementContext(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
61             final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
62         super(original);
63         this.parent = newParent;
64
65         if (newQNameModule != null) {
66             if (original.argument instanceof QName) {
67                 final QName originalQName = (QName) original.argument;
68                 this.argument = (A) getFromNamespace(QNameCacheNamespace.class,
69                         QName.create(newQNameModule, originalQName.getLocalName()));
70             } else if (StmtContextUtils.producesDeclared(original, KeyStatement.class)) {
71                 this.argument = (A) StmtContextUtils.replaceModuleQNameForKey(
72                         (StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?>) original, newQNameModule);
73             } else {
74                 this.argument = original.argument;
75             }
76         } else {
77             this.argument = original.argument;
78         }
79     }
80
81     @Override
82     public StatementContextBase<?, ?, ?> getParentContext() {
83         return parent;
84     }
85
86     @Override
87     public NamespaceStorageNode getParentNamespaceStorage() {
88         return parent;
89     }
90
91     @Override
92     public Registry getBehaviourRegistry() {
93         return parent.getBehaviourRegistry();
94     }
95
96     @Override
97     public RootStatementContext<?, ?, ?> getRoot() {
98         return parent.getRoot();
99     }
100
101     @Override
102     public A getStatementArgument() {
103         return argument;
104     }
105
106     @Override
107     public StatementContextBase<?, ?, ?> createCopy(final StatementContextBase<?, ?, ?> newParent,
108             final CopyType typeOfCopy) {
109         return createCopy(null, newParent, typeOfCopy);
110     }
111
112     @Override
113     public StatementContextBase<A, D, E> createCopy(final QNameModule newQNameModule,
114             final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
115         final SubstatementContext<A, D, E> copy = new SubstatementContext<>(this, newQNameModule, newParent, typeOfCopy);
116
117         copy.appendCopyHistory(typeOfCopy, this.getCopyHistory());
118
119         if (this.getOriginalCtx() != null) {
120             copy.setOriginalCtx(this.getOriginalCtx());
121         } else {
122             copy.setOriginalCtx(this);
123         }
124
125         definition().onStatementAdded(copy);
126
127         copy.copyStatements(this, newQNameModule, typeOfCopy);
128         return copy;
129     }
130
131     private void copyStatements(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
132             final CopyType typeOfCopy) {
133         final Collection<StatementContextBase<?, ?, ?>> declared = original.declaredSubstatements();
134         final Collection<StatementContextBase<?, ?, ?>> effective = original.effectiveSubstatements();
135         final Collection<StatementContextBase<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
136
137         for (final StatementContextBase<?, ?, ?> stmtContext : declared) {
138             if (StmtContextUtils.areFeaturesSupported(stmtContext)) {
139                 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
140             }
141         }
142
143         for (final StatementContextBase<?, ?, ?> stmtContext : effective) {
144             copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
145         }
146
147         addEffectiveSubstatements(buffer);
148     }
149
150     private void copySubstatement(final StatementContextBase<?, ?, ?> stmtContext,
151             final QNameModule newQNameModule, final CopyType typeOfCopy,
152             final Collection<StatementContextBase<?, ?, ?>> buffer) {
153         if (needToCopyByUses(stmtContext)) {
154             final StatementContextBase<?, ?, ?> copy = stmtContext.createCopy(newQNameModule, this, typeOfCopy);
155             LOG.debug("Copying substatement {} for {} as", stmtContext, this, copy);
156             buffer.add(copy);
157         } else if (isReusedByUses(stmtContext)) {
158             LOG.debug("Reusing substatement {} for {}", stmtContext, this);
159             buffer.add(stmtContext);
160         } else {
161             LOG.debug("Skipping statement {}", stmtContext);
162         }
163     }
164
165     // FIXME: revise this, as it seems to be wrong
166     private static final Set<Rfc6020Mapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
167         Rfc6020Mapping.DESCRIPTION,
168         Rfc6020Mapping.REFERENCE,
169         Rfc6020Mapping.STATUS);
170     private static final Set<Rfc6020Mapping> REUSED_DEF_SET = ImmutableSet.of(
171         Rfc6020Mapping.TYPE,
172         Rfc6020Mapping.TYPEDEF,
173         Rfc6020Mapping.USES);
174
175     private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
176         final StatementDefinition def = stmtContext.getPublicDefinition();
177         if (REUSED_DEF_SET.contains(def)) {
178             LOG.debug("Will reuse {} statement {}", def, stmtContext);
179             return false;
180         }
181         if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
182             return !Rfc6020Mapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
183         }
184
185         LOG.debug("Will copy {} statement {}", def, stmtContext);
186         return true;
187     }
188
189     private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
190         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
191     }
192
193     private boolean isSupportedAsShorthandCase() {
194         final Collection<?> supportedCaseShorthands = getFromNamespace(ValidationBundlesNamespace.class,
195                 ValidationBundleType.SUPPORTED_CASE_SHORTHANDS);
196         return supportedCaseShorthands == null || supportedCaseShorthands.contains(getPublicDefinition());
197     }
198
199     private SchemaPath createSchemaPath() {
200         final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
201         Verify.verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
202         final SchemaPath parentPath = maybeParentPath.get();
203
204         if (argument instanceof QName) {
205             final QName qname = (QName) argument;
206             if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
207                 return maybeParentPath.orNull();
208             }
209
210             final SchemaPath path;
211             if ((StmtContextUtils.producesDeclared(getParentContext(), ChoiceStatement.class)
212                     || Boolean.TRUE.equals(parent.getFromNamespace(AugmentToChoiceNamespace.class, parent)))
213                     && isSupportedAsShorthandCase()) {
214                 path = parentPath.createChild(qname);
215             } else {
216                 path = parentPath;
217             }
218             return path.createChild(qname);
219         }
220         if (argument instanceof String) {
221             // FIXME: This may yield illegal argument exceptions
222             final StatementContextBase<?, ?, ?> originalCtx = getOriginalCtx();
223             final QName qname = (originalCtx != null) ? Utils.qNameFromArgument(originalCtx, (String) argument) : Utils
224                     .qNameFromArgument(this, (String) argument);
225             return parentPath.createChild(qname);
226         }
227         if (argument instanceof SchemaNodeIdentifier
228                 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class) || StmtContextUtils
229                         .producesDeclared(this, RefineStatement.class))) {
230
231             return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
232         }
233         if (Utils.isUnknownNode(this)) {
234             return parentPath.createChild(getPublicDefinition().getStatementName());
235         }
236
237         // FIXME: this does not look right
238         return maybeParentPath.orNull();
239     }
240
241     @Override
242     public Optional<SchemaPath> getSchemaPath() {
243         SchemaPath local = schemaPath;
244         if (local == null) {
245             synchronized (this) {
246                 local = schemaPath;
247                 if (local == null) {
248                     local = createSchemaPath();
249                     schemaPath = local;
250                 }
251             }
252
253         }
254
255         return Optional.fromNullable(local);
256     }
257
258     @Override
259     public boolean isRootContext() {
260         return false;
261     }
262
263     @Override
264     public boolean isConfiguration() {
265         final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
266                 ConfigStatement.class);
267
268         /*
269          * If "config" statement is not specified, the default is the same as
270          * the parent schema node's "config" value.
271          */
272         if (configStatement == null) {
273             return parent.isConfiguration();
274         }
275
276         /*
277          * If a parent node has "config" set to "true", the node underneath it
278          * can have "config" set to "true" or "false".
279          */
280         if (parent.isConfiguration()) {
281             return configStatement.getStatementArgument();
282         }
283
284         /*
285          * If a parent node has "config" set to "false", no node underneath it
286          * can have "config" set to "true", therefore only "false" is permitted.
287          */
288         if (!configStatement.getStatementArgument()) {
289             return false;
290         }
291
292         throw new InferenceException(
293                 "Parent node has config statement set to false, therefore no node underneath it can have config set to true",
294                 getStatementSourceReference());
295     }
296
297     @Override
298     public boolean isEnabledSemanticVersioning() {
299         return parent.isEnabledSemanticVersioning();
300     }
301 }