Fix unique statement argument propagation
[yangtools.git] / parser / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / meta / UniqueStatementSupport.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.rfc7950.stmt.meta;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.CharMatcher;
13 import com.google.common.base.Splitter;
14 import com.google.common.collect.ImmutableBiMap;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Lists;
18 import com.google.common.collect.Maps;
19 import java.util.Collection;
20 import java.util.HashSet;
21 import java.util.Map;
22 import java.util.Objects;
23 import java.util.Set;
24 import java.util.regex.Pattern;
25 import java.util.stream.Stream;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.common.QNameModule;
28 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
29 import org.opendaylight.yangtools.yang.model.api.meta.DeclarationReference;
30 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.LeafEffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.ListEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
35 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Descendant;
36 import org.opendaylight.yangtools.yang.model.api.stmt.UniqueEffectiveStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.UniqueStatement;
38 import org.opendaylight.yangtools.yang.model.ri.stmt.DeclaredStatementDecorators;
39 import org.opendaylight.yangtools.yang.model.ri.stmt.DeclaredStatements;
40 import org.opendaylight.yangtools.yang.model.ri.stmt.EffectiveStatements;
41 import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration;
42 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.ArgumentUtils;
43 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.BoundStmtCtx;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
55 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
56
57 public final class UniqueStatementSupport
58         extends AbstractStatementSupport<Set<Descendant>, UniqueStatement, UniqueEffectiveStatement> {
59     /**
60      * Support 'sep' ABNF rule in RFC7950 section 14. CRLF pattern is used to squash line-break from CRLF to LF form
61      * and then we use SEP_SPLITTER, which can operate on single characters.
62      */
63     private static final Pattern CRLF_PATTERN = Pattern.compile("\r\n", Pattern.LITERAL);
64     private static final Splitter SEP_SPLITTER = Splitter.on(CharMatcher.anyOf(" \t\n").precomputed())
65             .omitEmptyStrings();
66
67     private static final SubstatementValidator SUBSTATEMENT_VALIDATOR =
68         SubstatementValidator.builder(YangStmtMapping.UNIQUE).build();
69
70     public UniqueStatementSupport(final YangParserConfiguration config) {
71         super(YangStmtMapping.UNIQUE,
72             StatementPolicy.copyDeclared(
73                 (copy, current, substatements) -> copy.getArgument().equals(current.getArgument())),
74             config, SUBSTATEMENT_VALIDATOR);
75     }
76
77     @Override
78     public Set<Descendant> adaptArgumentValue(
79             final StmtContext<Set<Descendant>, UniqueStatement, UniqueEffectiveStatement> ctx,
80             final QNameModule targetModule) {
81         // Copy operation to a targetNamespace -- this implies rehosting node-identifiers to target namespace. Check
82         // if that is needed first, though, so as not to copy things unnecessarily.
83         final var origArg = ctx.getArgument();
84         if (allMatch(origArg.stream().flatMap(desc -> desc.getNodeIdentifiers().stream()), targetModule)) {
85             return origArg;
86         }
87
88         return origArg.stream()
89             .map(descendant -> {
90                 final var nodeIds = descendant.getNodeIdentifiers();
91                 // Only update descendants that need updating
92                 return allMatch(nodeIds.stream(), targetModule) ? descendant
93                     : Descendant.of(Lists.transform(nodeIds, nodeId -> nodeId.bindTo(targetModule).intern()));
94             })
95             .collect(ImmutableSet.toImmutableSet());
96     }
97
98     @Override
99     public ImmutableSet<Descendant> parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
100         final var uniqueConstraints = parseUniqueConstraintArgument(ctx, value);
101         SourceException.throwIf(uniqueConstraints.isEmpty(), ctx,
102             "Invalid argument value '%s' of unique statement. The value must contains at least one descendant schema "
103                 + "node identifier.", value);
104         return uniqueConstraints;
105     }
106
107     @Override
108     public void onStatementAdded(final Mutable<Set<Descendant>, UniqueStatement, UniqueEffectiveStatement> stmt) {
109         // Check whether this statement is in a list statement and if so ...
110         final var list = stmt.coerceParentContext();
111         if (list.producesEffective(ListEffectiveStatement.class)) {
112             final var listParent = list.coerceParentContext();
113             // ... do not allow parent to complete until we have resolved ...
114             final var action = listParent.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
115             // ... we require the list to be completely resolve ...
116             action.requiresCtx(list, ModelProcessingPhase.EFFECTIVE_MODEL);
117             // ... after which we will continue
118             action.apply(new RequireEffectiveList(stmt, list, listParent));
119         }
120     }
121
122     @Override
123     protected UniqueStatement createDeclared(final BoundStmtCtx<Set<Descendant>> ctx,
124             final ImmutableList<DeclaredStatement<?>> substatements) {
125         return DeclaredStatements.createUnique(ctx.getRawArgument(), ctx.getArgument(), substatements);
126     }
127
128     @Override
129     protected UniqueStatement attachDeclarationReference(final UniqueStatement stmt,
130             final DeclarationReference reference) {
131         return DeclaredStatementDecorators.decorateUnique(stmt, reference);
132     }
133
134     @Override
135     protected UniqueEffectiveStatement createEffective(final Current<Set<Descendant>, UniqueStatement> stmt,
136             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
137         return EffectiveStatements.createUnique(stmt.declared(), substatements);
138     }
139
140     private static boolean allMatch(final Stream<QName> qnames, final QNameModule module) {
141         return qnames.allMatch(qname -> module.equals(qname.getModule()));
142     }
143
144     private static ImmutableSet<Descendant> parseUniqueConstraintArgument(final StmtContext<?, ?, ?> ctx,
145             final String argumentValue) {
146         // deal with 'line-break' rule, which is either "\n" or "\r\n", but not "\r"
147         final String nocrlf = CRLF_PATTERN.matcher(argumentValue).replaceAll("\n");
148
149         final var uniqueConstraintNodes = new HashSet<Descendant>();
150         for (var uniqueArgToken : SEP_SPLITTER.split(nocrlf)) {
151             final var nodeIdentifier = ArgumentUtils.nodeIdentifierFromPath(ctx, uniqueArgToken);
152             SourceException.throwIf(nodeIdentifier instanceof Absolute, ctx,
153                 "Unique statement argument '%s' contains schema node identifier '%s' which is not in the descendant "
154                     + "node identifier form.", argumentValue, uniqueArgToken);
155             uniqueConstraintNodes.add((Descendant) nodeIdentifier);
156         }
157         return ImmutableSet.copyOf(uniqueConstraintNodes);
158     }
159
160     /**
161      * Inference action to process parent list reaching effective model, i.e. we can tell it is now complete.
162      */
163     private static final class RequireEffectiveList implements InferenceAction {
164         private final StmtContext<Set<Descendant>, ?, ?> unique;
165         private final StmtContext<?, ?, ?> list;
166         private final Mutable<?, ?, ?> parent;
167
168         RequireEffectiveList(final StmtContext<Set<Descendant>, ?, ?> unique, final StmtContext<?, ?, ?> list,
169                 final Mutable<?, ?, ?> parent) {
170             this.unique = requireNonNull(unique);
171             this.list = requireNonNull(list);
172             this.parent = requireNonNull(parent);
173         }
174
175         @Override
176         public void apply(final InferenceContext ctx) {
177             if (isApplicable()) {
178                 // So now, we have the effective list, we again block its parent from resolving ...
179                 final var action = parent.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
180                 // ... and before going further ...
181                 action.apply(new RequireLeafDescendants(unique,
182                     // ... require that each schema node identifier resolves against the schema tree
183                     Maps.uniqueIndex(unique.getArgument(), desc -> action.requiresCtxPath(list,
184                         SchemaTreeNamespace.class, desc.getNodeIdentifiers(), ModelProcessingPhase.EFFECTIVE_MODEL))));
185             }
186         }
187
188         @Override
189         public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
190             InferenceException.throwIf(isApplicable(), unique, "Parent list failed to reach effective model");
191         }
192
193         private boolean isApplicable() {
194             return list.isSupportedToBuildEffective() && unique.isSupportedToBuildEffective();
195         }
196     }
197
198     private static final class RequireLeafDescendants implements InferenceAction {
199         private final Map<Prerequisite<StmtContext<?, ?, ?>>, Descendant> prereqs;
200         private final StmtContext<Set<Descendant>, ?, ?> unique;
201
202         RequireLeafDescendants(final StmtContext<Set<Descendant>, ?, ?> unique,
203                 final Map<Prerequisite<StmtContext<?, ?, ?>>, Descendant> prereqs) {
204             this.unique = requireNonNull(unique);
205             this.prereqs = requireNonNull(prereqs);
206
207         }
208
209         @Override
210         public void apply(final InferenceContext ctx) {
211             // All prerequisites have resolved, so now check each ...
212             for (var entry : prereqs.entrySet()) {
213                 final var stmt = entry.getKey().resolve(ctx);
214                 // ... and if it is not a leaf, report an error
215                 SourceException.throwIf(!stmt.producesEffective(LeafEffectiveStatement.class),
216                     unique, "Path %s resolved to non-leaf %s", stmt.publicDefinition().getStatementName());
217             }
218         }
219
220         @Override
221         public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
222             // Report failed descandants
223             final var inv = ImmutableBiMap.copyOf(prereqs);
224             throw new SourceException(unique,
225                 "Following components of unique statement argument refer to non-existent nodes: %s",
226                 failed.stream().map(inv::get).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet()));
227         }
228     }
229 }