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