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