Clean various constructs
[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 com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.CharMatcher;
12 import java.util.Collections;
13 import java.util.List;
14 import java.util.regex.Pattern;
15 import org.antlr.v4.runtime.tree.TerminalNode;
16 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser.ArgumentContext;
17 import org.opendaylight.yangtools.yang.common.YangVersion;
18 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
19 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
20
21 final class ArgumentContextUtils {
22     private static final CharMatcher WHITESPACE_MATCHER = CharMatcher.whitespace();
23     private static final CharMatcher ANYQUOTE_MATCHER = CharMatcher.anyOf("'\"");
24     private static final Pattern ESCAPED_DQUOT = Pattern.compile("\\\"", Pattern.LITERAL);
25     private static final Pattern ESCAPED_BACKSLASH = Pattern.compile("\\\\", Pattern.LITERAL);
26     private static final Pattern ESCAPED_LF = Pattern.compile("\\n", Pattern.LITERAL);
27     private static final Pattern ESCAPED_TAB = Pattern.compile("\\t", Pattern.LITERAL);
28
29     private ArgumentContextUtils() {
30         throw new UnsupportedOperationException();
31     }
32
33     static String stringFromStringContext(final ArgumentContext context, final YangVersion yangVersion,
34             final StatementSourceReference ref) {
35         final StringBuilder sb = new StringBuilder();
36         List<TerminalNode> strings = context.STRING();
37         if (strings.isEmpty()) {
38             strings = Collections.singletonList(context.IDENTIFIER());
39         }
40         for (final TerminalNode stringNode : strings) {
41             final String str = stringNode.getText();
42             final char firstChar = str.charAt(0);
43             final char lastChar = str.charAt(str.length() - 1);
44             if (firstChar == '"' && lastChar == '"') {
45                 final String innerStr = str.substring(1, str.length() - 1);
46                 /*
47                  * Unescape escaped double quotes, tabs, new line and backslash
48                  * in the inner string and trim the result.
49                  */
50                 checkDoubleQuotedString(innerStr, yangVersion, ref);
51
52                 sb.append(ESCAPED_TAB.matcher(
53                     ESCAPED_LF.matcher(
54                         ESCAPED_BACKSLASH.matcher(
55                             ESCAPED_DQUOT.matcher(
56                                 trimWhitespace(innerStr, stringNode.getSymbol().getCharPositionInLine()))
57                             .replaceAll("\\\""))
58                         .replaceAll("\\\\"))
59                     .replaceAll("\\\n"))
60                     .replaceAll("\\\t"));
61             } else if (firstChar == '\'' && lastChar == '\'') {
62                 /*
63                  * According to RFC6020 a single quote character cannot occur in
64                  * a single-quoted string, even when preceded by a backslash.
65                  */
66                 sb.append(str, 1, str.length() - 1);
67             } else {
68                 checkUnquotedString(str, yangVersion, ref);
69                 sb.append(str);
70             }
71         }
72         return sb.toString();
73     }
74
75     private static void checkUnquotedString(final String str, final YangVersion yangVersion,
76             final StatementSourceReference ref) {
77         if (yangVersion == YangVersion.VERSION_1_1) {
78             SourceException.throwIf(ANYQUOTE_MATCHER.matchesAnyOf(str), ref,
79                 "YANG 1.1: unquoted string (%s) contains illegal characters", str);
80         }
81     }
82
83     private static void checkDoubleQuotedString(final String str, final YangVersion yangVersion,
84             final StatementSourceReference ref) {
85         if (yangVersion == YangVersion.VERSION_1_1) {
86             for (int i = 0; i < str.length() - 1; i++) {
87                 if (str.charAt(i) == '\\') {
88                     switch (str.charAt(i + 1)) {
89                         case 'n':
90                         case 't':
91                         case '\\':
92                         case '\"':
93                             i++;
94                             break;
95                         default:
96                             throw new SourceException(ref, "YANG 1.1: illegal double quoted string (%s). In double "
97                                     + "quoted string the backslash must be followed by one of the following character "
98                                     + "[n,t,\",\\], but was '%s'.", str, str.charAt(i + 1));
99                     }
100                 }
101             }
102         }
103     }
104
105     @VisibleForTesting
106     static String trimWhitespace(final String str, final int dquot) {
107         int brk = str.indexOf('\n');
108         if (brk == -1) {
109             // No need to trim whitespace
110             return str;
111         }
112
113         // Okay, we may need to do some trimming, set up a builder and append the first segment
114         final int length = str.length();
115         final StringBuilder sb = new StringBuilder(length);
116
117         // Append first segment, which needs only tail-trimming
118         sb.append(str, 0, trimTrailing(str, 0, brk)).append('\n');
119
120         // With that out of the way, setup our iteration state. The string segment we are looking at is
121         // str.substring(start, end), which is guaranteed not to include any line breaks, i.e. end <= brk unless we are
122         // at the last segment.
123         int start = brk + 1;
124         brk = str.indexOf('\n', start);
125
126         // Loop over inner strings
127         while (brk != -1) {
128             final int end = brk != -1 ? brk : length;
129             trimLeadingAndAppend(sb, dquot, str, start, trimTrailing(str, start, end)).append('\n');
130             start = end + 1;
131             brk = str.indexOf('\n', start);
132         }
133
134         return trimLeadingAndAppend(sb, dquot, str, start, length).toString();
135     }
136
137     private static StringBuilder trimLeadingAndAppend(final StringBuilder sb, final int dquot, final String str,
138             final int start, final int end) {
139         int offset = start;
140         int pos = 0;
141
142         while (pos <= dquot) {
143             if (offset == end) {
144                 // We ran out of data, nothing to append
145                 return sb;
146             }
147
148             final char ch = str.charAt(offset);
149             if (ch == '\t') {
150                 // tabs are to be treated as 8 spaces
151                 pos += 8;
152             } else if (WHITESPACE_MATCHER.matches(ch)) {
153                 pos++;
154             } else {
155                 break;
156             }
157
158             offset++;
159         }
160
161         // We have expanded beyond double quotes, push equivalent spaces
162         while (pos - 1 > dquot) {
163             sb.append(' ');
164             pos--;
165         }
166
167         return sb.append(str, offset, end);
168     }
169
170     private static int trimTrailing(final String str, final int start, final int end) {
171         int ret = end;
172         while (ret > start) {
173             final int prev = ret - 1;
174             if (!WHITESPACE_MATCHER.matches(str.charAt(prev))) {
175                 break;
176             }
177             ret = prev;
178         }
179         return ret;
180     }
181 }