2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.collect.ImmutableSet;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Optional;
17 import javax.annotation.Nonnull;
18 import org.opendaylight.yangtools.util.OptionalBoolean;
19 import org.opendaylight.yangtools.yang.common.QName;
20 import org.opendaylight.yangtools.yang.common.QNameModule;
21 import org.opendaylight.yangtools.yang.common.YangVersion;
22 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
23 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
24 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
25 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
28 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
35 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.QNameCacheNamespace;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
46 import org.opendaylight.yangtools.yang.parser.spi.source.AugmentToChoiceNamespace;
47 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
48 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
49 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> extends
54 StatementContextBase<A, D, E> {
55 private static final Logger LOG = LoggerFactory.getLogger(SubstatementContext.class);
57 private final StatementContextBase<?, ?, ?> parent;
58 private final A argument;
61 * config statements are not all that common which means we are performing a recursive search towards the root
62 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
63 * for the (usually non-existent) config statement.
65 * This field maintains a resolution cache, so once we have returned a result, we will keep on returning the same
66 * result without performing any lookups.
69 private byte configuration;
72 * This field maintains a resolution cache for ignore config, so once we have returned a result, we will
73 * keep on returning the same result without performing any lookups.
76 private byte ignoreConfig;
79 * This field maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
80 * keep on returning the same result without performing any lookups.
83 private byte ignoreIfFeature;
85 private volatile SchemaPath schemaPath;
87 SubstatementContext(final StatementContextBase<?, ?, ?> parent, final StatementDefinitionContext<A, D, E> def,
88 final StatementSourceReference ref, final String rawArgument) {
89 super(def, ref, rawArgument);
90 this.parent = Preconditions.checkNotNull(parent, "Parent must not be null");
91 this.argument = def.parseArgumentValue(this, rawStatementArgument());
94 @SuppressWarnings("unchecked")
95 private SubstatementContext(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
96 final StatementContextBase<?, ?, ?> newParent, final CopyType copyType) {
97 super(original, copyType);
98 this.parent = Preconditions.checkNotNull(newParent);
100 if (newQNameModule != null) {
101 final A originalArg = original.argument;
102 if (originalArg instanceof QName) {
103 final QName originalQName = (QName) originalArg;
104 this.argument = (A) getFromNamespace(QNameCacheNamespace.class,
105 QName.create(newQNameModule, originalQName.getLocalName()));
106 } else if (StmtContextUtils.producesDeclared(original, KeyStatement.class)) {
107 this.argument = (A) StmtContextUtils.replaceModuleQNameForKey(
108 (StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?>) original, newQNameModule);
110 this.argument = original.argument;
113 this.argument = original.argument;
118 public StatementContextBase<?, ?, ?> getParentContext() {
123 public StorageNodeType getStorageNodeType() {
124 return StorageNodeType.STATEMENT_LOCAL;
128 public NamespaceStorageNode getParentNamespaceStorage() {
133 public Registry getBehaviourRegistry() {
134 return parent.getBehaviourRegistry();
139 public RootStatementContext<?, ?, ?> getRoot() {
140 return parent.getRoot();
144 public A getStatementArgument() {
149 public StatementContextBase<A, D, E> createCopy(final StatementContextBase<?, ?, ?> newParent,
150 final CopyType typeOfCopy) {
151 return createCopy(null, newParent, typeOfCopy);
155 public StatementContextBase<A, D, E> createCopy(final QNameModule newQNameModule,
156 final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
157 Preconditions.checkState(getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
158 "Attempted to copy statement %s which has completed phase %s", this, getCompletedPhase());
160 final SubstatementContext<A, D, E> copy = new SubstatementContext<>(this, newQNameModule, newParent, typeOfCopy);
162 definition().onStatementAdded(copy);
164 copy.copyStatements(this, newQNameModule, typeOfCopy);
168 private void copyStatements(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
169 final CopyType typeOfCopy) {
170 final Collection<? extends Mutable<?, ?, ?>> declared = original.mutableDeclaredSubstatements();
171 final Collection<? extends Mutable<?, ?, ?>> effective = original.mutableEffectiveSubstatements();
172 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
174 for (final Mutable<?, ?, ?> stmtContext : declared) {
175 if (stmtContext.isSupportedByFeatures()) {
176 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
180 for (final Mutable<?, ?, ?> stmtContext : effective) {
181 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
184 addEffectiveSubstatements(buffer);
187 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final QNameModule newQNameModule,
188 final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer) {
189 if (needToCopyByUses(stmtContext)) {
190 final Mutable<?, ?, ?> copy = stmtContext.createCopy(newQNameModule, this, typeOfCopy);
191 LOG.debug("Copying substatement {} for {} as", stmtContext, this, copy);
193 } else if (isReusedByUses(stmtContext)) {
194 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
195 buffer.add(stmtContext);
197 LOG.debug("Skipping statement {}", stmtContext);
201 // FIXME: revise this, as it seems to be wrong
202 private static final Set<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
203 YangStmtMapping.DESCRIPTION,
204 YangStmtMapping.REFERENCE,
205 YangStmtMapping.STATUS);
206 private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
207 YangStmtMapping.TYPE,
208 YangStmtMapping.TYPEDEF,
209 YangStmtMapping.USES);
211 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
212 final StatementDefinition def = stmtContext.getPublicDefinition();
213 if (REUSED_DEF_SET.contains(def)) {
214 LOG.debug("Will reuse {} statement {}", def, stmtContext);
217 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
218 return !YangStmtMapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
221 LOG.debug("Will copy {} statement {}", def, stmtContext);
225 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
226 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
229 private boolean isSupportedAsShorthandCase() {
230 final Collection<?> supportedCaseShorthands = getFromNamespace(ValidationBundlesNamespace.class,
231 ValidationBundleType.SUPPORTED_CASE_SHORTHANDS);
232 return supportedCaseShorthands == null || supportedCaseShorthands.contains(getPublicDefinition());
235 private SchemaPath createSchemaPath() {
236 final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
237 Verify.verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
238 final SchemaPath parentPath = maybeParentPath.get();
240 if (StmtContextUtils.isUnknownStatement(this)) {
241 return parentPath.createChild(getPublicDefinition().getStatementName());
243 if (argument instanceof QName) {
244 final QName qname = (QName) argument;
245 if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
246 return maybeParentPath.orElse(null);
249 final SchemaPath path;
250 if ((StmtContextUtils.producesDeclared(getParentContext(), ChoiceStatement.class)
251 || Boolean.TRUE.equals(parent.getFromNamespace(AugmentToChoiceNamespace.class, parent)))
252 && isSupportedAsShorthandCase()) {
253 path = parentPath.createChild(qname);
257 return path.createChild(qname);
259 if (argument instanceof String) {
260 // FIXME: This may yield illegal argument exceptions
261 final Optional<StmtContext<?, ?, ?>> originalCtx = getOriginalCtx();
262 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
263 return parentPath.createChild(qname);
265 if (argument instanceof SchemaNodeIdentifier
266 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class)
267 || StmtContextUtils.producesDeclared(this, RefineStatement.class)
268 || StmtContextUtils.producesDeclared(this, DeviationStatement.class))) {
270 return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
273 // FIXME: this does not look right
274 return maybeParentPath.orElse(null);
279 public Optional<SchemaPath> getSchemaPath() {
280 SchemaPath local = schemaPath;
282 synchronized (this) {
285 local = createSchemaPath();
292 return Optional.ofNullable(local);
296 public boolean isConfiguration() {
297 if (isIgnoringConfig()) {
301 if (OptionalBoolean.isPresent(configuration)) {
302 return OptionalBoolean.get(configuration);
305 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
306 ConfigStatement.class);
307 final boolean parentIsConfig = parent.isConfiguration();
309 final boolean isConfig;
310 if (configStatement != null) {
311 isConfig = configStatement.getStatementArgument();
313 // Validity check: if parent is config=false this cannot be a config=true
314 InferenceException.throwIf(isConfig && !parentIsConfig, getStatementSourceReference(),
315 "Parent node has config=false, this node must not be specifed as config=true");
317 // If "config" statement is not specified, the default is the same as the parent's "config" value.
318 isConfig = parentIsConfig;
321 // Resolved, make sure we cache this return
322 configuration = OptionalBoolean.of(isConfig);
327 public boolean isEnabledSemanticVersioning() {
328 return parent.isEnabledSemanticVersioning();
332 public YangVersion getRootVersion() {
333 return getRoot().getRootVersion();
337 public void setRootVersion(final YangVersion version) {
338 getRoot().setRootVersion(version);
342 public void addMutableStmtToSeal(final MutableStatement mutableStatement) {
343 getRoot().addMutableStmtToSeal(mutableStatement);
347 public void addRequiredModule(final ModuleIdentifier dependency) {
348 getRoot().addRequiredModule(dependency);
352 public void setRootIdentifier(final ModuleIdentifier identifier) {
353 getRoot().setRootIdentifier(identifier);
357 protected boolean isIgnoringIfFeatures() {
358 if (OptionalBoolean.isPresent(ignoreIfFeature)) {
359 return OptionalBoolean.get(ignoreIfFeature);
362 final boolean ret = definition().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures();
363 ignoreIfFeature = OptionalBoolean.of(ret);
369 protected boolean isIgnoringConfig() {
370 if (OptionalBoolean.isPresent(ignoreConfig)) {
371 return OptionalBoolean.get(ignoreConfig);
374 final boolean ret = definition().isIgnoringConfig() || parent.isIgnoringConfig();
375 ignoreConfig = OptionalBoolean.of(ret);