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.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;
17 import javax.annotation.Nonnull;
18 import org.opendaylight.yangtools.yang.common.QName;
19 import org.opendaylight.yangtools.yang.common.QNameModule;
20 import org.opendaylight.yangtools.yang.common.YangVersion;
21 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
22 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
23 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
24 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
25 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
27 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
34 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.QNameCacheNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
45 import org.opendaylight.yangtools.yang.parser.spi.source.AugmentToChoiceNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
47 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
49 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
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.
68 private boolean haveConfiguration;
69 private boolean configuration;
70 private boolean wasCheckedIfInYangDataExtensionBody;
71 private boolean isInYangDataExtensionBody;
73 private volatile SchemaPath schemaPath;
75 SubstatementContext(final StatementContextBase<?, ?, ?> parent, final StatementDefinitionContext<A, D, E> def,
76 final StatementSourceReference ref, final String rawArgument) {
77 super(def, ref, rawArgument);
78 this.parent = Preconditions.checkNotNull(parent, "Parent must not be null");
79 this.argument = def.parseArgumentValue(this, rawStatementArgument());
82 @SuppressWarnings("unchecked")
83 SubstatementContext(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
84 final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
86 this.parent = newParent;
88 if (newQNameModule != null) {
89 final A originalArg = original.argument;
90 if (originalArg instanceof QName) {
91 final QName originalQName = (QName) originalArg;
92 this.argument = (A) getFromNamespace(QNameCacheNamespace.class,
93 QName.create(newQNameModule, originalQName.getLocalName()));
94 } else if (StmtContextUtils.producesDeclared(original, KeyStatement.class)) {
95 this.argument = (A) StmtContextUtils.replaceModuleQNameForKey(
96 (StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?>) original, newQNameModule);
98 this.argument = original.argument;
101 this.argument = original.argument;
106 public StatementContextBase<?, ?, ?> getParentContext() {
111 public StorageNodeType getStorageNodeType() {
112 return StorageNodeType.STATEMENT_LOCAL;
116 public NamespaceStorageNode getParentNamespaceStorage() {
121 public Registry getBehaviourRegistry() {
122 return parent.getBehaviourRegistry();
127 public RootStatementContext<?, ?, ?> getRoot() {
128 return parent.getRoot();
132 public A getStatementArgument() {
137 public StatementContextBase<A, D, E> createCopy(final StatementContextBase<?, ?, ?> newParent,
138 final CopyType typeOfCopy) {
139 return createCopy(null, newParent, typeOfCopy);
143 public StatementContextBase<A, D, E> createCopy(final QNameModule newQNameModule,
144 final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
145 Preconditions.checkState(getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
146 "Attempted to copy statement %s which has completed phase %s", this, getCompletedPhase());
148 final SubstatementContext<A, D, E> copy = new SubstatementContext<>(this, newQNameModule, newParent, typeOfCopy);
150 copy.appendCopyHistory(typeOfCopy, this.getCopyHistory());
152 if (this.getOriginalCtx() != null) {
153 copy.setOriginalCtx(this.getOriginalCtx());
155 copy.setOriginalCtx(this);
158 definition().onStatementAdded(copy);
160 copy.copyStatements(this, newQNameModule, typeOfCopy);
164 private void copyStatements(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
165 final CopyType typeOfCopy) {
166 final Collection<? extends Mutable<?, ?, ?>> declared = original.mutableDeclaredSubstatements();
167 final Collection<? extends Mutable<?, ?, ?>> effective = original.mutableEffectiveSubstatements();
168 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
170 for (final Mutable<?, ?, ?> stmtContext : declared) {
171 if (stmtContext.isSupportedByFeatures()) {
172 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
176 for (final Mutable<?, ?, ?> stmtContext : effective) {
177 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
180 addEffectiveSubstatements(buffer);
183 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final QNameModule newQNameModule,
184 final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer) {
185 if (needToCopyByUses(stmtContext)) {
186 final Mutable<?, ?, ?> copy = stmtContext.createCopy(newQNameModule, this, typeOfCopy);
187 LOG.debug("Copying substatement {} for {} as", stmtContext, this, copy);
189 } else if (isReusedByUses(stmtContext)) {
190 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
191 buffer.add(stmtContext);
193 LOG.debug("Skipping statement {}", stmtContext);
197 // FIXME: revise this, as it seems to be wrong
198 private static final Set<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
199 YangStmtMapping.DESCRIPTION,
200 YangStmtMapping.REFERENCE,
201 YangStmtMapping.STATUS);
202 private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
203 YangStmtMapping.TYPE,
204 YangStmtMapping.TYPEDEF,
205 YangStmtMapping.USES);
207 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
208 final StatementDefinition def = stmtContext.getPublicDefinition();
209 if (REUSED_DEF_SET.contains(def)) {
210 LOG.debug("Will reuse {} statement {}", def, stmtContext);
213 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
214 return !YangStmtMapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
217 LOG.debug("Will copy {} statement {}", def, stmtContext);
221 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
222 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
225 private boolean isSupportedAsShorthandCase() {
226 final Collection<?> supportedCaseShorthands = getFromNamespace(ValidationBundlesNamespace.class,
227 ValidationBundleType.SUPPORTED_CASE_SHORTHANDS);
228 return supportedCaseShorthands == null || supportedCaseShorthands.contains(getPublicDefinition());
231 private SchemaPath createSchemaPath() {
232 final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
233 Verify.verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
234 final SchemaPath parentPath = maybeParentPath.get();
236 if (Utils.isUnknownNode(this)) {
237 return parentPath.createChild(getPublicDefinition().getStatementName());
239 if (argument instanceof QName) {
240 final QName qname = (QName) argument;
241 if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
242 return maybeParentPath.orNull();
245 final SchemaPath path;
246 if ((StmtContextUtils.producesDeclared(getParentContext(), ChoiceStatement.class)
247 || Boolean.TRUE.equals(parent.getFromNamespace(AugmentToChoiceNamespace.class, parent)))
248 && isSupportedAsShorthandCase()) {
249 path = parentPath.createChild(qname);
253 return path.createChild(qname);
255 if (argument instanceof String) {
256 // FIXME: This may yield illegal argument exceptions
257 final StmtContext<?, ?, ?> originalCtx = getOriginalCtx();
258 final QName qname = originalCtx != null ? Utils.qNameFromArgument(originalCtx, (String) argument) : Utils
259 .qNameFromArgument(this, (String) argument);
260 return parentPath.createChild(qname);
262 if (argument instanceof SchemaNodeIdentifier
263 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class) || StmtContextUtils
264 .producesDeclared(this, RefineStatement.class) || StmtContextUtils
265 .producesDeclared(this, DeviationStatement.class))) {
267 return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
270 // FIXME: this does not look right
271 return maybeParentPath.orNull();
276 public Optional<SchemaPath> getSchemaPath() {
277 SchemaPath local = schemaPath;
279 synchronized (this) {
282 local = createSchemaPath();
289 return Optional.fromNullable(local);
293 public boolean isRootContext() {
298 public boolean isConfiguration() {
299 // if this statement is within a 'yang-data' extension body, config substatements are ignored as if
300 // they were not declared. As 'yang-data' is always a top-level node, all configs that are within it are
301 // automatically true
302 if (isInYangDataExtensionBody()) {
306 if (haveConfiguration) {
307 return configuration;
310 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
311 ConfigStatement.class);
312 final boolean parentIsConfig = parent.isConfiguration();
314 final boolean isConfig;
315 if (configStatement != null) {
316 isConfig = configStatement.getStatementArgument();
318 // Validity check: if parent is config=false this cannot be a config=true
319 InferenceException.throwIf(isConfig && !parentIsConfig, getStatementSourceReference(),
320 "Parent node has config=false, this node must not be specifed as config=true");
322 // If "config" statement is not specified, the default is the same as the parent's "config" value.
323 isConfig = parentIsConfig;
326 // Resolved, make sure we cache this return
327 configuration = isConfig;
328 haveConfiguration = true;
333 public boolean isInYangDataExtensionBody() {
334 if (wasCheckedIfInYangDataExtensionBody) {
335 return isInYangDataExtensionBody;
338 final boolean parentIsInYangDataExtensionBody = parent.isInYangDataExtensionBody();
339 if (parentIsInYangDataExtensionBody) {
340 isInYangDataExtensionBody = parentIsInYangDataExtensionBody;
342 isInYangDataExtensionBody = StmtContextUtils.hasYangDataExtensionParent(this);
345 wasCheckedIfInYangDataExtensionBody = true;
346 return isInYangDataExtensionBody;
350 public boolean isEnabledSemanticVersioning() {
351 return parent.isEnabledSemanticVersioning();
355 public YangVersion getRootVersion() {
356 return getRoot().getRootVersion();
360 public void setRootVersion(final YangVersion version) {
361 getRoot().setRootVersion(version);
365 public void addMutableStmtToSeal(final MutableStatement mutableStatement) {
366 getRoot().addMutableStmtToSeal(mutableStatement);
370 public void addRequiredModule(final ModuleIdentifier dependency) {
371 getRoot().addRequiredModule(dependency);
375 public void setRootIdentifier(final ModuleIdentifier identifier) {
376 getRoot().setRootIdentifier(identifier);