Rework YANG lexer/parser
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / repo / ArgumentContextUtils.java
1 /*
2  * Copyright (c) 2015 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.rfc7950.repo;
9
10 import static com.google.common.base.Verify.verify;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.CharMatcher;
14 import com.google.common.base.VerifyException;
15 import org.antlr.v4.runtime.Token;
16 import org.antlr.v4.runtime.tree.ParseTree;
17 import org.antlr.v4.runtime.tree.TerminalNode;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.opendaylight.yangtools.yang.common.YangVersion;
20 import org.opendaylight.yangtools.yang.parser.antlr.YangStatementParser;
21 import org.opendaylight.yangtools.yang.parser.antlr.YangStatementParser.ArgumentContext;
22 import org.opendaylight.yangtools.yang.parser.antlr.YangStatementParser.QuotedStringContext;
23 import org.opendaylight.yangtools.yang.parser.antlr.YangStatementParser.UnquotedStringContext;
24 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
25 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
26
27 /**
28  * Utilities for dealing with YANG statement argument strings, encapsulated in ANTLR grammar's ArgumentContext.
29  */
30 abstract class ArgumentContextUtils {
31     /**
32      * YANG 1.0 version of strings, which were not completely clarified in
33      * <a href="https://tools.ietf.org/html/rfc6020#section-6.1.3">RFC6020</a>.
34      */
35     private static final class RFC6020 extends ArgumentContextUtils {
36         private static final @NonNull RFC6020 INSTANCE = new RFC6020();
37
38         @Override
39         void checkDoubleQuoted(final String str, final StatementSourceReference ref, final int backslash) {
40             // No-op
41         }
42
43         @Override
44         void checkUnquoted(final String str, final StatementSourceReference ref) {
45             // No-op
46         }
47     }
48
49     /**
50      * YANG 1.1 version of strings, which were clarified in
51      * <a href="https://tools.ietf.org/html/rfc7950#section-6.1.3">RFC7950</a>.
52      */
53     // NOTE: the differences clarified lead to a proper ability to delegate this to ANTLR lexer, but that does not
54     //       understand versions and needs to work with both.
55     private static final class RFC7950 extends ArgumentContextUtils {
56         private static final CharMatcher ANYQUOTE_MATCHER = CharMatcher.anyOf("'\"");
57         private static final @NonNull RFC7950 INSTANCE = new RFC7950();
58
59         @Override
60         void checkDoubleQuoted(final String str, final StatementSourceReference ref, final int backslash) {
61             if (backslash < str.length() - 1) {
62                 int index = backslash;
63                 while (index != -1) {
64                     switch (str.charAt(index + 1)) {
65                         case 'n':
66                         case 't':
67                         case '\\':
68                         case '\"':
69                             index = str.indexOf('\\', index + 2);
70                             break;
71                         default:
72                             throw new SourceException(ref, "YANG 1.1: illegal double quoted string (%s). In double "
73                                 + "quoted string the backslash must be followed by one of the following character "
74                                 + "[n,t,\",\\], but was '%s'.", str, str.charAt(index + 1));
75                     }
76                 }
77             }
78         }
79
80         @Override
81         void checkUnquoted(final String str, final StatementSourceReference ref) {
82             SourceException.throwIf(ANYQUOTE_MATCHER.matchesAnyOf(str), ref,
83                 "YANG 1.1: unquoted string (%s) contains illegal characters", str);
84         }
85     }
86
87     private static final CharMatcher WHITESPACE_MATCHER = CharMatcher.whitespace();
88
89     private ArgumentContextUtils() {
90         // Hidden on purpose
91     }
92
93     static @NonNull ArgumentContextUtils forVersion(final YangVersion version) {
94         switch (version) {
95             case VERSION_1:
96                 return RFC6020.INSTANCE;
97             case VERSION_1_1:
98                 return RFC7950.INSTANCE;
99             default:
100                 throw new IllegalStateException("Unhandled version " + version);
101         }
102     }
103
104     // TODO: teach the only caller about versions, or provide common-enough idioms for its use case
105     static @NonNull ArgumentContextUtils rfc6020() {
106         return RFC6020.INSTANCE;
107     }
108
109     /*
110      * NOTE: this method we do not use convenience methods provided by generated parser code, but instead are making
111      *       based on the grammar assumptions. While this is more verbose, it cuts out a number of unnecessary code,
112      *       such as intermediate List allocation et al.
113      */
114     final @NonNull String stringFromStringContext(final ArgumentContext context, final StatementSourceReference ref) {
115         // Get first child, which we fully expect to exist and be a lexer token
116         final ParseTree firstChild = context.getChild(0);
117         if (firstChild instanceof UnquotedStringContext) {
118             // Simple case, just grab the text, as ANTLR has done all the heavy lifting
119             final String str = firstChild.getText();
120             checkUnquoted(str, ref);
121             return str;
122         }
123
124         verify(firstChild instanceof QuotedStringContext, "Unexpected shape of %s", context);
125         if (context.getChildCount() == 1) {
126             // No concatenation needed, special-case
127             return unquoteString((QuotedStringContext) firstChild, ref);
128         }
129
130         // Potentially-complex case of string quoting, escaping and concatenation.
131         return concatStrings(context, ref);
132     }
133
134     private String unquoteString(final QuotedStringContext context, final StatementSourceReference ref) {
135         final ParseTree secondChild = context.getChild(1);
136         verify(secondChild instanceof TerminalNode, "Unexpected shape of %s", context);
137         final Token secondToken = ((TerminalNode) secondChild).getSymbol();
138         final int type = secondToken.getType();
139         switch (type) {
140             case YangStatementParser.DQUOT_END:
141             case YangStatementParser.SQUOT_END:
142                 // We are missing actual body, hence this is an empty string
143                 return "";
144             case YangStatementParser.SQUOT_STRING:
145                 return secondChild.getText();
146             case YangStatementParser.DQUOT_STRING:
147                 // We should be looking at the first token, which is DQUOT_START, but since it is a single-character
148                 // token, let's not bother.
149                 return normalizeDoubleQuoted(secondChild.getText(), secondToken.getCharPositionInLine() - 1, ref);
150             default:
151                 throw new VerifyException("Unhandled token type " + type);
152         }
153     }
154
155     private String concatStrings(final ArgumentContext context, final StatementSourceReference ref) {
156         /*
157          * We have multiple fragments. Just search the tree. This code is equivalent to
158          *
159          *    context.quotedString().forEach(stringNode -> sb.append(unquoteString(stringNode, ref))
160          *
161          * except we minimize allocations which that would do.
162          */
163         final StringBuilder sb = new StringBuilder();
164         for (ParseTree child : context.children) {
165             if (child instanceof TerminalNode) {
166                 final TerminalNode childNode = (TerminalNode) child;
167                 switch (childNode.getSymbol().getType()) {
168                     case YangStatementParser.SEP:
169                     case YangStatementParser.PLUS:
170                         // Operator, which we are handling by concat
171                         break;
172                     default:
173                         throw new VerifyException("Unexpected symbol in " + childNode);
174                 }
175             } else {
176                 verify(child instanceof QuotedStringContext, "Unexpected fragment component %s", child);
177                 sb.append(unquoteString((QuotedStringContext) child, ref));
178                 continue;
179             }
180         }
181         return sb.toString();
182     }
183
184     private String normalizeDoubleQuoted(final String str, final int dquot, final StatementSourceReference ref) {
185         // Whitespace normalization happens irrespective of further handling and has no effect on the result
186         final String stripped = trimWhitespace(str, dquot);
187
188         // Now we need to perform some amount of unescaping. This serves as a pre-check before we dispatch
189         // validation and processing (which will reuse the work we have done)
190         final int backslash = stripped.indexOf('\\');
191         return backslash == -1 ? stripped : unescape(ref, stripped, backslash);
192     }
193
194     /*
195      * NOTE: Enforcement and transformation logic done by these methods should logically reside in the lexer and ANTLR
196      *       account the for it with lexer modes. We do not want to force a re-lexing phase in the parser just because
197      *       we decided to let ANTLR do the work.
198      */
199     abstract void checkDoubleQuoted(String str, StatementSourceReference ref, int backslash);
200
201     abstract void checkUnquoted(String str, StatementSourceReference ref);
202
203     /*
204      * Unescape escaped double quotes, tabs, new line and backslash in the inner string and trim the result.
205      */
206     private String unescape(final StatementSourceReference ref, final String str, final int backslash) {
207         checkDoubleQuoted(str, ref, backslash);
208         StringBuilder sb = new StringBuilder(str.length());
209         unescapeBackslash(sb, str, backslash);
210         return sb.toString();
211     }
212
213     @VisibleForTesting
214     static void unescapeBackslash(final StringBuilder sb, final String str, final int backslash) {
215         String substring = str;
216         int backslashIndex = backslash;
217         while (true) {
218             int nextIndex = backslashIndex + 1;
219             if (backslashIndex != -1 && nextIndex < substring.length()) {
220                 replaceBackslash(sb, substring, nextIndex);
221                 substring = substring.substring(nextIndex + 1);
222                 if (substring.length() > 0) {
223                     backslashIndex = substring.indexOf('\\');
224                 } else {
225                     break;
226                 }
227             } else {
228                 sb.append(substring);
229                 break;
230             }
231         }
232     }
233
234     private static void replaceBackslash(final StringBuilder sb, final String str, final int nextAfterBackslash) {
235         int backslash = nextAfterBackslash - 1;
236         sb.append(str, 0, backslash);
237         final char c = str.charAt(nextAfterBackslash);
238         switch (c) {
239             case '\\':
240             case '"':
241                 sb.append(c);
242                 break;
243             case 't':
244                 sb.append('\t');
245                 break;
246             case 'n':
247                 sb.append('\n');
248                 break;
249             default:
250                 sb.append(str, backslash, nextAfterBackslash + 1);
251         }
252     }
253
254     @VisibleForTesting
255     static String trimWhitespace(final String str, final int dquot) {
256         final int firstBrk = str.indexOf('\n');
257         if (firstBrk == -1) {
258             return str;
259         }
260
261         // Okay, we may need to do some trimming, set up a builder and append the first segment
262         final int length = str.length();
263         final StringBuilder sb = new StringBuilder(length);
264
265         // Append first segment, which needs only tail-trimming
266         sb.append(str, 0, trimTrailing(str, 0, firstBrk)).append('\n');
267
268         // With that out of the way, setup our iteration state. The string segment we are looking at is
269         // str.substring(start, end), which is guaranteed not to include any line breaks, i.e. end <= brk unless we are
270         // at the last segment.
271         int start = firstBrk + 1;
272         int brk = str.indexOf('\n', start);
273
274         // Loop over inner strings
275         while (brk != -1) {
276             trimLeadingAndAppend(sb, dquot, str, start, trimTrailing(str, start, brk)).append('\n');
277             start = brk + 1;
278             brk = str.indexOf('\n', start);
279         }
280
281         return trimLeadingAndAppend(sb, dquot, str, start, length).toString();
282     }
283
284     private static StringBuilder trimLeadingAndAppend(final StringBuilder sb, final int dquot, final String str,
285             final int start, final int end) {
286         int offset = start;
287         int pos = 0;
288
289         while (pos <= dquot) {
290             if (offset == end) {
291                 // We ran out of data, nothing to append
292                 return sb;
293             }
294
295             final char ch = str.charAt(offset);
296             if (ch == '\t') {
297                 // tabs are to be treated as 8 spaces
298                 pos += 8;
299             } else if (WHITESPACE_MATCHER.matches(ch)) {
300                 pos++;
301             } else {
302                 break;
303             }
304
305             offset++;
306         }
307
308         // We have expanded beyond double quotes, push equivalent spaces
309         while (pos - 1 > dquot) {
310             sb.append(' ');
311             pos--;
312         }
313
314         return sb.append(str, offset, end);
315     }
316
317     private static int trimTrailing(final String str, final int start, final int end) {
318         int ret = end;
319         while (ret > start) {
320             final int prev = ret - 1;
321             if (!WHITESPACE_MATCHER.matches(str.charAt(prev))) {
322                 break;
323             }
324             ret = prev;
325         }
326         return ret;
327     }
328 }