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;
71 private volatile SchemaPath schemaPath;
73 SubstatementContext(final StatementContextBase<?, ?, ?> parent, final StatementDefinitionContext<A, D, E> def,
74 final StatementSourceReference ref, final String rawArgument) {
75 super(def, ref, rawArgument);
76 this.parent = Preconditions.checkNotNull(parent, "Parent must not be null");
77 this.argument = def.parseArgumentValue(this, rawArgument);
80 @SuppressWarnings("unchecked")
81 SubstatementContext(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
82 final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
84 this.parent = newParent;
86 if (newQNameModule != null) {
87 final A originalArg = original.argument;
88 if (originalArg instanceof QName) {
89 final QName originalQName = (QName) originalArg;
90 this.argument = (A) getFromNamespace(QNameCacheNamespace.class,
91 QName.create(newQNameModule, originalQName.getLocalName()));
92 } else if (StmtContextUtils.producesDeclared(original, KeyStatement.class)) {
93 this.argument = (A) StmtContextUtils.replaceModuleQNameForKey(
94 (StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?>) original, newQNameModule);
96 this.argument = original.argument;
99 this.argument = original.argument;
104 public StatementContextBase<?, ?, ?> getParentContext() {
109 public StorageNodeType getStorageNodeType() {
110 return StorageNodeType.STATEMENT_LOCAL;
114 public NamespaceStorageNode getParentNamespaceStorage() {
119 public Registry getBehaviourRegistry() {
120 return parent.getBehaviourRegistry();
125 public RootStatementContext<?, ?, ?> getRoot() {
126 return parent.getRoot();
130 public A getStatementArgument() {
135 public StatementContextBase<?, ?, ?> createCopy(final StatementContextBase<?, ?, ?> newParent,
136 final CopyType typeOfCopy) {
137 return createCopy(null, newParent, typeOfCopy);
141 public StatementContextBase<A, D, E> createCopy(final QNameModule newQNameModule,
142 final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
143 Preconditions.checkState(getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
144 "Attempted to copy statement {} which has completed phase {}", this, getCompletedPhase());
146 final SubstatementContext<A, D, E> copy = new SubstatementContext<>(this, newQNameModule, newParent, typeOfCopy);
148 copy.appendCopyHistory(typeOfCopy, this.getCopyHistory());
150 if (this.getOriginalCtx() != null) {
151 copy.setOriginalCtx(this.getOriginalCtx());
153 copy.setOriginalCtx(this);
156 definition().onStatementAdded(copy);
158 copy.copyStatements(this, newQNameModule, typeOfCopy);
162 private void copyStatements(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
163 final CopyType typeOfCopy) {
164 final Collection<StatementContextBase<?, ?, ?>> declared = original.declaredSubstatements();
165 final Collection<StatementContextBase<?, ?, ?>> effective = original.effectiveSubstatements();
166 final Collection<StatementContextBase<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
168 for (final StatementContextBase<?, ?, ?> stmtContext : declared) {
169 if (StmtContextUtils.areFeaturesSupported(stmtContext)) {
170 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
174 for (final StatementContextBase<?, ?, ?> stmtContext : effective) {
175 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
178 addEffectiveSubstatements(buffer);
181 private void copySubstatement(final StatementContextBase<?, ?, ?> stmtContext,
182 final QNameModule newQNameModule, final CopyType typeOfCopy,
183 final Collection<StatementContextBase<?, ?, ?>> buffer) {
184 if (needToCopyByUses(stmtContext)) {
185 final StatementContextBase<?, ?, ?> copy = stmtContext.createCopy(newQNameModule, this, typeOfCopy);
186 LOG.debug("Copying substatement {} for {} as", stmtContext, this, copy);
188 } else if (isReusedByUses(stmtContext)) {
189 LOG.debug("Reusing substatement {} for {}", stmtContext, this);
190 buffer.add(stmtContext);
192 LOG.debug("Skipping statement {}", stmtContext);
196 // FIXME: revise this, as it seems to be wrong
197 private static final Set<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
198 YangStmtMapping.DESCRIPTION,
199 YangStmtMapping.REFERENCE,
200 YangStmtMapping.STATUS);
201 private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
202 YangStmtMapping.TYPE,
203 YangStmtMapping.TYPEDEF,
204 YangStmtMapping.USES);
206 private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
207 final StatementDefinition def = stmtContext.getPublicDefinition();
208 if (REUSED_DEF_SET.contains(def)) {
209 LOG.debug("Will reuse {} statement {}", def, stmtContext);
212 if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
213 return !YangStmtMapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
216 LOG.debug("Will copy {} statement {}", def, stmtContext);
220 private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
221 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
224 private boolean isSupportedAsShorthandCase() {
225 final Collection<?> supportedCaseShorthands = getFromNamespace(ValidationBundlesNamespace.class,
226 ValidationBundleType.SUPPORTED_CASE_SHORTHANDS);
227 return supportedCaseShorthands == null || supportedCaseShorthands.contains(getPublicDefinition());
230 private SchemaPath createSchemaPath() {
231 final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath();
232 Verify.verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
233 final SchemaPath parentPath = maybeParentPath.get();
235 if (Utils.isUnknownNode(this)) {
236 return parentPath.createChild(getPublicDefinition().getStatementName());
238 if (argument instanceof QName) {
239 final QName qname = (QName) argument;
240 if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) {
241 return maybeParentPath.orNull();
244 final SchemaPath path;
245 if ((StmtContextUtils.producesDeclared(getParentContext(), ChoiceStatement.class)
246 || Boolean.TRUE.equals(parent.getFromNamespace(AugmentToChoiceNamespace.class, parent)))
247 && isSupportedAsShorthandCase()) {
248 path = parentPath.createChild(qname);
252 return path.createChild(qname);
254 if (argument instanceof String) {
255 // FIXME: This may yield illegal argument exceptions
256 final StatementContextBase<?, ?, ?> originalCtx = getOriginalCtx();
257 final QName qname = (originalCtx != null) ? Utils.qNameFromArgument(originalCtx, (String) argument) : Utils
258 .qNameFromArgument(this, (String) argument);
259 return parentPath.createChild(qname);
261 if (argument instanceof SchemaNodeIdentifier
262 && (StmtContextUtils.producesDeclared(this, AugmentStatement.class) || StmtContextUtils
263 .producesDeclared(this, RefineStatement.class) || StmtContextUtils
264 .producesDeclared(this, DeviationStatement.class))) {
266 return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot());
269 // FIXME: this does not look right
270 return maybeParentPath.orNull();
275 public Optional<SchemaPath> getSchemaPath() {
276 SchemaPath local = schemaPath;
278 synchronized (this) {
281 local = createSchemaPath();
288 return Optional.fromNullable(local);
292 public boolean isRootContext() {
297 public boolean isConfiguration() {
298 if (haveConfiguration) {
299 return configuration;
302 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
303 ConfigStatement.class);
304 final boolean parentIsConfig = parent.isConfiguration();
306 final boolean isConfig;
307 if (configStatement != null) {
308 isConfig = configStatement.getStatementArgument();
310 // Validity check: if parent is config=false this cannot be a config=true
311 InferenceException.throwIf(isConfig && !parentIsConfig, getStatementSourceReference(),
312 "Parent node has config=false, this node must not be specifed as config=true");
314 // If "config" statement is not specified, the default is the same as the parent's "config" value.
315 isConfig = parentIsConfig;
318 // Resolved, make sure we cache this return
319 configuration = isConfig;
320 haveConfiguration = true;
325 public boolean isEnabledSemanticVersioning() {
326 return parent.isEnabledSemanticVersioning();
330 public YangVersion getRootVersion() {
331 return getRoot().getRootVersion();
335 public void setRootVersion(final YangVersion version) {
336 getRoot().setRootVersion(version);
340 public void addMutableStmtToSeal(final MutableStatement mutableStatement) {
341 getRoot().addMutableStmtToSeal(mutableStatement);
345 public void addRequiredModule(final ModuleIdentifier dependency) {
346 getRoot().addRequiredModule(dependency);
350 public void setRootIdentifier(final ModuleIdentifier identifier) {
351 getRoot().setRootIdentifier(identifier);