018c46451b24310fd046d1d070948dae46d95447
[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.Collections;
18 import java.util.List;
19 import java.util.regex.Matcher;
20 import java.util.regex.Pattern;
21 import javax.annotation.Nonnull;
22 import javax.annotation.Nullable;
23 import javax.annotation.RegEx;
24 import javax.xml.xpath.XPath;
25 import javax.xml.xpath.XPathExpressionException;
26 import javax.xml.xpath.XPathFactory;
27 import org.antlr.v4.runtime.tree.TerminalNode;
28 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.common.YangVersion;
31 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
33 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
36 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
37 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
38 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public final class Utils {
43     private static final Logger LOG = LoggerFactory.getLogger(Utils.class);
44     private static final CharMatcher ANYQUOTE_MATCHER = CharMatcher.anyOf("'\"");
45     private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings().trimResults();
46     private static final Pattern PATH_ABS = Pattern.compile("/[^/].*");
47     @RegEx
48     private static final String YANG_XPATH_FUNCTIONS_STRING =
49             "(re-match|deref|derived-from(-or-self)?|enum-value|bit-is-set)([ \t\r\n]*)(\\()";
50     private static final Pattern YANG_XPATH_FUNCTIONS_PATTERN = Pattern.compile(YANG_XPATH_FUNCTIONS_STRING);
51     private static final Pattern ESCAPED_DQUOT = Pattern.compile("\\\"", Pattern.LITERAL);
52     private static final Pattern ESCAPED_BACKSLASH = Pattern.compile("\\\\", Pattern.LITERAL);
53     private static final Pattern ESCAPED_LF = Pattern.compile("\\n", Pattern.LITERAL);
54     private static final Pattern ESCAPED_TAB = Pattern.compile("\\t", Pattern.LITERAL);
55
56     private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>() {
57         @Override
58         protected XPathFactory initialValue() {
59             return XPathFactory.newInstance();
60         }
61     };
62
63     private Utils() {
64         throw new UnsupportedOperationException();
65     }
66
67     /**
68      * Cleanup any resources attached to the current thread. Threads interacting with this class can cause thread-local
69      * caches to them. Invoke this method if you want to detach those resources.
70      */
71     public static void detachFromCurrentThread() {
72         XPATH_FACTORY.remove();
73     }
74
75     private static String trimSingleLastSlashFromXPath(final String path) {
76         return path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
77     }
78
79     public static RevisionAwareXPath parseXPath(final StmtContext<?, ?, ?> ctx, final String path) {
80         final XPath xPath = XPATH_FACTORY.get().newXPath();
81         xPath.setNamespaceContext(StmtNamespaceContext.create(ctx,
82                 ImmutableBiMap.of(RFC6020_YANG_NAMESPACE.toString(), YANG_XPATH_FUNCTIONS_PREFIX)));
83
84         final String trimmed = trimSingleLastSlashFromXPath(path);
85         try {
86             // XPath extension functions have to be prefixed
87             // yang-specific XPath functions are in fact extended functions, therefore we have to add
88             // "yang" prefix to them so that they can be properly validated with the XPath.compile() method
89             // the "yang" prefix is bound to RFC6020 YANG namespace
90             final String prefixedXPath = addPrefixToYangXPathFunctions(trimmed, ctx);
91             // TODO: we could capture the result and expose its 'evaluate' method
92             xPath.compile(prefixedXPath);
93         } catch (final XPathExpressionException e) {
94             LOG.warn("Argument \"{}\" is not valid XPath string at \"{}\"", path, ctx.getStatementSourceReference(), e);
95         }
96
97         return new RevisionAwareXPathImpl(path, PATH_ABS.matcher(path).matches());
98     }
99
100     private static String addPrefixToYangXPathFunctions(final String path, final StmtContext<?, ?, ?> ctx) {
101         if (ctx.getRootVersion() == YangVersion.VERSION_1_1) {
102             // FIXME once Java 9 is available, change this to StringBuilder as Matcher.appendReplacement() and
103             // Matcher.appendTail() will accept StringBuilder parameter in Java 9
104             final StringBuffer result = new StringBuffer();
105             final String prefix = YANG_XPATH_FUNCTIONS_PREFIX + ":";
106             final Matcher matcher = YANG_XPATH_FUNCTIONS_PATTERN.matcher(path);
107             while (matcher.find()) {
108                 matcher.appendReplacement(result, prefix + matcher.group());
109             }
110
111             matcher.appendTail(result);
112             return result.toString();
113         }
114
115         return path;
116     }
117
118     @SuppressWarnings("checkstyle:illegalCatch")
119     public static SchemaNodeIdentifier nodeIdentifierFromPath(final StmtContext<?, ?, ?> ctx, final String path) {
120         // FIXME: is the path trimming really necessary??
121         final List<QName> qNames = new ArrayList<>();
122         for (final String nodeName : SLASH_SPLITTER.split(trimSingleLastSlashFromXPath(path))) {
123             try {
124                 final QName qName = StmtContextUtils.qnameFromArgument(ctx, nodeName);
125                 qNames.add(qName);
126             } catch (final RuntimeException e) {
127                 throw new SourceException(ctx.getStatementSourceReference(), e,
128                         "Failed to parse node '%s' in path '%s'", nodeName, path);
129             }
130         }
131
132         return SchemaNodeIdentifier.create(qNames, PATH_ABS.matcher(path).matches());
133     }
134
135     public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
136             final StatementSourceReference ref) {
137         return stringFromStringContext(context, YangVersion.VERSION_1, ref);
138     }
139
140     public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
141             final YangVersion yangVersion, final StatementSourceReference ref) {
142         final StringBuilder sb = new StringBuilder();
143         List<TerminalNode> strings = context.STRING();
144         if (strings.isEmpty()) {
145             strings = Collections.singletonList(context.IDENTIFIER());
146         }
147         for (final TerminalNode stringNode : strings) {
148             final String str = stringNode.getText();
149             final char firstChar = str.charAt(0);
150             final char lastChar = str.charAt(str.length() - 1);
151             if (firstChar == '"' && lastChar == '"') {
152                 final String innerStr = str.substring(1, str.length() - 1);
153                 /*
154                  * Unescape escaped double quotes, tabs, new line and backslash
155                  * in the inner string and trim the result.
156                  */
157                 checkDoubleQuotedString(innerStr, yangVersion, ref);
158                 sb.append(ESCAPED_TAB.matcher(
159                     ESCAPED_LF.matcher(
160                         ESCAPED_BACKSLASH.matcher(
161                             ESCAPED_DQUOT.matcher(innerStr).replaceAll("\\\""))
162                         .replaceAll("\\\\"))
163                     .replaceAll("\\\n"))
164                     .replaceAll("\\\t"));
165             } else if (firstChar == '\'' && lastChar == '\'') {
166                 /*
167                  * According to RFC6020 a single quote character cannot occur in
168                  * a single-quoted string, even when preceded by a backslash.
169                  */
170                 sb.append(str.substring(1, str.length() - 1));
171             } else {
172                 checkUnquotedString(str, yangVersion, ref);
173                 sb.append(str);
174             }
175         }
176         return sb.toString();
177     }
178
179     private static void checkUnquotedString(final String str, final YangVersion yangVersion,
180             final StatementSourceReference ref) {
181         if (yangVersion == YangVersion.VERSION_1_1) {
182             SourceException.throwIf(ANYQUOTE_MATCHER.matchesAnyOf(str), ref,
183                 "YANG 1.1: unquoted string (%s) contains illegal characters", str);
184         }
185     }
186
187     private static void checkDoubleQuotedString(final String str, final YangVersion yangVersion,
188             final StatementSourceReference ref) {
189         if (yangVersion == YangVersion.VERSION_1_1) {
190             for (int i = 0; i < str.length() - 1; i++) {
191                 if (str.charAt(i) == '\\') {
192                     switch (str.charAt(i + 1)) {
193                         case 'n':
194                         case 't':
195                         case '\\':
196                         case '\"':
197                             i++;
198                             break;
199                         default:
200                             throw new SourceException(ref, "YANG 1.1: illegal double quoted string (%s). In double "
201                                     + "quoted string the backslash must be followed by one of the following character "
202                                     + "[n,t,\",\\], but was '%s'.", str, str.charAt(i + 1));
203                     }
204                 }
205             }
206         }
207     }
208
209     @Nullable
210     public static StatementContextBase<?, ?, ?> findNode(final StmtContext<?, ?, ?> rootStmtCtx,
211             final SchemaNodeIdentifier node) {
212         return (StatementContextBase<?, ?, ?>) rootStmtCtx.getFromNamespace(SchemaNodeIdentifierBuildNamespace.class,
213             node);
214     }
215
216     public static @Nonnull Boolean parseBoolean(final StmtContext<?, ?, ?> ctx, final String input) {
217         if ("true".equals(input)) {
218             return Boolean.TRUE;
219         } else if ("false".equals(input)) {
220             return Boolean.FALSE;
221         } else {
222             throw new SourceException(ctx.getStatementSourceReference(),
223                 "Invalid '%s' statement %s '%s', it can be either 'true' or 'false'",
224                 ctx.getPublicDefinition().getStatementName(), ctx.getPublicDefinition().getArgumentName(), input);
225         }
226     }
227
228     public static String internBoolean(final String input) {
229         if ("true".equals(input)) {
230             return "true";
231         } else if ("false".equals(input)) {
232             return "false";
233         } else {
234             return input;
235         }
236     }
237 }