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