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.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 final class SubstatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> extends
53 StatementContextBase<A, D, E> {
54 private static final Logger LOG = LoggerFactory.getLogger(SubstatementContext.class);
56 private final StatementContextBase<?, ?, ?> parent;
57 private final A argument;
60 * config statements are not all that common which means we are performing a recursive search towards the root
61 * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
62 * for the (usually non-existent) config statement.
64 * This field maintains a resolution cache, so once we have returned a result, we will keep on returning the same
65 * result without performing any lookups.
67 private boolean haveConfiguration;
68 private boolean configuration;
69 private boolean wasCheckedIfInYangDataExtensionBody;
70 private boolean isInYangDataExtensionBody;
72 private volatile SchemaPath schemaPath;
74 SubstatementContext(final StatementContextBase<?, ?, ?> parent, final StatementDefinitionContext<A, D, E> def,
75 final StatementSourceReference ref, final String rawArgument) {
76 super(def, ref, rawArgument);
77 this.parent = Preconditions.checkNotNull(parent, "Parent must not be null");
78 this.argument = def.parseArgumentValue(this, rawStatementArgument());
81 @SuppressWarnings("unchecked")
82 private SubstatementContext(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
83 final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
85 this.parent = Preconditions.checkNotNull(newParent);
87 if (newQNameModule != null) {
88 final A originalArg = original.argument;
89 if (originalArg instanceof QName) {
90 final QName originalQName = (QName) originalArg;
91 this.argument = (A) getFromNamespace(QNameCacheNamespace.class,
92 QName.create(newQNameModule, originalQName.getLocalName()));
93 } else if (StmtContextUtils.producesDeclared(original, KeyStatement.class)) {
94 this.argument = (A) StmtContextUtils.replaceModuleQNameForKey(
95 (StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?>) original, newQNameModule);
97 this.argument = original.argument;
100 this.argument = original.argument;
105 public StatementContextBase<?, ?, ?> getParentContext() {
110 public StorageNodeType getStorageNodeType() {
111 return StorageNodeType.STATEMENT_LOCAL;
115 public NamespaceStorageNode getParentNamespaceStorage() {
120 public Registry getBehaviourRegistry() {
121 return parent.getBehaviourRegistry();
126 public RootStatementContext<?, ?, ?> getRoot() {
127 return parent.getRoot();
131 public A getStatementArgument() {
136 public StatementContextBase<A, D, E> createCopy(final StatementContextBase<?, ?, ?> newParent,
137 final CopyType typeOfCopy) {
138 return createCopy(null, newParent, typeOfCopy);
142 public StatementContextBase<A, D, E> createCopy(final QNameModule newQNameModule,
143 final StatementContextBase<?, ?, ?> newParent, final CopyType typeOfCopy) {
144 Preconditions.checkState(getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
145 "Attempted to copy statement %s which has completed phase %s", this, getCompletedPhase());
147 final SubstatementContext<A, D, E> copy = new SubstatementContext<>(this, newQNameModule, newParent, typeOfCopy);
149 copy.appendCopyHistory(typeOfCopy, this.getCopyHistory());
151 if (this.getOriginalCtx() != null) {
152 copy.setOriginalCtx(this.getOriginalCtx());
154 copy.setOriginalCtx(this);
157 definition().onStatementAdded(copy);
159 copy.copyStatements(this, newQNameModule, typeOfCopy);
163 private void copyStatements(final SubstatementContext<A, D, E> original, final QNameModule newQNameModule,
164 final CopyType typeOfCopy) {
165 final Collection<? extends Mutable<?, ?, ?>> declared = original.mutableDeclaredSubstatements();
166 final Collection<? extends Mutable<?, ?, ?>> effective = original.mutableEffectiveSubstatements();
167 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
169 for (final Mutable<?, ?, ?> stmtContext : declared) {
170 if (stmtContext.isSupportedByFeatures()) {
171 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
175 for (final Mutable<?, ?, ?> stmtContext : effective) {
176 copySubstatement(stmtContext, newQNameModule, typeOfCopy, buffer);
179 addEffectiveSubstatements(buffer);
182 private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final QNameModule newQNameModule,
183 final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer) {
184 if (needToCopyByUses(stmtContext)) {
185 final Mutable<?, ?, ?> 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 (StmtContextUtils.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 StmtContext<?, ?, ?> originalCtx = getOriginalCtx();
257 final QName qname = originalCtx != null ? StmtContextUtils.qnameFromArgument(originalCtx, (String) argument)
258 : StmtContextUtils.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 isConfiguration() {
293 // if this statement is within a 'yang-data' extension body, config substatements are ignored as if
294 // they were not declared. As 'yang-data' is always a top-level node, all configs that are within it are
295 // automatically true
296 if (isInYangDataExtensionBody()) {
300 if (haveConfiguration) {
301 return configuration;
304 final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
305 ConfigStatement.class);
306 final boolean parentIsConfig = parent.isConfiguration();
308 final boolean isConfig;
309 if (configStatement != null) {
310 isConfig = configStatement.getStatementArgument();
312 // Validity check: if parent is config=false this cannot be a config=true
313 InferenceException.throwIf(isConfig && !parentIsConfig, getStatementSourceReference(),
314 "Parent node has config=false, this node must not be specifed as config=true");
316 // If "config" statement is not specified, the default is the same as the parent's "config" value.
317 isConfig = parentIsConfig;
320 // Resolved, make sure we cache this return
321 configuration = isConfig;
322 haveConfiguration = true;
327 public boolean isInYangDataExtensionBody() {
328 if (wasCheckedIfInYangDataExtensionBody) {
329 return isInYangDataExtensionBody;
332 final boolean parentIsInYangDataExtensionBody = parent.isInYangDataExtensionBody();
333 if (parentIsInYangDataExtensionBody) {
334 isInYangDataExtensionBody = parentIsInYangDataExtensionBody;
336 isInYangDataExtensionBody = StmtContextUtils.hasYangDataExtensionParent(this);
339 wasCheckedIfInYangDataExtensionBody = true;
340 return isInYangDataExtensionBody;
344 public boolean isEnabledSemanticVersioning() {
345 return parent.isEnabledSemanticVersioning();
349 public YangVersion getRootVersion() {
350 return getRoot().getRootVersion();
354 public void setRootVersion(final YangVersion version) {
355 getRoot().setRootVersion(version);
359 public void addMutableStmtToSeal(final MutableStatement mutableStatement) {
360 getRoot().addMutableStmtToSeal(mutableStatement);
364 public void addRequiredModule(final ModuleIdentifier dependency) {
365 getRoot().addRequiredModule(dependency);
369 public void setRootIdentifier(final ModuleIdentifier identifier) {
370 getRoot().setRootIdentifier(identifier);