YANGTOOLS-706: reorganize statement definitions
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / rfc6020 / Utils.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.stmt.rfc6020;
9
10 import static org.opendaylight.yangtools.yang.common.YangConstants.RFC6020_YANG_NAMESPACE;
11 import static org.opendaylight.yangtools.yang.common.YangConstants.YANG_XPATH_FUNCTIONS_PREFIX;
12
13 import com.google.common.base.CharMatcher;
14 import com.google.common.base.Splitter;
15 import com.google.common.collect.ImmutableBiMap;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Set;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
24 import javax.annotation.Nonnull;
25 import javax.annotation.Nullable;
26 import javax.annotation.RegEx;
27 import javax.xml.xpath.XPath;
28 import javax.xml.xpath.XPathExpressionException;
29 import javax.xml.xpath.XPathFactory;
30 import org.antlr.v4.runtime.tree.TerminalNode;
31 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.YangVersion;
34 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
35 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
36 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Relative;
37 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
40 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
41 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
42 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 public final class Utils {
47     private static final Logger LOG = LoggerFactory.getLogger(Utils.class);
48     private static final CharMatcher LEFT_PARENTHESIS_MATCHER = CharMatcher.is('(');
49     private static final CharMatcher RIGHT_PARENTHESIS_MATCHER = CharMatcher.is(')');
50     private static final CharMatcher AMPERSAND_MATCHER = CharMatcher.is('&');
51     private static final CharMatcher QUESTION_MARK_MATCHER = CharMatcher.is('?');
52     private static final CharMatcher ANYQUOTE_MATCHER = CharMatcher.anyOf("'\"");
53     private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings().trimResults();
54     private static final Splitter SPACE_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
55     private static final Splitter COLON_SPLITTER = Splitter.on(":").omitEmptyStrings().trimResults();
56     private static final Pattern PATH_ABS = Pattern.compile("/[^/].*");
57     @RegEx
58     private static final String YANG_XPATH_FUNCTIONS_STRING =
59             "(re-match|deref|derived-from(-or-self)?|enum-value|bit-is-set)([ \t\r\n]*)(\\()";
60     private static final Pattern YANG_XPATH_FUNCTIONS_PATTERN = Pattern.compile(YANG_XPATH_FUNCTIONS_STRING);
61     private static final Pattern ESCAPED_DQUOT = Pattern.compile("\\\"", Pattern.LITERAL);
62     private static final Pattern ESCAPED_BACKSLASH = Pattern.compile("\\\\", Pattern.LITERAL);
63     private static final Pattern ESCAPED_LF = Pattern.compile("\\n", Pattern.LITERAL);
64     private static final Pattern ESCAPED_TAB = Pattern.compile("\\t", Pattern.LITERAL);
65
66     private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>() {
67         @Override
68         protected XPathFactory initialValue() {
69             return XPathFactory.newInstance();
70         }
71     };
72
73     private Utils() {
74         throw new UnsupportedOperationException();
75     }
76
77     /**
78      * Cleanup any resources attached to the current thread. Threads interacting with this class can cause thread-local
79      * caches to them. Invoke this method if you want to detach those resources.
80      */
81     public static void detachFromCurrentThread() {
82         XPATH_FACTORY.remove();
83     }
84
85     public static Collection<SchemaNodeIdentifier.Relative> transformKeysStringToKeyNodes(
86             final StmtContext<?, ?, ?> ctx, final String value) {
87         final List<String> keyTokens = SPACE_SPLITTER.splitToList(value);
88
89         // to detect if key contains duplicates
90         if (new HashSet<>(keyTokens).size() < keyTokens.size()) {
91             // FIXME: report all duplicate keys
92             throw new SourceException(ctx.getStatementSourceReference(), "Duplicate value in list key: %s", value);
93         }
94
95         final Set<SchemaNodeIdentifier.Relative> keyNodes = new HashSet<>();
96
97         for (final String keyToken : keyTokens) {
98
99             final SchemaNodeIdentifier.Relative keyNode = (Relative) SchemaNodeIdentifier.Relative.create(false,
100                     StmtContextUtils.qnameFromArgument(ctx, keyToken));
101             keyNodes.add(keyNode);
102         }
103
104         return keyNodes;
105     }
106
107     private static String trimSingleLastSlashFromXPath(final String path) {
108         return path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
109     }
110
111     public static RevisionAwareXPath parseXPath(final StmtContext<?, ?, ?> ctx, final String path) {
112         final XPath xPath = XPATH_FACTORY.get().newXPath();
113         xPath.setNamespaceContext(StmtNamespaceContext.create(ctx,
114                 ImmutableBiMap.of(RFC6020_YANG_NAMESPACE.toString(), YANG_XPATH_FUNCTIONS_PREFIX)));
115
116         final String trimmed = trimSingleLastSlashFromXPath(path);
117         try {
118             // XPath extension functions have to be prefixed
119             // yang-specific XPath functions are in fact extended functions, therefore we have to add
120             // "yang" prefix to them so that they can be properly validated with the XPath.compile() method
121             // the "yang" prefix is bound to RFC6020 YANG namespace
122             final String prefixedXPath = addPrefixToYangXPathFunctions(trimmed, ctx);
123             // TODO: we could capture the result and expose its 'evaluate' method
124             xPath.compile(prefixedXPath);
125         } catch (final XPathExpressionException e) {
126             LOG.warn("Argument \"{}\" is not valid XPath string at \"{}\"", path, ctx.getStatementSourceReference(), e);
127         }
128
129         return new RevisionAwareXPathImpl(path, PATH_ABS.matcher(path).matches());
130     }
131
132     private static String addPrefixToYangXPathFunctions(final String path, final StmtContext<?, ?, ?> ctx) {
133         if (ctx.getRootVersion() == YangVersion.VERSION_1_1) {
134             // FIXME once Java 9 is available, change this to StringBuilder as Matcher.appendReplacement() and
135             // Matcher.appendTail() will accept StringBuilder parameter in Java 9
136             final StringBuffer result = new StringBuffer();
137             final String prefix = YANG_XPATH_FUNCTIONS_PREFIX + ":";
138             final Matcher matcher = YANG_XPATH_FUNCTIONS_PATTERN.matcher(path);
139             while (matcher.find()) {
140                 matcher.appendReplacement(result, prefix + matcher.group());
141             }
142
143             matcher.appendTail(result);
144             return result.toString();
145         }
146
147         return path;
148     }
149
150     public static QName trimPrefix(final QName identifier) {
151         final String prefixedLocalName = identifier.getLocalName();
152         final String[] namesParts = prefixedLocalName.split(":");
153
154         if (namesParts.length == 2) {
155             final String localName = namesParts[1];
156             return QName.create(identifier.getModule(), localName);
157         }
158
159         return identifier;
160     }
161
162     public static String trimPrefix(final String identifier) {
163         final List<String> namesParts = COLON_SPLITTER.splitToList(identifier);
164         if (namesParts.size() == 2) {
165             return namesParts.get(1);
166         }
167         return identifier;
168     }
169
170     @SuppressWarnings("checkstyle:illegalCatch")
171     public static SchemaNodeIdentifier nodeIdentifierFromPath(final StmtContext<?, ?, ?> ctx, final String path) {
172         // FIXME: is the path trimming really necessary??
173         final List<QName> qNames = new ArrayList<>();
174         for (final String nodeName : SLASH_SPLITTER.split(trimSingleLastSlashFromXPath(path))) {
175             try {
176                 final QName qName = StmtContextUtils.qnameFromArgument(ctx, nodeName);
177                 qNames.add(qName);
178             } catch (final RuntimeException e) {
179                 throw new SourceException(ctx.getStatementSourceReference(), e,
180                         "Failed to parse node '%s' in path '%s'", nodeName, path);
181             }
182         }
183
184         return SchemaNodeIdentifier.create(qNames, PATH_ABS.matcher(path).matches());
185     }
186
187     public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
188             final StatementSourceReference ref) {
189         return stringFromStringContext(context, YangVersion.VERSION_1, ref);
190     }
191
192     public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
193             final YangVersion yangVersion, final StatementSourceReference ref) {
194         final StringBuilder sb = new StringBuilder();
195         List<TerminalNode> strings = context.STRING();
196         if (strings.isEmpty()) {
197             strings = Collections.singletonList(context.IDENTIFIER());
198         }
199         for (final TerminalNode stringNode : strings) {
200             final String str = stringNode.getText();
201             final char firstChar = str.charAt(0);
202             final char lastChar = str.charAt(str.length() - 1);
203             if (firstChar == '"' && lastChar == '"') {
204                 final String innerStr = str.substring(1, str.length() - 1);
205                 /*
206                  * Unescape escaped double quotes, tabs, new line and backslash
207                  * in the inner string and trim the result.
208                  */
209                 checkDoubleQuotedString(innerStr, yangVersion, ref);
210                 sb.append(ESCAPED_TAB.matcher(
211                     ESCAPED_LF.matcher(
212                         ESCAPED_BACKSLASH.matcher(
213                             ESCAPED_DQUOT.matcher(innerStr).replaceAll("\\\""))
214                         .replaceAll("\\\\"))
215                     .replaceAll("\\\n"))
216                     .replaceAll("\\\t"));
217             } else if (firstChar == '\'' && lastChar == '\'') {
218                 /*
219                  * According to RFC6020 a single quote character cannot occur in
220                  * a single-quoted string, even when preceded by a backslash.
221                  */
222                 sb.append(str.substring(1, str.length() - 1));
223             } else {
224                 checkUnquotedString(str, yangVersion, ref);
225                 sb.append(str);
226             }
227         }
228         return sb.toString();
229     }
230
231     private static void checkUnquotedString(final String str, final YangVersion yangVersion,
232             final StatementSourceReference ref) {
233         if (yangVersion == YangVersion.VERSION_1_1) {
234             SourceException.throwIf(ANYQUOTE_MATCHER.matchesAnyOf(str), ref,
235                 "YANG 1.1: unquoted string (%s) contains illegal characters", str);
236         }
237     }
238
239     private static void checkDoubleQuotedString(final String str, final YangVersion yangVersion,
240             final StatementSourceReference ref) {
241         if (yangVersion == YangVersion.VERSION_1_1) {
242             for (int i = 0; i < str.length() - 1; i++) {
243                 if (str.charAt(i) == '\\') {
244                     switch (str.charAt(i + 1)) {
245                         case 'n':
246                         case 't':
247                         case '\\':
248                         case '\"':
249                             i++;
250                             break;
251                         default:
252                             throw new SourceException(ref, "YANG 1.1: illegal double quoted string (%s). In double "
253                                     + "quoted string the backslash must be followed by one of the following character "
254                                     + "[n,t,\",\\], but was '%s'.", str, str.charAt(i + 1));
255                     }
256                 }
257             }
258         }
259     }
260
261     @Nullable
262     public static StatementContextBase<?, ?, ?> findNode(final StmtContext<?, ?, ?> rootStmtCtx,
263             final SchemaNodeIdentifier node) {
264         return (StatementContextBase<?, ?, ?>) rootStmtCtx.getFromNamespace(SchemaNodeIdentifierBuildNamespace.class,
265             node);
266     }
267
268     public static @Nonnull Boolean parseBoolean(final StmtContext<?, ?, ?> ctx, final String input) {
269         if ("true".equals(input)) {
270             return Boolean.TRUE;
271         } else if ("false".equals(input)) {
272             return Boolean.FALSE;
273         } else {
274             throw new SourceException(ctx.getStatementSourceReference(),
275                 "Invalid '%s' statement %s '%s', it can be either 'true' or 'false'",
276                 ctx.getPublicDefinition().getStatementName(), ctx.getPublicDefinition().getArgumentName(), input);
277         }
278     }
279
280     public static String internBoolean(final String input) {
281         if ("true".equals(input)) {
282             return "true";
283         } else if ("false".equals(input)) {
284             return "false";
285         } else {
286             return input;
287         }
288     }
289
290     /**
291      * Replaces illegal characters of QName by the name of the character (e.g. '?' is replaced by "QuestionMark" etc.).
292      *
293      * @param string
294      *            input String
295      * @return result String
296      */
297     public static String replaceIllegalCharsForQName(String string) {
298         string = LEFT_PARENTHESIS_MATCHER.replaceFrom(string, "LeftParenthesis");
299         string = RIGHT_PARENTHESIS_MATCHER.replaceFrom(string, "RightParenthesis");
300         string = AMPERSAND_MATCHER.replaceFrom(string, "Ampersand");
301         string = QUESTION_MARK_MATCHER.replaceFrom(string, "QuestionMark");
302
303         return string;
304     }
305
306     public static boolean belongsToTheSameModule(final QName targetStmtQName, final QName sourceStmtQName) {
307         return targetStmtQName.getModule().equals(sourceStmtQName.getModule());
308     }
309 }