Split out RFC7950 ANTLR grammars
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / repo / YangStatementStreamSource.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, 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 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.collect.ImmutableList;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import org.antlr.v4.runtime.CharStreams;
18 import org.antlr.v4.runtime.CommonTokenStream;
19 import org.antlr.v4.runtime.ParserRuleContext;
20 import org.antlr.v4.runtime.tree.ErrorNode;
21 import org.antlr.v4.runtime.tree.ParseTreeListener;
22 import org.antlr.v4.runtime.tree.ParseTreeWalker;
23 import org.antlr.v4.runtime.tree.TerminalNode;
24 import org.opendaylight.yangtools.concepts.AbstractIdentifiable;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.common.QNameModule;
27 import org.opendaylight.yangtools.yang.common.YangVersion;
28 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
29 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
30 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
31 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
32 import org.opendaylight.yangtools.yang.parser.antlr.YangStatementLexer;
33 import org.opendaylight.yangtools.yang.parser.antlr.YangStatementParser;
34 import org.opendaylight.yangtools.yang.parser.antlr.YangStatementParser.StatementContext;
35 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
36 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
37 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
38 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
39 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
40 import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter;
41
42 /**
43  * This class represents implementation of StatementStreamSource in order to emit YANG statements using supplied
44  * StatementWriter.
45  *
46  * @author Robert Varga
47  */
48 @Beta
49 public final class YangStatementStreamSource extends AbstractIdentifiable<SourceIdentifier>
50         implements StatementStreamSource {
51     private static final ParseTreeListener MAKE_IMMUTABLE_LISTENER = new ParseTreeListener() {
52         @Override
53         public void enterEveryRule(final ParserRuleContext ctx) {
54             // No-op
55         }
56
57         @Override
58         public void exitEveryRule(final ParserRuleContext ctx) {
59             ctx.children = ctx.children == null ? ImmutableList.of() : ImmutableList.copyOf(ctx.children);
60         }
61
62         @Override
63         public void visitTerminal(final TerminalNode node) {
64             // No-op
65         }
66
67         @Override
68         public void visitErrorNode(final ErrorNode node) {
69             // No-op
70         }
71     };
72
73     private final StatementContext context;
74     private final String sourceName;
75
76     private YangStatementStreamSource(final SourceIdentifier identifier,  final StatementContext context,
77             final String sourceName) {
78         super(identifier);
79         this.context = requireNonNull(context);
80         this.sourceName = sourceName;
81     }
82
83     /**
84      * Create a {@link YangStatementStreamSource} for a {@link YangTextSchemaSource}.
85      *
86      * @param source YangTextSchemaSource, must not be null
87      * @return A new {@link YangStatementStreamSource}
88      * @throws IOException When we fail to read the source
89      * @throws YangSyntaxErrorException If the source fails basic parsing
90      */
91     public static YangStatementStreamSource create(final YangTextSchemaSource source) throws IOException,
92             YangSyntaxErrorException {
93         final StatementContext context;
94         try (InputStream stream = source.openStream()) {
95             context = parseYangSource(source.getIdentifier(), stream);
96         }
97
98         return new YangStatementStreamSource(source.getIdentifier(), context, source.getSymbolicName().orElse(null));
99     }
100
101     /**
102      * Create a {@link YangStatementStreamSource} for a {@link ASTSchemaSource}.
103      *
104      * @param source YangTextSchemaSource, must not be null
105      * @return A new {@link YangStatementStreamSource}
106      */
107     public static YangStatementStreamSource create(final ASTSchemaSource source) {
108         final ParserRuleContext ast = source.getAST();
109         checkArgument(ast instanceof StatementContext,
110                 "Unsupported context class %s for source %s", ast.getClass(), source.getIdentifier());
111         return create(source.getIdentifier(), (StatementContext) ast, source.getSymbolicName().orElse(null));
112     }
113
114     public static YangStatementStreamSource create(final SourceIdentifier identifier, final StatementContext context,
115         final String symbolicName) {
116         return new YangStatementStreamSource(identifier, context, symbolicName);
117     }
118
119     @Override
120     public void writePreLinkage(final StatementWriter writer, final QNameToStatementDefinition stmtDef) {
121         new StatementContextVisitor(sourceName, writer, stmtDef, null, YangVersion.VERSION_1).visit(context);
122     }
123
124     @Override
125     public void writeLinkage(final StatementWriter writer, final QNameToStatementDefinition stmtDef,
126             final PrefixToModule preLinkagePrefixes, final YangVersion yangVersion) {
127         new StatementContextVisitor(sourceName, writer, stmtDef, preLinkagePrefixes, yangVersion) {
128             @Override
129             StatementDefinition resolveStatement(final QNameModule module, final String localName) {
130                 return stmtDef.getByNamespaceAndLocalName(module.getNamespace(), localName);
131             }
132         }.visit(context);
133     }
134
135     @Override
136     public void writeLinkageAndStatementDefinitions(final StatementWriter writer,
137             final QNameToStatementDefinition stmtDef, final PrefixToModule prefixes, final YangVersion yangVersion) {
138         new StatementContextVisitor(sourceName, writer, stmtDef, prefixes, yangVersion).visit(context);
139     }
140
141     @Override
142     public void writeFull(final StatementWriter writer, final QNameToStatementDefinition stmtDef,
143             final PrefixToModule prefixes, final YangVersion yangVersion) {
144         new StatementContextVisitor(sourceName, writer, stmtDef, prefixes, yangVersion) {
145             @Override
146             QName getValidStatementDefinition(final String keywordText, final StatementSourceReference ref) {
147                 return SourceException.throwIfNull(super.getValidStatementDefinition(keywordText, ref), ref,
148                     "%s is not a YANG statement or use of extension.", keywordText);
149             }
150         }.visit(context);
151     }
152
153     public ParserRuleContext getYangAST() {
154         return context;
155     }
156
157     private static StatementContext parseYangSource(final SourceIdentifier source, final InputStream stream)
158             throws IOException, YangSyntaxErrorException {
159         final YangStatementLexer lexer = new YangStatementLexer(CharStreams.fromStream(stream));
160         final YangStatementParser parser = new YangStatementParser(new CommonTokenStream(lexer));
161         // disconnect from console error output
162         lexer.removeErrorListeners();
163         parser.removeErrorListeners();
164
165         final YangErrorListener errorListener = new YangErrorListener(source);
166         lexer.addErrorListener(errorListener);
167         parser.addErrorListener(errorListener);
168
169         final StatementContext result = parser.statement();
170         errorListener.validate();
171
172         // Walk the resulting tree and replace each children with an immutable list, lowering memory requirements
173         // and making sure the resulting tree will not get accidentally modified. An alternative would be to use
174         // org.antlr.v4.runtime.Parser.TrimToSizeListener, but that does not make the tree immutable.
175         ParseTreeWalker.DEFAULT.walk(MAKE_IMMUTABLE_LISTENER, result);
176
177         return result;
178     }
179 }