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