2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.rfc7950.repo;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
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;
23 import org.antlr.v4.runtime.ParserRuleContext;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser.ArgumentContext;
27 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser.StatementContext;
28 import org.opendaylight.yangtools.concepts.SemVer;
29 import org.opendaylight.yangtools.openconfig.model.api.OpenConfigStatements;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.common.Revision;
32 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
33 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
34 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
35 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
36 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
37 import org.opendaylight.yangtools.yang.parser.spi.source.DeclarationInTextSource;
38 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
41 * Helper transfer object which holds basic and dependency information for YANG
45 * There are two concrete implementations of this interface:
47 * <li>{@link ModuleDependencyInfo} - Dependency information for module</li>
48 * <li>{@link SubmoduleDependencyInfo} - Dependency information for submodule</li>
51 * @see ModuleDependencyInfo
52 * @see SubmoduleDependencyInfo
54 public abstract class YangModelDependencyInfo {
55 private static final String BELONGS_TO = YangStmtMapping.BELONGS_TO.getStatementName().getLocalName();
56 private static final String IMPORT = YangStmtMapping.IMPORT.getStatementName().getLocalName();
57 private static final String INCLUDE = YangStmtMapping.INCLUDE.getStatementName().getLocalName();
58 private static final String MODULE = YangStmtMapping.MODULE.getStatementName().getLocalName();
59 private static final String REVISION = YangStmtMapping.REVISION.getStatementName().getLocalName();
60 private static final String REVISION_DATE = YangStmtMapping.REVISION_DATE.getStatementName().getLocalName();
61 private static final String SUBMODULE = YangStmtMapping.SUBMODULE.getStatementName().getLocalName();
63 private static final String OPENCONFIG_VERSION = OpenConfigStatements.OPENCONFIG_VERSION.getStatementName()
65 private static final Splitter COLON_SPLITTER = Splitter.on(":").omitEmptyStrings().trimResults();
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;
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());
80 YangModelDependencyInfo(final String name, final String formattedRevision,
81 final ImmutableSet<ModuleImport> imports,
82 final ImmutableSet<ModuleImport> includes,
83 final Optional<SemVer> semVer) {
85 this.revision = Revision.ofNullable(formattedRevision).orElse(null);
86 this.moduleImports = imports;
87 this.submoduleIncludes = includes;
88 this.dependencies = ImmutableSet.<ModuleImport>builder()
89 .addAll(moduleImports).addAll(submoduleIncludes).build();
90 this.semVer = semVer.orElse(null);
94 * Returns immutable collection of all module imports. This collection contains both <code>import</code> statements
95 * and <code>include</code> statements for submodules.
97 * @return Immutable collection of imports.
99 public ImmutableSet<ModuleImport> getDependencies() {
104 * Returns model name.
108 public String getName() {
113 * Returns formatted revision string.
115 * @return formatted revision string
117 public String getFormattedRevision() {
118 return revision != null ? revision.toString() : null;
124 * @return revision, potentially null
126 public Optional<Revision> getRevision() {
127 return Optional.ofNullable(revision);
131 * Returns semantic version of module.
133 * @return semantic version
135 public Optional<SemVer> getSemanticVersion() {
136 return Optional.ofNullable(semVer);
140 public int hashCode() {
141 final int prime = 31;
143 result = prime * result + Objects.hashCode(name);
144 result = prime * result + Objects.hashCode(revision);
145 result = prime * result + Objects.hashCode(semVer);
150 public boolean equals(final Object obj) {
157 if (!(obj instanceof YangModelDependencyInfo)) {
160 final YangModelDependencyInfo other = (YangModelDependencyInfo) obj;
161 return Objects.equals(name, other.name) && Objects.equals(revision, other.revision)
162 && Objects.equals(semVer, other.semVer);
166 * Extracts {@link YangModelDependencyInfo} from an abstract syntax tree of a YANG model.
168 * @param source Source identifier
169 * @param tree Abstract syntax tree
170 * @return {@link YangModelDependencyInfo}
171 * @throws YangSyntaxErrorException If the AST is not a valid YANG module/submodule
173 static @NonNull YangModelDependencyInfo fromAST(final SourceIdentifier source, final ParserRuleContext tree)
174 throws YangSyntaxErrorException {
176 if (tree instanceof StatementContext) {
177 final StatementContext rootStatement = (StatementContext) tree;
178 return parseAST(rootStatement, source);
181 throw new YangSyntaxErrorException(source, 0, 0, "Unknown YANG text type");
184 private static @NonNull YangModelDependencyInfo parseAST(final StatementContext rootStatement,
185 final SourceIdentifier source) {
186 final String keyWordText = rootStatement.keyword().getText();
187 if (MODULE.equals(keyWordText)) {
188 return parseModuleContext(rootStatement, source);
190 if (SUBMODULE.equals(keyWordText)) {
191 return parseSubmoduleContext(rootStatement, source);
193 throw new IllegalArgumentException("Root of parsed AST must be either module or submodule");
197 * Extracts {@link YangModelDependencyInfo} from input stream containing a YANG model. This parsing does not
198 * validate full YANG module, only parses header up to the revisions and imports.
200 * @param refClass Base search class
201 * @param resourceName resource name, relative to refClass
202 * @return {@link YangModelDependencyInfo}
203 * @throws YangSyntaxErrorException If the resource does not pass syntactic analysis
204 * @throws IOException When the resource cannot be read
205 * @throws IllegalArgumentException
206 * If input stream is not valid YANG stream
209 public static YangModelDependencyInfo forResource(final Class<?> refClass, final String resourceName)
210 throws IOException, YangSyntaxErrorException {
211 final YangStatementStreamSource source = YangStatementStreamSource.create(
212 YangTextSchemaSource.forResource(refClass, resourceName));
213 final ParserRuleContext ast = source.getYangAST();
214 checkArgument(ast instanceof StatementContext);
215 return parseAST((StatementContext) ast, source.getIdentifier());
218 private static @NonNull YangModelDependencyInfo parseModuleContext(final StatementContext module,
219 final SourceIdentifier source) {
220 final String name = safeStringArgument(source, module, "module name");
221 final String latestRevision = getLatestRevision(module, source);
222 final Optional<SemVer> semVer = Optional.ofNullable(findSemanticVersion(module, source));
223 final ImmutableSet<ModuleImport> imports = parseImports(module, source);
224 final ImmutableSet<ModuleImport> includes = parseIncludes(module, source);
226 return new ModuleDependencyInfo(name, latestRevision, imports, includes, semVer);
229 private static ImmutableSet<ModuleImport> parseImports(final StatementContext module,
230 final SourceIdentifier source) {
231 final Set<ModuleImport> result = new HashSet<>();
232 for (final StatementContext subStatementContext : module.statement()) {
233 if (IMPORT.equals(subStatementContext.keyword().getText())) {
234 final String importedModuleName = safeStringArgument(source, subStatementContext,
235 "imported module name");
236 final String revisionDateStr = getRevisionDateString(subStatementContext, source);
237 final Revision revisionDate = Revision.ofNullable(revisionDateStr).orElse(null);
238 final SemVer importSemVer = findSemanticVersion(subStatementContext, source);
239 result.add(new ModuleImportImpl(importedModuleName, revisionDate, importSemVer));
242 return ImmutableSet.copyOf(result);
245 private static SemVer findSemanticVersion(final StatementContext statement, final SourceIdentifier source) {
246 String semVerString = null;
247 for (final StatementContext subStatement : statement.statement()) {
248 final String subStatementName = trimPrefix(subStatement.keyword().getText());
249 if (OPENCONFIG_VERSION.equals(subStatementName)) {
250 semVerString = safeStringArgument(source, subStatement, "version string");
255 return Strings.isNullOrEmpty(semVerString) ? null : SemVer.valueOf(semVerString);
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);
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 = safeStringArgument(source, subStatementContext,
275 "included submodule name");
276 final Revision revisionDate = Revision.ofNullable(revisionDateStr).orElse(null);
277 result.add(new ModuleImportImpl(IncludeModuleName, revisionDate));
280 return ImmutableSet.copyOf(result);
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 = safeStringArgument(source, importSubStatement, "imported module revision-date");
290 return revisionDateStr;
293 public static String getLatestRevision(final StatementContext module, final SourceIdentifier source) {
294 String latestRevision = null;
295 for (final StatementContext subStatementContext : module.statement()) {
296 if (REVISION.equals(subStatementContext.keyword().getText())) {
297 final String currentRevision = safeStringArgument(source, subStatementContext, "revision date");
298 if (latestRevision == null || latestRevision.compareTo(currentRevision) < 0) {
299 latestRevision = currentRevision;
303 return latestRevision;
306 private static @NonNull YangModelDependencyInfo parseSubmoduleContext(final StatementContext submodule,
307 final SourceIdentifier source) {
308 final String name = safeStringArgument(source, submodule, "submodule name");
309 final String belongsTo = parseBelongsTo(submodule, source);
311 final String latestRevision = getLatestRevision(submodule, source);
312 final ImmutableSet<ModuleImport> imports = parseImports(submodule, source);
313 final ImmutableSet<ModuleImport> includes = parseIncludes(submodule, source);
315 return new SubmoduleDependencyInfo(name, latestRevision, belongsTo, imports, includes);
318 private static String parseBelongsTo(final StatementContext submodule, final SourceIdentifier source) {
319 for (final StatementContext subStatementContext : submodule.statement()) {
320 if (BELONGS_TO.equals(subStatementContext.keyword().getText())) {
321 return safeStringArgument(source, subStatementContext, "belongs-to module name");
327 private static String safeStringArgument(final SourceIdentifier source, final StatementContext stmt,
329 final StatementSourceReference ref = getReference(source, stmt);
330 final ArgumentContext arg = stmt.argument();
331 checkArgument(arg != null, "Missing %s at %s", desc, ref);
332 // TODO: we probably need to understand yang version first....
333 return ArgumentContextUtils.rfc6020().stringFromStringContext(arg, ref);
336 private static StatementSourceReference getReference(final SourceIdentifier source,
337 final StatementContext context) {
338 return DeclarationInTextSource.atPosition(source.getName(), context.getStart().getLine(),
339 context.getStart().getCharPositionInLine());
343 * Dependency information for YANG module.
345 public static final class ModuleDependencyInfo extends YangModelDependencyInfo {
346 ModuleDependencyInfo(final String name, final String latestRevision, final ImmutableSet<ModuleImport> imports,
347 final ImmutableSet<ModuleImport> includes, final Optional<SemVer> semVer) {
348 super(name, latestRevision, imports, includes, semVer);
352 public String toString() {
353 return "Module [name=" + getName() + ", revision=" + getRevision()
354 + ", semanticVersion=" + getSemanticVersion().orElse(null)
355 + ", dependencies=" + getDependencies()
361 * Dependency information for submodule, also provides name for parent module.
363 public static final class SubmoduleDependencyInfo extends YangModelDependencyInfo {
364 private final String belongsTo;
366 private SubmoduleDependencyInfo(final String name, final String latestRevision, final String belongsTo,
367 final ImmutableSet<ModuleImport> imports, final ImmutableSet<ModuleImport> includes) {
368 super(name, latestRevision, imports, includes);
369 this.belongsTo = belongsTo;
373 * Returns name of parent module.
375 public String getParentModule() {
380 public String toString() {
381 return "Submodule [name=" + getName() + ", revision="
382 + getRevision() + ", dependencies=" + getDependencies()
388 * Utility implementation of {@link ModuleImport} to be used by {@link YangModelDependencyInfo}.
390 private static final class ModuleImportImpl implements ModuleImport {
392 private final Revision revision;
393 private final SemVer semVer;
394 private final String name;
396 ModuleImportImpl(final @NonNull String moduleName, final @Nullable Revision revision) {
397 this(moduleName, revision, null);
400 ModuleImportImpl(final @NonNull String moduleName, final @Nullable Revision revision,
401 final @Nullable SemVer semVer) {
402 this.name = requireNonNull(moduleName, "Module name must not be null.");
403 this.revision = revision;
404 this.semVer = semVer;
408 public String getModuleName() {
413 public Optional<Revision> getRevision() {
414 return Optional.ofNullable(revision);
418 public Optional<SemVer> getSemanticVersion() {
419 return Optional.ofNullable(semVer);
423 public String getPrefix() {
428 public Optional<String> getDescription() {
429 return Optional.empty();
433 public Optional<String> getReference() {
434 return Optional.empty();
438 public int hashCode() {
439 final int prime = 31;
441 result = prime * result + Objects.hashCode(name);
442 result = prime * result + Objects.hashCode(revision);
443 result = prime * result + Objects.hashCode(semVer);
448 public boolean equals(final Object obj) {
452 if (!(obj instanceof ModuleImportImpl)) {
455 final ModuleImportImpl other = (ModuleImportImpl) obj;
456 return name.equals(other.name) && Objects.equals(revision, other.revision)
457 && Objects.equals(getSemanticVersion(), other.getSemanticVersion());
461 public String toString() {
462 return "ModuleImportImpl [name=" + name + ", revision="
463 + QName.formattedRevision(Optional.ofNullable(revision)) + ", semanticVersion=" + semVer + "]";