YANGTOOLS-706: Split up base utility classes into rfc6020.util
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / rfc6020 / effective / AbstractEffectiveModule.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. 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.stmt.rfc6020.effective;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.MoreObjects;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Iterables;
18 import java.net.URI;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.HashSet;
22 import java.util.LinkedHashMap;
23 import java.util.LinkedHashSet;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Optional;
27 import java.util.Set;
28 import java.util.stream.Collectors;
29 import javax.annotation.Nonnull;
30 import org.opendaylight.yangtools.concepts.SemVer;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.Revision;
33 import org.opendaylight.yangtools.yang.common.YangVersion;
34 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
36 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.Deviation;
38 import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition;
39 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
40 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
41 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.Module;
43 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
44 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
45 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
46 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.UsesNode;
50 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
51 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
52 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
53 import org.opendaylight.yangtools.yang.model.api.stmt.ContactEffectiveStatement;
54 import org.opendaylight.yangtools.yang.model.api.stmt.OrganizationEffectiveStatement;
55 import org.opendaylight.yangtools.yang.model.api.stmt.PrefixEffectiveStatement;
56 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
57 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefEffectiveStatement;
58 import org.opendaylight.yangtools.yang.model.api.stmt.YangVersionEffectiveStatement;
59 import org.opendaylight.yangtools.yang.parser.rfc6020.util.AbstractEffectiveDocumentedNode;
60 import org.opendaylight.yangtools.yang.parser.rfc6020.util.EffectiveStatementBase;
61 import org.opendaylight.yangtools.yang.parser.rfc6020.util.EffectiveStmtUtils;
62 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
63 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
64 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
65 import org.opendaylight.yangtools.yang.parser.spi.source.IncludedSubmoduleNameToModuleCtx;
66 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
67 import org.opendaylight.yangtools.yang.parser.stmt.openconfig.OpenconfigVersionEffectiveStatement;
68
69 abstract class AbstractEffectiveModule<D extends DeclaredStatement<String>> extends
70         AbstractEffectiveDocumentedNode<String, D> implements Module, MutableStatement {
71     private final String name;
72     private final String prefix;
73     private final YangVersion yangVersion;
74     private final String organization;
75     private final String contact;
76     private final Set<ModuleImport> imports;
77     private final Set<FeatureDefinition> features;
78     private final Set<NotificationDefinition> notifications;
79     private final Set<AugmentationSchemaNode> augmentations;
80     private final Set<RpcDefinition> rpcs;
81     private final Set<Deviation> deviations;
82     private final List<ExtensionDefinition> extensionNodes;
83     private final Set<IdentitySchemaNode> identities;
84     private final List<UnknownSchemaNode> unknownNodes;
85     private final Map<QName, DataSchemaNode> childNodes;
86     private final Set<GroupingDefinition> groupings;
87     private final Set<UsesNode> uses;
88     private final Set<TypeDefinition<?>> typeDefinitions;
89     private final Set<DataSchemaNode> publicChildNodes;
90     private final SemVer semanticVersion;
91
92     private Set<StmtContext<?, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>>>
93         submoduleContextsToBuild;
94     private Set<Module> submodules;
95     private boolean sealed;
96
97     AbstractEffectiveModule(final StmtContext<String, D, ? extends EffectiveStatement<String, ?>> ctx) {
98         super(ctx);
99
100         this.name = argument();
101
102         EffectiveStatementBase<?, ?> parentOfPrefix = this;
103         if (ctx.getPublicDefinition() == YangStmtMapping.SUBMODULE) {
104             parentOfPrefix = firstEffective(BelongsToEffectiveStatementImpl.class);
105             SourceException.throwIfNull(parentOfPrefix, ctx.getStatementSourceReference(),
106                     "Unable to find belongs-to statement in submodule %s.", ctx.getStatementArgument());
107         }
108
109         final PrefixEffectiveStatement prefixStmt = parentOfPrefix.firstEffective(PrefixEffectiveStatement.class);
110         SourceException.throwIfNull(prefixStmt, ctx.getStatementSourceReference(),
111                 "Unable to resolve prefix for module or submodule %s.", ctx.getStatementArgument());
112         this.prefix = prefixStmt.argument();
113
114         final YangVersionEffectiveStatement yangVersionStmt = firstEffective(YangVersionEffectiveStatement.class);
115         this.yangVersion = yangVersionStmt == null ? YangVersion.VERSION_1 : yangVersionStmt.argument();
116
117         final OpenconfigVersionEffectiveStatement semanticVersionStmt =
118                 firstEffective(OpenconfigVersionEffectiveStatement.class);
119         this.semanticVersion = semanticVersionStmt == null ? null : semanticVersionStmt.argument();
120
121         final OrganizationEffectiveStatement organizationStmt = firstEffective(OrganizationEffectiveStatement.class);
122         this.organization = organizationStmt == null ? null : organizationStmt.argument();
123
124         final ContactEffectiveStatement contactStmt = firstEffective(ContactEffectiveStatement.class);
125         this.contact = contactStmt == null ? null : contactStmt.argument();
126
127         // init submodules and substatements of submodules
128         final List<EffectiveStatement<?, ?>> substatementsOfSubmodules;
129         final Map<String, StmtContext<?, ?, ?>> includedSubmodulesMap = ctx
130                 .getAllFromCurrentStmtCtxNamespace(IncludedSubmoduleNameToModuleCtx.class);
131
132         if (includedSubmodulesMap == null || includedSubmodulesMap.isEmpty()) {
133             this.submodules = ImmutableSet.of();
134             this.submoduleContextsToBuild = ImmutableSet.of();
135             substatementsOfSubmodules = ImmutableList.of();
136         } else if (YangStmtMapping.MODULE.equals(ctx.getPublicDefinition())) {
137             /*
138              * Aggregation of substatements from submodules should be done only
139              * for modules. In case of submodules it does not make sense because
140              * of possible circular chains of includes between submodules.
141              */
142             final Collection<StmtContext<?, ?, ?>> includedSubmodules = includedSubmodulesMap.values();
143             final Set<Module> submodulesInit = new HashSet<>();
144             final List<EffectiveStatement<?, ?>> substatementsOfSubmodulesInit = new ArrayList<>();
145             for (final StmtContext<?, ?, ?> submoduleCtx : includedSubmodules) {
146                 final SubmoduleEffectiveStatementImpl submodule = (SubmoduleEffectiveStatementImpl) submoduleCtx
147                         .buildEffective();
148                 submodulesInit.add(submodule);
149                 substatementsOfSubmodulesInit.addAll(submodule.effectiveSubstatements().stream()
150                         .filter(sub -> sub instanceof SchemaNode || sub instanceof DataNodeContainer)
151                         .collect(Collectors.toList()));
152             }
153
154             this.submodules = ImmutableSet.copyOf(submodulesInit);
155             this.submoduleContextsToBuild = ImmutableSet.of();
156             substatementsOfSubmodules = ImmutableList.copyOf(substatementsOfSubmodulesInit);
157         } else {
158             /*
159              * Because of possible circular chains of includes between submodules we can
160              * collect only submodule contexts here and then build them during
161              * sealing of this statement.
162              */
163             final Set<StmtContext<?, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>>>
164                 submoduleContextsInit = new HashSet<>();
165             for (final StmtContext<?, ?, ?> submoduleCtx : includedSubmodulesMap.values()) {
166                 submoduleContextsInit.add(
167                     (StmtContext<?, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>>)submoduleCtx);
168             }
169
170             this.submoduleContextsToBuild = ImmutableSet.copyOf(submoduleContextsInit);
171             substatementsOfSubmodules = ImmutableList.of();
172         }
173
174         if (!submoduleContextsToBuild.isEmpty()) {
175             ((Mutable<?, ?, ?>) ctx).addMutableStmtToSeal(this);
176             sealed = false;
177         } else {
178             sealed = true;
179         }
180
181         // init substatements collections
182         final List<EffectiveStatement<?, ?>> effectiveSubstatements = new ArrayList<>();
183         effectiveSubstatements.addAll(effectiveSubstatements());
184         effectiveSubstatements.addAll(substatementsOfSubmodules);
185
186         final List<UnknownSchemaNode> unknownNodesInit = new ArrayList<>();
187         final Set<AugmentationSchemaNode> augmentationsInit = new LinkedHashSet<>();
188         final Set<ModuleImport> importsInit = new HashSet<>();
189         final Set<NotificationDefinition> notificationsInit = new HashSet<>();
190         final Set<RpcDefinition> rpcsInit = new HashSet<>();
191         final Set<Deviation> deviationsInit = new HashSet<>();
192         final Set<IdentitySchemaNode> identitiesInit = new HashSet<>();
193         final Set<FeatureDefinition> featuresInit = new HashSet<>();
194         final List<ExtensionDefinition> extensionNodesInit = new ArrayList<>();
195
196         final Map<QName, DataSchemaNode> mutableChildNodes = new LinkedHashMap<>();
197         final Set<GroupingDefinition> mutableGroupings = new HashSet<>();
198         final Set<UsesNode> mutableUses = new HashSet<>();
199         final Set<TypeDefinition<?>> mutableTypeDefinitions = new LinkedHashSet<>();
200         final Set<DataSchemaNode> mutablePublicChildNodes = new LinkedHashSet<>();
201
202         for (final EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
203             if (effectiveStatement instanceof UnknownSchemaNode) {
204                 unknownNodesInit.add((UnknownSchemaNode) effectiveStatement);
205             }
206             if (effectiveStatement instanceof AugmentationSchemaNode) {
207                 augmentationsInit.add((AugmentationSchemaNode) effectiveStatement);
208             }
209             if (effectiveStatement instanceof ModuleImport) {
210                 importsInit.add((ModuleImport) effectiveStatement);
211             }
212             if (effectiveStatement instanceof NotificationDefinition) {
213                 notificationsInit.add((NotificationDefinition) effectiveStatement);
214             }
215             if (effectiveStatement instanceof RpcDefinition) {
216                 rpcsInit.add((RpcDefinition) effectiveStatement);
217             }
218             if (effectiveStatement instanceof Deviation) {
219                 deviationsInit.add((Deviation) effectiveStatement);
220             }
221             if (effectiveStatement instanceof IdentitySchemaNode) {
222                 identitiesInit.add((IdentitySchemaNode) effectiveStatement);
223             }
224             if (effectiveStatement instanceof FeatureDefinition) {
225                 featuresInit.add((FeatureDefinition) effectiveStatement);
226             }
227             if (effectiveStatement instanceof ExtensionEffectiveStatementImpl) {
228                 extensionNodesInit.add((ExtensionEffectiveStatementImpl) effectiveStatement);
229             }
230             if (effectiveStatement instanceof DataSchemaNode) {
231                 final DataSchemaNode dataSchemaNode = (DataSchemaNode) effectiveStatement;
232                 if (!mutableChildNodes.containsKey(dataSchemaNode.getQName())) {
233                     mutableChildNodes.put(dataSchemaNode.getQName(), dataSchemaNode);
234                     mutablePublicChildNodes.add(dataSchemaNode);
235                 } else {
236                     throw EffectiveStmtUtils.createNameCollisionSourceException(ctx, effectiveStatement);
237                 }
238             }
239             if (effectiveStatement instanceof UsesNode) {
240                 final UsesNode usesNode = (UsesNode) effectiveStatement;
241                 if (!mutableUses.contains(usesNode)) {
242                     mutableUses.add(usesNode);
243                 } else {
244                     throw EffectiveStmtUtils.createNameCollisionSourceException(ctx, effectiveStatement);
245                 }
246             }
247             if (effectiveStatement instanceof TypedefEffectiveStatement) {
248                 final TypedefEffectiveStatement typeDef = (TypedefEffectiveStatement) effectiveStatement;
249                 final TypeDefinition<?> type = typeDef.getTypeDefinition();
250                 if (!mutableTypeDefinitions.contains(type)) {
251                     mutableTypeDefinitions.add(type);
252                 } else {
253                     throw EffectiveStmtUtils.createNameCollisionSourceException(ctx, effectiveStatement);
254                 }
255             }
256             if (effectiveStatement instanceof GroupingDefinition) {
257                 final GroupingDefinition grp = (GroupingDefinition) effectiveStatement;
258                 if (!mutableGroupings.contains(grp)) {
259                     mutableGroupings.add(grp);
260                 } else {
261                     throw EffectiveStmtUtils.createNameCollisionSourceException(ctx, effectiveStatement);
262                 }
263             }
264         }
265
266         this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
267         this.augmentations = ImmutableSet.copyOf(augmentationsInit);
268         this.imports = ImmutableSet.copyOf(importsInit);
269         this.notifications = ImmutableSet.copyOf(notificationsInit);
270         this.rpcs = ImmutableSet.copyOf(rpcsInit);
271         this.deviations = ImmutableSet.copyOf(deviationsInit);
272         this.identities = ImmutableSet.copyOf(identitiesInit);
273         this.features = ImmutableSet.copyOf(featuresInit);
274         this.extensionNodes = ImmutableList.copyOf(extensionNodesInit);
275
276         this.childNodes = ImmutableMap.copyOf(mutableChildNodes);
277         this.groupings = ImmutableSet.copyOf(mutableGroupings);
278         this.publicChildNodes = ImmutableSet.copyOf(mutablePublicChildNodes);
279         this.typeDefinitions = ImmutableSet.copyOf(mutableTypeDefinitions);
280         this.uses = ImmutableSet.copyOf(mutableUses);
281
282     }
283
284     @Override
285     public URI getNamespace() {
286         return getQNameModule().getNamespace();
287     }
288
289     @Override
290     public String getName() {
291         return name;
292     }
293
294     @Override
295     public Optional<Revision> getRevision() {
296         return getQNameModule().getRevision();
297     }
298
299     @Override
300     public String getPrefix() {
301         return prefix;
302     }
303
304     @Override
305     public YangVersion getYangVersion() {
306         return yangVersion;
307     }
308
309     @Override
310     public Optional<String> getOrganization() {
311         return Optional.ofNullable(organization);
312     }
313
314     @Override
315     public Optional<String> getContact() {
316         return Optional.ofNullable(contact);
317     }
318
319     @Override
320     public Set<ModuleImport> getImports() {
321         return imports;
322     }
323
324     @Override
325     public Set<Module> getSubmodules() {
326         checkState(sealed, "Attempt to get base submodules from unsealed submodule effective statement %s",
327             getQNameModule());
328         return submodules;
329     }
330
331     @Override
332     public Set<FeatureDefinition> getFeatures() {
333         return features;
334     }
335
336     @Override
337     public Set<NotificationDefinition> getNotifications() {
338         return notifications;
339     }
340
341     @Override
342     public Set<AugmentationSchemaNode> getAugmentations() {
343         return augmentations;
344     }
345
346     @Override
347     public Set<RpcDefinition> getRpcs() {
348         return rpcs;
349     }
350
351     @Override
352     public Set<Deviation> getDeviations() {
353         return deviations;
354     }
355
356     @Override
357     public List<ExtensionDefinition> getExtensionSchemaNodes() {
358         return extensionNodes;
359     }
360
361     @Override
362     public Set<IdentitySchemaNode> getIdentities() {
363         return identities;
364     }
365
366     @Nonnull
367     @Override
368     public List<UnknownSchemaNode> getUnknownSchemaNodes() {
369         return unknownNodes;
370     }
371
372     @Override
373     public final Set<TypeDefinition<?>> getTypeDefinitions() {
374         return typeDefinitions;
375     }
376
377     @Override
378     public final Set<DataSchemaNode> getChildNodes() {
379         return publicChildNodes;
380     }
381
382     @Override
383     public final Set<GroupingDefinition> getGroupings() {
384         return groupings;
385     }
386
387     @Override
388     public final Optional<DataSchemaNode> findDataChildByName(final QName name) {
389         // Child nodes are keyed by their container name, so we can do a direct lookup
390         return Optional.ofNullable(childNodes.get(requireNonNull(name)));
391     }
392
393     @Override
394     public Set<UsesNode> getUses() {
395         return uses;
396     }
397
398     @Override
399     public Optional<SemVer> getSemanticVersion() {
400         return Optional.ofNullable(semanticVersion);
401     }
402
403     @Override
404     public String toString() {
405         return MoreObjects.toStringHelper(this).omitNullValues()
406                 .add("name", name)
407                 .add("namespace", getNamespace())
408                 .add("revision", getRevision().orElse(null))
409                 .add("prefix", prefix)
410                 .add("yangVersion", yangVersion)
411                 .toString();
412     }
413
414     @Override
415     public void seal() {
416         if (!sealed) {
417             submodules = ImmutableSet.copyOf(Iterables.transform(submoduleContextsToBuild,
418                 ctx -> (Module) ctx.buildEffective()));
419             submoduleContextsToBuild = ImmutableSet.of();
420             sealed = true;
421         }
422     }
423 }