7c30b80dc042796e4945a12e0ffc950284de5016
[yangtools.git] / parser / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / repo / TextToIRTransformer.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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 com.google.common.annotations.Beta;
11 import com.google.common.util.concurrent.Futures;
12 import java.io.IOException;
13 import org.eclipse.jdt.annotation.NonNull;
14 import org.opendaylight.yangtools.yang.ir.IRStatement;
15 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
16 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
17 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
18 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
19 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceTransformer;
20 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
21 import org.opendaylight.yangtools.yang.parser.rfc7950.antlr.IRSupport;
22
23 @Beta
24 public final class TextToIRTransformer extends SchemaSourceTransformer<YangTextSchemaSource, IRSchemaSource> {
25     private TextToIRTransformer(final SchemaRepository provider, final SchemaSourceRegistry consumer) {
26         super(provider, YangTextSchemaSource.class, consumer, IRSchemaSource.class,
27             input -> Futures.immediateFuture(transformText(input)));
28     }
29
30     public static @NonNull TextToIRTransformer create(final SchemaRepository provider,
31             final SchemaSourceRegistry consumer) {
32         return new TextToIRTransformer(provider, consumer);
33     }
34
35     public static @NonNull IRSchemaSource transformText(final YangTextSchemaSource text)
36             throws YangSyntaxErrorException, IOException {
37         final IRStatement rootStatement = IRSupport.createStatement(YangStatementStreamSource.parseYangSource(text));
38         final String name = YangModelDependencyInfo.safeStringArgument(text.getIdentifier(), rootStatement, "name");
39         final String latestRevision = YangModelDependencyInfo.getLatestRevision(rootStatement, text.getIdentifier());
40         final SourceIdentifier sourceId = new SourceIdentifier(name, latestRevision);
41
42         return new IRSchemaSource(sourceId, rootStatement, text.getSymbolicName().orElse(null));
43     }
44 }