Bump odlparent to 10.0.0
[yangtools.git] / parser / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / repo / YangModelDependencyInfo.java
1 /*
2  * Copyright (c) 2014 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.repo;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.ImmutableSet;
16 import java.io.IOException;
17 import java.util.HashSet;
18 import java.util.Objects;
19 import java.util.Optional;
20 import java.util.Set;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.opendaylight.yangtools.concepts.SemVer;
24 import org.opendaylight.yangtools.openconfig.model.api.OpenConfigStatements;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.common.Revision;
27 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
28 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
29 import org.opendaylight.yangtools.yang.model.api.stmt.ImportEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
31 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
32 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
33 import org.opendaylight.yangtools.yang.parser.rfc7950.ir.IRArgument;
34 import org.opendaylight.yangtools.yang.parser.rfc7950.ir.IRKeyword;
35 import org.opendaylight.yangtools.yang.parser.rfc7950.ir.IRKeyword.Unqualified;
36 import org.opendaylight.yangtools.yang.parser.rfc7950.ir.IRSchemaSource;
37 import org.opendaylight.yangtools.yang.parser.rfc7950.ir.IRStatement;
38 import org.opendaylight.yangtools.yang.parser.spi.source.ExplicitStatement;
39 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
40
41 /**
42  * Helper transfer object which holds basic and dependency information for YANG
43  * model.
44  *
45  * <p>
46  * There are two concrete implementations of this interface:
47  * <ul>
48  * <li>{@link ModuleDependencyInfo} - Dependency information for module</li>
49  * <li>{@link SubmoduleDependencyInfo} - Dependency information for submodule</li>
50  * </ul>
51  *
52  * @see ModuleDependencyInfo
53  * @see SubmoduleDependencyInfo
54  */
55 public abstract class YangModelDependencyInfo {
56     private static final String BELONGS_TO = YangStmtMapping.BELONGS_TO.getStatementName().getLocalName();
57     private static final String IMPORT = YangStmtMapping.IMPORT.getStatementName().getLocalName();
58     private static final String INCLUDE = YangStmtMapping.INCLUDE.getStatementName().getLocalName();
59     private static final String MODULE = YangStmtMapping.MODULE.getStatementName().getLocalName();
60     private static final String REVISION = YangStmtMapping.REVISION.getStatementName().getLocalName();
61     private static final String REVISION_DATE = YangStmtMapping.REVISION_DATE.getStatementName().getLocalName();
62     private static final String SUBMODULE = YangStmtMapping.SUBMODULE.getStatementName().getLocalName();
63
64     private static final String OPENCONFIG_VERSION = OpenConfigStatements.OPENCONFIG_VERSION.getStatementName()
65             .getLocalName();
66
67     private final String name;
68     private final Revision revision;
69     private final SemVer semVer;
70     private final ImmutableSet<ModuleImport> submoduleIncludes;
71     private final ImmutableSet<ModuleImport> moduleImports;
72     private final ImmutableSet<ModuleImport> dependencies;
73
74     YangModelDependencyInfo(final String name, final String formattedRevision,
75             final ImmutableSet<ModuleImport> imports,
76             final ImmutableSet<ModuleImport> includes) {
77         this(name, formattedRevision, imports, includes, Optional.empty());
78     }
79
80     YangModelDependencyInfo(final String name, final String formattedRevision,
81             final ImmutableSet<ModuleImport> imports,
82             final ImmutableSet<ModuleImport> includes,
83             final Optional<SemVer> semVer) {
84         this.name = name;
85         revision = Revision.ofNullable(formattedRevision).orElse(null);
86         moduleImports = imports;
87         submoduleIncludes = includes;
88         dependencies = ImmutableSet.<ModuleImport>builder()
89                 .addAll(moduleImports).addAll(submoduleIncludes).build();
90         this.semVer = semVer.orElse(null);
91     }
92
93     /**
94      * Returns immutable collection of all module imports. This collection contains both <code>import</code> statements
95      * and <code>include</code> statements for submodules.
96      *
97      * @return Immutable collection of imports.
98      */
99     public ImmutableSet<ModuleImport> getDependencies() {
100         return dependencies;
101     }
102
103     /**
104      * Returns model name.
105      *
106      * @return model name
107      */
108     public String getName() {
109         return name;
110     }
111
112     /**
113      * Returns formatted revision string.
114      *
115      * @return formatted revision string
116      */
117     public String getFormattedRevision() {
118         return revision != null ? revision.toString() : null;
119     }
120
121     /**
122      * Returns revision.
123      *
124      * @return revision, potentially null
125      */
126     public Optional<Revision> getRevision() {
127         return Optional.ofNullable(revision);
128     }
129
130     /**
131      * Returns semantic version of module.
132      *
133      * @return semantic version
134      */
135     public Optional<SemVer> getSemanticVersion() {
136         return Optional.ofNullable(semVer);
137     }
138
139     @Override
140     public int hashCode() {
141         final int prime = 31;
142         int result = 1;
143         result = prime * result + Objects.hashCode(name);
144         result = prime * result + Objects.hashCode(revision);
145         result = prime * result + Objects.hashCode(semVer);
146         return result;
147     }
148
149     @Override
150     public boolean equals(final Object obj) {
151         if (this == obj) {
152             return true;
153         }
154         if (obj == null) {
155             return false;
156         }
157         if (!(obj instanceof YangModelDependencyInfo)) {
158             return false;
159         }
160         final YangModelDependencyInfo other = (YangModelDependencyInfo) obj;
161         return Objects.equals(name, other.name) && Objects.equals(revision, other.revision)
162                 && Objects.equals(semVer, other.semVer);
163     }
164
165     /**
166      * Extracts {@link YangModelDependencyInfo} from an intermediate representation root statement of a YANG model.
167      *
168      * @param source Schema source
169      * @return {@link YangModelDependencyInfo}
170      * @throws IllegalArgumentException If the root statement is not a valid YANG module/submodule
171      */
172     public static @NonNull YangModelDependencyInfo forIR(final IRSchemaSource source) {
173         return forIR(source.getRootStatement(), source.getIdentifier());
174     }
175
176     /**
177      * Extracts {@link YangModelDependencyInfo} from an intermediate representation root statement of a YANG model.
178      *
179      * @param source Source identifier
180      * @param rootStatement root statement
181      * @return {@link YangModelDependencyInfo}
182      * @throws IllegalArgumentException If the root statement is not a valid YANG module/submodule
183      */
184     static @NonNull YangModelDependencyInfo forIR(final IRStatement rootStatement,
185             final SourceIdentifier source) {
186         final IRKeyword keyword = rootStatement.keyword();
187         checkArgument(keyword instanceof Unqualified, "Invalid root statement %s", keyword);
188
189         final String arg = keyword.identifier();
190         if (MODULE.equals(arg)) {
191             return parseModuleContext(rootStatement, source);
192         }
193         if (SUBMODULE.equals(arg)) {
194             return parseSubmoduleContext(rootStatement, source);
195         }
196         throw new IllegalArgumentException("Root of parsed AST must be either module or submodule");
197     }
198
199     /**
200      * Extracts {@link YangModelDependencyInfo} from a {@link YangTextSchemaSource}. This parsing does not
201      * validate full YANG module, only parses header up to the revisions and imports.
202      *
203      * @param yangText {@link YangTextSchemaSource}
204      * @return {@link YangModelDependencyInfo}
205      * @throws YangSyntaxErrorException If the resource does not pass syntactic analysis
206      * @throws IOException When the resource cannot be read
207      */
208     public static YangModelDependencyInfo forYangText(final YangTextSchemaSource yangText)
209             throws IOException, YangSyntaxErrorException {
210         final YangStatementStreamSource source = YangStatementStreamSource.create(yangText);
211         return forIR(source.rootStatement(), source.getIdentifier());
212     }
213
214     private static @NonNull YangModelDependencyInfo parseModuleContext(final IRStatement module,
215             final SourceIdentifier source) {
216         final String name = safeStringArgument(source, module, "module name");
217         final String latestRevision = getLatestRevision(module, source);
218         final Optional<SemVer> semVer = Optional.ofNullable(findSemanticVersion(module, source));
219         final ImmutableSet<ModuleImport> imports = parseImports(module, source);
220         final ImmutableSet<ModuleImport> includes = parseIncludes(module, source);
221
222         return new ModuleDependencyInfo(name, latestRevision, imports, includes, semVer);
223     }
224
225     private static ImmutableSet<ModuleImport> parseImports(final IRStatement module,
226             final SourceIdentifier source) {
227         final Set<ModuleImport> result = new HashSet<>();
228         for (final IRStatement substatement : module.statements()) {
229             if (isBuiltin(substatement, IMPORT)) {
230                 final String importedModuleName = safeStringArgument(source, substatement, "imported module name");
231                 final String revisionDateStr = getRevisionDateString(substatement, source);
232                 final Revision revisionDate = Revision.ofNullable(revisionDateStr).orElse(null);
233                 final SemVer importSemVer = findSemanticVersion(substatement, source);
234                 result.add(new ModuleImportImpl(importedModuleName, revisionDate, importSemVer));
235             }
236         }
237         return ImmutableSet.copyOf(result);
238     }
239
240     @Beta
241     public static SemVer findSemanticVersion(final IRStatement statement, final SourceIdentifier source) {
242         String semVerString = null;
243         for (final IRStatement substatement : statement.statements()) {
244             // FIXME: this should also check we are using a prefix
245             if (OPENCONFIG_VERSION.equals(substatement.keyword().identifier())) {
246                 semVerString = safeStringArgument(source,  substatement, "version string");
247                 break;
248             }
249         }
250
251         return Strings.isNullOrEmpty(semVerString) ? null : SemVer.valueOf(semVerString);
252     }
253
254     private static boolean isBuiltin(final IRStatement stmt, final String localName) {
255         final IRKeyword keyword = stmt.keyword();
256         return keyword instanceof Unqualified && localName.equals(keyword.identifier());
257     }
258
259     private static ImmutableSet<ModuleImport> parseIncludes(final IRStatement module, final SourceIdentifier source) {
260         final Set<ModuleImport> result = new HashSet<>();
261         for (final IRStatement substatement : module.statements()) {
262             if (isBuiltin(substatement, INCLUDE)) {
263                 final String revisionDateStr = getRevisionDateString(substatement, source);
264                 final String IncludeModuleName = safeStringArgument(source, substatement, "included submodule name");
265                 final Revision revisionDate = Revision.ofNullable(revisionDateStr).orElse(null);
266                 result.add(new ModuleImportImpl(IncludeModuleName, revisionDate));
267             }
268         }
269         return ImmutableSet.copyOf(result);
270     }
271
272     private static String getRevisionDateString(final IRStatement importStatement, final SourceIdentifier source) {
273         String revisionDateStr = null;
274         for (final IRStatement substatement : importStatement.statements()) {
275             if (isBuiltin(substatement, REVISION_DATE)) {
276                 revisionDateStr = safeStringArgument(source, substatement, "imported module revision-date");
277             }
278         }
279         return revisionDateStr;
280     }
281
282     public static String getLatestRevision(final IRStatement module, final SourceIdentifier source) {
283         String latestRevision = null;
284         for (final IRStatement substatement : module.statements()) {
285             if (isBuiltin(substatement, REVISION)) {
286                 final String currentRevision = safeStringArgument(source, substatement, "revision date");
287                 if (latestRevision == null || latestRevision.compareTo(currentRevision) < 0) {
288                     latestRevision = currentRevision;
289                 }
290             }
291         }
292         return latestRevision;
293     }
294
295     private static @NonNull YangModelDependencyInfo parseSubmoduleContext(final IRStatement submodule,
296             final SourceIdentifier source) {
297         final String name = safeStringArgument(source, submodule, "submodule name");
298         final String belongsTo = parseBelongsTo(submodule, source);
299
300         final String latestRevision = getLatestRevision(submodule, source);
301         final ImmutableSet<ModuleImport> imports = parseImports(submodule, source);
302         final ImmutableSet<ModuleImport> includes = parseIncludes(submodule, source);
303
304         return new SubmoduleDependencyInfo(name, latestRevision, belongsTo, imports, includes);
305     }
306
307     private static String parseBelongsTo(final IRStatement submodule, final SourceIdentifier source) {
308         for (final IRStatement substatement : submodule.statements()) {
309             if (isBuiltin(substatement, BELONGS_TO)) {
310                 return safeStringArgument(source, substatement, "belongs-to module name");
311             }
312         }
313         return null;
314     }
315
316     static String safeStringArgument(final SourceIdentifier source, final IRStatement stmt, final String desc) {
317         final StatementSourceReference ref = getReference(source, stmt);
318         final IRArgument arg = stmt.argument();
319         if (arg == null) {
320             throw new IllegalArgumentException("Missing " + desc + " at " + ref);
321         }
322
323         // TODO: we probably need to understand yang version first....
324         return ArgumentContextUtils.rfc6020().stringFromStringContext(arg, ref);
325     }
326
327     private static StatementSourceReference getReference(final SourceIdentifier source, final IRStatement stmt) {
328         return ExplicitStatement.atPosition(source.getName(), stmt.startLine(), stmt.startColumn() + 1);
329     }
330
331     /**
332      * Dependency information for YANG module.
333      */
334     public static final class ModuleDependencyInfo extends YangModelDependencyInfo {
335         ModuleDependencyInfo(final String name, final String latestRevision, final ImmutableSet<ModuleImport> imports,
336                 final ImmutableSet<ModuleImport> includes, final Optional<SemVer> semVer) {
337             super(name, latestRevision, imports, includes, semVer);
338         }
339
340         @Override
341         public String toString() {
342             return "Module [name=" + getName() + ", revision=" + getRevision()
343                 + ", semanticVersion=" + getSemanticVersion().orElse(null)
344                 + ", dependencies=" + getDependencies()
345                 + "]";
346         }
347     }
348
349     /**
350      * Dependency information for submodule, also provides name for parent module.
351      */
352     public static final class SubmoduleDependencyInfo extends YangModelDependencyInfo {
353         private final String belongsTo;
354
355         private SubmoduleDependencyInfo(final String name, final String latestRevision, final String belongsTo,
356                 final ImmutableSet<ModuleImport> imports, final ImmutableSet<ModuleImport> includes) {
357             super(name, latestRevision, imports, includes);
358             this.belongsTo = belongsTo;
359         }
360
361         /**
362          * Returns name of parent module.
363          *
364          * @return The module this info belongs to
365          */
366         public String getParentModule() {
367             return belongsTo;
368         }
369
370         @Override
371         public String toString() {
372             return "Submodule [name=" + getName() + ", revision="
373                     + getRevision() + ", dependencies=" + getDependencies()
374                     + "]";
375         }
376     }
377
378     /**
379      * Utility implementation of {@link ModuleImport} to be used by {@link YangModelDependencyInfo}.
380      */
381     // FIXME: this is a rather nasty misuse of APIs :(
382     private static final class ModuleImportImpl implements ModuleImport {
383
384         private final Revision revision;
385         private final SemVer semVer;
386         private final String name;
387
388         ModuleImportImpl(final @NonNull String moduleName, final @Nullable Revision revision) {
389             this(moduleName, revision, null);
390         }
391
392         ModuleImportImpl(final @NonNull String moduleName, final @Nullable Revision revision,
393                 final @Nullable SemVer semVer) {
394             name = requireNonNull(moduleName, "Module name must not be null.");
395             this.revision = revision;
396             this.semVer = semVer;
397         }
398
399         @Override
400         public String getModuleName() {
401             return name;
402         }
403
404         @Override
405         public Optional<Revision> getRevision() {
406             return Optional.ofNullable(revision);
407         }
408
409         @Override
410         public Optional<SemVer> getSemanticVersion() {
411             return Optional.ofNullable(semVer);
412         }
413
414         @Override
415         public String getPrefix() {
416             throw new UnsupportedOperationException();
417         }
418
419         @Override
420         public Optional<String> getDescription() {
421             return Optional.empty();
422         }
423
424         @Override
425         public Optional<String> getReference() {
426             return Optional.empty();
427         }
428
429         @Override
430         public ImportEffectiveStatement asEffectiveStatement() {
431             throw new UnsupportedOperationException();
432         }
433
434         @Override
435         public int hashCode() {
436             final int prime = 31;
437             int result = 1;
438             result = prime * result + Objects.hashCode(name);
439             result = prime * result + Objects.hashCode(revision);
440             result = prime * result + Objects.hashCode(semVer);
441             return result;
442         }
443
444         @Override
445         public boolean equals(final Object obj) {
446             if (this == obj) {
447                 return true;
448             }
449             if (!(obj instanceof ModuleImportImpl)) {
450                 return false;
451             }
452             final ModuleImportImpl other = (ModuleImportImpl) obj;
453             return name.equals(other.name) && Objects.equals(revision, other.revision)
454                     && Objects.equals(getSemanticVersion(), other.getSemanticVersion());
455         }
456
457         @Override
458         public String toString() {
459             return "ModuleImportImpl [name=" + name + ", revision="
460                     + QName.formattedRevision(Optional.ofNullable(revision)) + ", semanticVersion=" + semVer + "]";
461         }
462     }
463 }