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