2 * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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 static com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.base.VerifyException;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableSet;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.HashMap;
19 import java.util.List;
21 import java.util.Optional;
22 import java.util.stream.Stream;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.common.QNameModule;
27 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
28 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
29 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
33 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
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.NamespaceBehaviour.OnDemandSchemaTreeStorageNode;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextDefaults;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
42 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * A statement which has been inferred to exist. Functionally it is equivalent to a SubstatementContext, but it is not
48 * backed by a declaration (and declared statements). It is backed by a prototype StatementContextBase and has only
49 * effective substatements, which are either transformed from that prototype or added by inference.
51 final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
52 extends StatementContextBase<A, D, E> implements OnDemandSchemaTreeStorageNode {
53 private static final Logger LOG = LoggerFactory.getLogger(InferredStatementContext.class);
55 private final @NonNull StatementContextBase<A, D, E> prototype;
56 private final @NonNull StatementContextBase<?, ?, ?> parent;
57 private final @NonNull StmtContext<A, D, E> originalCtx;
58 private final @NonNull CopyType childCopyType;
59 private final QNameModule targetModule;
60 private final A argument;
63 * Effective substatements, lazily materialized. This field can have three states:
65 * <li>it can be {@code null}, in which case no materialization has taken place</li>
66 * <li>it can be a {@link HashMap}, in which case partial materialization has taken place</li>
67 * <li>it can be a {@link List}, in which case full materialization has taken place</li>
70 private Object substatements;
72 private InferredStatementContext(final InferredStatementContext<A, D, E> original,
73 final StatementContextBase<?, ?, ?> parent) {
75 this.parent = requireNonNull(parent);
76 this.childCopyType = original.childCopyType;
77 this.targetModule = original.targetModule;
78 this.prototype = original.prototype;
79 this.originalCtx = original.originalCtx;
80 this.argument = original.argument;
81 // Substatements are initialized here
82 this.substatements = ImmutableList.of();
85 InferredStatementContext(final StatementContextBase<?, ?, ?> parent, final StatementContextBase<A, D, E> prototype,
86 final CopyType myCopyType, final CopyType childCopyType, final QNameModule targetModule) {
87 super(prototype.definition(), CopyHistory.of(myCopyType, prototype.getCopyHistory()));
88 this.parent = requireNonNull(parent);
89 this.prototype = requireNonNull(prototype);
90 this.argument = targetModule == null ? prototype.getStatementArgument()
91 : prototype.definition().adaptArgumentValue(prototype, targetModule);
92 this.childCopyType = requireNonNull(childCopyType);
93 this.targetModule = targetModule;
94 this.originalCtx = prototype.getOriginalCtx().orElse(prototype);
98 public Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements() {
99 return ImmutableList.of();
103 public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
104 return mutableEffectiveSubstatements(ensureEffectiveSubstatements());
108 public Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
109 // No need to concat with declared
110 return effectiveSubstatements();
114 public Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
115 // No need to concat with declared
116 return effectiveSubstatements().stream();
120 public StatementSourceReference sourceReference() {
121 return originalCtx.sourceReference();
125 public String rawArgument() {
126 return originalCtx.rawArgument();
130 public Optional<StmtContext<A, D, E>> getOriginalCtx() {
131 return Optional.of(originalCtx);
135 public Optional<StmtContext<A, D, E>> getPreviousCopyCtx() {
136 return Optional.of(prototype);
140 public D buildDeclared() {
142 * Share original instance of declared statement between all effective statements which have been copied or
143 * derived from this original declared statement.
145 return originalCtx.buildDeclared();
149 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
150 substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef);
154 public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
155 final String statementArg) {
156 substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef,
161 public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
162 substatements = addEffectiveSubstatement(ensureEffectiveSubstatements(), substatement);
166 void addEffectiveSubstatementsImpl(final Collection<? extends Mutable<?, ?, ?>> statements) {
167 substatements = addEffectiveSubstatementsImpl(ensureEffectiveSubstatements(), statements);
171 InferredStatementContext<A, D, E> reparent(final StatementContextBase<?, ?, ?> newParent) {
172 return new InferredStatementContext<>(this, newParent);
176 boolean hasEmptySubstatements() {
177 if (substatements == null) {
178 return prototype.hasEmptySubstatements();
180 return substatements instanceof HashMap ? false : ((List<?>) substatements).isEmpty();
184 public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
185 final @NonNull Class<Z> type) {
186 if (substatements instanceof List) {
187 return StmtContextDefaults.findSubstatementArgument(this, type);
190 final Optional<X> templateArg = prototype.findSubstatementArgument(type);
191 if (templateArg.isEmpty()) {
194 if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) {
195 // X is known to be QName
196 return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule));
202 public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
203 return substatements instanceof List ? StmtContextDefaults.hasSubstatement(prototype, type)
204 // We do not allow deletion of partially-materialized statements, hence this is accurate
205 : prototype.hasSubstatement(type);
209 public <Y extends DeclaredStatement<QName>, Z extends EffectiveStatement<QName, Y>>
210 StmtContext<QName, Y, Z> requestSchemaTreeChild(final QName qname) {
211 if (substatements instanceof List) {
212 // We have performed materialization, hence we have triggered creation of all our schema tree child
217 final QName templateQName = qname.bindTo(StmtContextUtils.getRootModuleQName(prototype));
218 LOG.debug("Materializing child {} from {}", qname, templateQName);
220 final StmtContext<?, ?, ?> template;
221 if (prototype instanceof InferredStatementContext) {
222 // Note: we need to access namespace here, as the target statement may have already been populated, in which
223 // case we want to obtain the statement in local namespace storage.
224 template = (StmtContext) ((InferredStatementContext<?, ?, ?>) prototype).getFromNamespace(
225 SchemaTreeNamespace.class, templateQName);
227 template = prototype.allSubstatementsStream()
228 .filter(stmt -> stmt.producesEffective(SchemaTreeEffectiveStatement.class)
229 && templateQName.equals(stmt.getStatementArgument()))
234 if (template == null) {
235 // We do not have a template, this child does not exist. It may be added later, but that is someone else's
237 LOG.debug("Child {} does not have a template", qname);
241 @SuppressWarnings("unchecked")
242 final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template)
243 .orElseThrow(() -> new InferenceException(getStatementSourceReference(),
244 "Failed to materialize child %s template %s", qname, template));
245 ensureCompletedPhase(ret);
246 addMaterialized(template, ret);
248 LOG.debug("Child {} materialized", qname);
252 // Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall
253 // BuildGlobalContext, hence it must be called at most once.
254 private List<StatementContextBase<?, ?, ?>> ensureEffectiveSubstatements() {
255 return substatements instanceof List ? castEffective(substatements)
256 : initializeSubstatements(castMaterialized(substatements));
260 Iterable<StatementContextBase<?, ?, ?>> effectiveChildrenToComplete() {
261 // When we have not initialized, there are no statements to catch up: we will catch up when we are copying
262 // from prototype (which is already at ModelProcessingPhase.EFFECTIVE_MODEL).
263 if (substatements == null) {
264 return ImmutableList.of();
265 } else if (substatements instanceof HashMap) {
266 return castMaterialized(substatements).values();
268 return castEffective(substatements);
273 Stream<? extends StmtContext<?, ?, ?>> streamDeclared() {
274 return Stream.empty();
278 Stream<? extends StmtContext<?, ?, ?>> streamEffective() {
279 // FIXME: YANGTOOLS-1184: do not force initialization
280 return ensureEffectiveSubstatements().stream();
283 private List<StatementContextBase<?, ?, ?>> initializeSubstatements(
284 final Map<StmtContext<?, ?, ?>, StatementContextBase<?, ?, ?>> materializedSchemaTree) {
285 final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
286 final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
287 final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
289 for (final Mutable<?, ?, ?> stmtContext : declared) {
290 if (stmtContext.isSupportedByFeatures()) {
291 copySubstatement(stmtContext, buffer, materializedSchemaTree);
294 for (final Mutable<?, ?, ?> stmtContext : effective) {
295 copySubstatement(stmtContext, buffer, materializedSchemaTree);
298 final List<StatementContextBase<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(),
300 ret.addAll((Collection) buffer);
305 // Statement copy mess starts here
307 // FIXME: This is messy and is probably wrong in some corner case. Even if it is correct, the way how it is correct
308 // relies on hard-coded maps. At the end of the day, the logic needs to be controlled by statement's
310 // FIXME: YANGTOOLS-652: this map looks very much like UsesStatementSupport.TOP_REUSED_DEF_SET
311 private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
312 YangStmtMapping.TYPE,
313 YangStmtMapping.TYPEDEF,
314 YangStmtMapping.USES);
316 private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
317 final Map<StmtContext<?, ?, ?>, StatementContextBase<?, ?, ?>> materializedSchemaTree) {
318 final StatementDefinition def = substatement.publicDefinition();
320 // FIXME: YANGTOOLS-652: formerly known as "isReusedByUses"
321 if (REUSED_DEF_SET.contains(def)) {
322 LOG.debug("Reusing substatement {} for {}", substatement, this);
323 buffer.add(substatement);
327 // Consult materialized substatements. We are in a copy operation and will end up throwing materialized
328 // statements away -- hence we do not perform Map.remove() to save ourselves a mutation operation.
330 // We could also perform a Map.containsKey() and perform a bulk add, but that would mean the statement order
331 // against parent would change -- and we certainly do not want that to happen.
332 final StatementContextBase<?, ?, ?> materialized = findMaterialized(materializedSchemaTree, substatement);
333 if (materialized == null) {
334 copySubstatement(substatement).ifPresent(copy -> {
335 ensureCompletedPhase(copy);
339 buffer.add(materialized);
343 private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
344 return substatement.copyAsChildOf(this, childCopyType, targetModule);
347 private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) {
348 final HashMap<StmtContext<?, ?, ?>, StatementContextBase<?, ?, ?>> materializedSchemaTree;
349 if (substatements == null) {
350 // Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit
351 // here means an inference along schema tree, such as deviate/augment. HashMap requires power-of-two and
352 // defaults to 0.75 load factor -- we therefore size it to 4, i.e. next two inserts will not cause a
353 // resizing operation.
354 materializedSchemaTree = new HashMap<>(4);
355 substatements = materializedSchemaTree;
357 verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements);
358 materializedSchemaTree = castMaterialized(substatements);
361 final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template,
362 (StatementContextBase<?, ?, ?>) copy);
363 if (existing != null) {
364 throw new VerifyException(
365 "Unexpected duplicate request for " + copy.getStatementArgument() + " previous result was " + existing);
369 private static @Nullable StatementContextBase<?, ?, ?> findMaterialized(
370 final Map<StmtContext<?, ?, ?>, StatementContextBase<?, ?, ?>> materializedSchemaTree,
371 final StmtContext<?, ?, ?> template) {
372 return materializedSchemaTree == null ? null : materializedSchemaTree.get(template);
375 @SuppressWarnings("unchecked")
376 private static List<StatementContextBase<?, ?, ?>> castEffective(final Object substatements) {
377 return (List<StatementContextBase<?, ?, ?>>) substatements;
380 @SuppressWarnings("unchecked")
381 private static HashMap<StmtContext<?, ?, ?>, StatementContextBase<?, ?, ?>> castMaterialized(
382 final Object substatements) {
383 return (HashMap<StmtContext<?, ?, ?>, StatementContextBase<?, ?, ?>>) substatements;
386 // Statement copy mess ends here
389 * KEEP THINGS ORGANIZED!
391 * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
392 * properly updated there.
396 Optional<SchemaPath> schemaPath() {
397 return substatementGetSchemaPath();
401 public A argument() {
406 public StatementContextBase<?, ?, ?> getParentContext() {
411 public StorageNodeType getStorageNodeType() {
412 return StorageNodeType.STATEMENT_LOCAL;
416 public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
421 public RootStatementContext<?, ?, ?> getRoot() {
422 return parent.getRoot();
426 public boolean isConfiguration() {
427 return isConfiguration(parent);
431 protected boolean isIgnoringIfFeatures() {
432 return isIgnoringIfFeatures(parent);
436 protected boolean isIgnoringConfig() {
437 return isIgnoringConfig(parent);
441 protected boolean isParentSupportedByFeatures() {
442 return parent.isSupportedByFeatures();