Optimize ArgumentContext parsing
[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 java.util.regex.Pattern;
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.spi.source.SourceException;
23 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
24
25 /**
26  * Utilities for dealing with YANG statement argument strings, encapsulated in ANTLR grammar's ArgumentContext.
27  */
28 enum ArgumentContextUtils {
29     /**
30      * YANG 1.0 version of strings, which were not completely clarified in RFC6020.
31      */
32     RFC6020 {
33         @Override
34         void checkDoubleQuotedString(final String str, final StatementSourceReference ref) {
35             // No-op
36         }
37
38         @Override
39         void checkUnquotedString(final String str, final StatementSourceReference ref) {
40             // No-op
41         }
42     },
43     /**
44      * YANG 1.1 version of strings, which were clarified in RFC7950.
45      */
46     // NOTE: the differences clarified lead to a proper ability to delegate this to ANTLR lexer, but that does not
47     //       understand versions and needs to work with both.
48     RFC7950 {
49         @Override
50         void checkDoubleQuotedString(final String str, final StatementSourceReference ref) {
51             for (int i = 0; i < str.length() - 1; i++) {
52                 if (str.charAt(i) == '\\') {
53                     switch (str.charAt(i + 1)) {
54                         case 'n':
55                         case 't':
56                         case '\\':
57                         case '\"':
58                             i++;
59                             break;
60                         default:
61                             throw new SourceException(ref, "YANG 1.1: illegal double quoted string (%s). In double "
62                                     + "quoted string the backslash must be followed by one of the following character "
63                                     + "[n,t,\",\\], but was '%s'.", str, str.charAt(i + 1));
64                     }
65                 }
66             }
67         }
68
69         @Override
70         void checkUnquotedString(final String str, final StatementSourceReference ref) {
71             SourceException.throwIf(ANYQUOTE_MATCHER.matchesAnyOf(str), ref,
72                 "YANG 1.1: unquoted string (%s) contains illegal characters", str);
73         }
74     };
75
76     private static final CharMatcher WHITESPACE_MATCHER = CharMatcher.whitespace();
77     private static final CharMatcher ANYQUOTE_MATCHER = CharMatcher.anyOf("'\"");
78     private static final Pattern ESCAPED_DQUOT = Pattern.compile("\\\"", Pattern.LITERAL);
79     private static final Pattern ESCAPED_BACKSLASH = Pattern.compile("\\\\", Pattern.LITERAL);
80     private static final Pattern ESCAPED_LF = Pattern.compile("\\n", Pattern.LITERAL);
81     private static final Pattern ESCAPED_TAB = Pattern.compile("\\t", Pattern.LITERAL);
82
83     static @NonNull ArgumentContextUtils forVersion(final YangVersion version) {
84         switch (version) {
85             case VERSION_1:
86                 return RFC6020;
87             case VERSION_1_1:
88                 return RFC7950;
89             default:
90                 throw new IllegalStateException("Unhandled version " + version);
91         }
92     }
93
94     /*
95      * NOTE: this method we do not use convenience methods provided by generated parser code, but instead are making
96      *       based on the grammar assumptions. While this is more verbose, it cuts out a number of unnecessary code,
97      *       such as intermediate List allocation et al.
98      */
99     final @NonNull String stringFromStringContext(final ArgumentContext context, final StatementSourceReference ref) {
100         // Get first child, which we fully expect to exist and be a lexer token
101         final ParseTree firstChild = context.getChild(0);
102         verify(firstChild instanceof TerminalNode, "Unexpected shape of %s", context);
103         final TerminalNode firstNode = (TerminalNode) firstChild;
104         final int firstType = firstNode.getSymbol().getType();
105         switch (firstType) {
106             case YangStatementParser.IDENTIFIER:
107                 // Simple case, there is a simple string, which cannot contain anything that we would need to process.
108                 return firstNode.getText();
109             case YangStatementParser.STRING:
110                 // Complex case, defer to a separate method
111                 return concatStrings(context, ref);
112             default:
113                 throw new VerifyException("Unexpected first symbol in " + context);
114         }
115     }
116
117     private String concatStrings(final ArgumentContext context, final StatementSourceReference ref) {
118         /*
119          * We have multiple fragments. Just search the tree. This code is equivalent to
120          *
121          *    context.STRING().forEach(stringNode -> appendString(sb, stringNode, ref))
122          *
123          * except we minimize allocations which that would do.
124          */
125         final StringBuilder sb = new StringBuilder();
126         for (ParseTree child : context.children) {
127             verify(child instanceof TerminalNode, "Unexpected fragment component %s", child);
128             final TerminalNode childNode = (TerminalNode) child;
129             switch (childNode.getSymbol().getType()) {
130                 case YangStatementParser.SEP:
131                     // Ignore whitespace
132                     break;
133                 case YangStatementParser.PLUS:
134                     // Operator, which we are handling by concat
135                     break;
136                 case YangStatementParser.STRING:
137                     // a lexer string, could be pretty much anything
138                     appendString(sb, childNode, ref);
139                     break;
140                 default:
141                     throw new VerifyException("Unexpected symbol in " + childNode);
142             }
143         }
144         return sb.toString();
145     }
146
147     private void appendString(final StringBuilder sb, final TerminalNode stringNode,
148             final StatementSourceReference ref) {
149
150         final String str = stringNode.getText();
151         final char firstChar = str.charAt(0);
152         final char lastChar = str.charAt(str.length() - 1);
153         // NOTE: Enforcement and transformation logic here should certainly be pushed down to the lexer, as ANTLR can
154         //       account the for it with lexer modes. One problem is that lexing here depends on version being lexed,
155         //       hence we really would have to re-parse the YANG file after determining its version. We certainly do not
156         //       want to do that.
157         // FIXME: YANGTOOLS-1079: but since we are performing quoting checks, perhaps at least that part could be lexed?
158         if (firstChar == '"' && lastChar == '"') {
159             final String innerStr = str.substring(1, str.length() - 1);
160             /*
161              * Unescape escaped double quotes, tabs, new line and backslash
162              * in the inner string and trim the result.
163              */
164             checkDoubleQuotedString(innerStr, ref);
165             sb.append(unescape(trimWhitespace(innerStr, stringNode.getSymbol().getCharPositionInLine())));
166         } else if (firstChar == '\'' && lastChar == '\'') {
167             /*
168              * According to RFC6020 a single quote character cannot occur in
169              * a single-quoted string, even when preceded by a backslash.
170              */
171             sb.append(str, 1, str.length() - 1);
172         } else {
173             checkUnquotedString(str, ref);
174             sb.append(str);
175         }
176     }
177
178     abstract void checkDoubleQuotedString(String str, StatementSourceReference ref);
179
180     abstract void checkUnquotedString(String str, StatementSourceReference ref);
181
182     private static String unescape(final String str) {
183         final int backslash = str.indexOf('\\');
184         if (backslash == -1) {
185             return str;
186         }
187
188         // FIXME: YANGTOOLS-1079: given we the leading backslash, it would be more efficient to walk the string and
189         //                        unescape in one go
190         return ESCAPED_TAB.matcher(
191                     ESCAPED_LF.matcher(
192                         ESCAPED_BACKSLASH.matcher(
193                             ESCAPED_DQUOT.matcher(str).replaceAll("\\\""))
194                         .replaceAll("\\\\"))
195                     .replaceAll("\\\n"))
196                .replaceAll("\\\t");
197     }
198
199     @VisibleForTesting
200     static String trimWhitespace(final String str, final int dquot) {
201         int brk = str.indexOf('\n');
202         if (brk == -1) {
203             // No need to trim whitespace
204             return str;
205         }
206
207         // Okay, we may need to do some trimming, set up a builder and append the first segment
208         final int length = str.length();
209         final StringBuilder sb = new StringBuilder(length);
210
211         // Append first segment, which needs only tail-trimming
212         sb.append(str, 0, trimTrailing(str, 0, brk)).append('\n');
213
214         // With that out of the way, setup our iteration state. The string segment we are looking at is
215         // str.substring(start, end), which is guaranteed not to include any line breaks, i.e. end <= brk unless we are
216         // at the last segment.
217         int start = brk + 1;
218         brk = str.indexOf('\n', start);
219
220         // Loop over inner strings
221         while (brk != -1) {
222             trimLeadingAndAppend(sb, dquot, str, start, trimTrailing(str, start, brk)).append('\n');
223             start = brk + 1;
224             brk = str.indexOf('\n', start);
225         }
226
227         return trimLeadingAndAppend(sb, dquot, str, start, length).toString();
228     }
229
230     private static StringBuilder trimLeadingAndAppend(final StringBuilder sb, final int dquot, final String str,
231             final int start, final int end) {
232         int offset = start;
233         int pos = 0;
234
235         while (pos <= dquot) {
236             if (offset == end) {
237                 // We ran out of data, nothing to append
238                 return sb;
239             }
240
241             final char ch = str.charAt(offset);
242             if (ch == '\t') {
243                 // tabs are to be treated as 8 spaces
244                 pos += 8;
245             } else if (WHITESPACE_MATCHER.matches(ch)) {
246                 pos++;
247             } else {
248                 break;
249             }
250
251             offset++;
252         }
253
254         // We have expanded beyond double quotes, push equivalent spaces
255         while (pos - 1 > dquot) {
256             sb.append(' ');
257             pos--;
258         }
259
260         return sb.append(str, offset, end);
261     }
262
263     private static int trimTrailing(final String str, final int start, final int end) {
264         int ret = end;
265         while (ret > start) {
266             final int prev = ret - 1;
267             if (!WHITESPACE_MATCHER.matches(str.charAt(prev))) {
268                 break;
269             }
270             ret = prev;
271         }
272         return ret;
273     }
274 }