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