Move DeviateKind parsing
[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 import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.firstAttributeOf;
13
14 import com.google.common.base.CharMatcher;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Splitter;
17 import com.google.common.base.Strings;
18 import com.google.common.collect.ImmutableBiMap;
19 import com.google.common.collect.ImmutableSet;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Date;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.Set;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30 import javax.annotation.Nullable;
31 import javax.annotation.RegEx;
32 import javax.xml.xpath.XPath;
33 import javax.xml.xpath.XPathExpressionException;
34 import javax.xml.xpath.XPathFactory;
35 import org.antlr.v4.runtime.tree.TerminalNode;
36 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.common.QNameModule;
39 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
40 import org.opendaylight.yangtools.yang.common.YangVersion;
41 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
42 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
43 import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
44 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
45 import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
46 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
47 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Relative;
48 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
49 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
50 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
51 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.QNameCacheNamespace;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
57 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
58 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
59 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
60 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
61 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
62 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
63 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
64 import org.opendaylight.yangtools.yang.parser.stmt.reactor.RootStatementContext;
65 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 public final class Utils {
70     private static final Logger LOG = LoggerFactory.getLogger(Utils.class);
71     private static final CharMatcher LEFT_PARENTHESIS_MATCHER = CharMatcher.is('(');
72     private static final CharMatcher RIGHT_PARENTHESIS_MATCHER = CharMatcher.is(')');
73     private static final CharMatcher AMPERSAND_MATCHER = CharMatcher.is('&');
74     private static final CharMatcher QUESTION_MARK_MATCHER = CharMatcher.is('?');
75     private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings().trimResults();
76     private static final Splitter SPACE_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
77     private static final Splitter COLON_SPLITTER = Splitter.on(":").omitEmptyStrings().trimResults();
78     private static final Pattern PATH_ABS = Pattern.compile("/[^/].*");
79     @RegEx
80     private static final String YANG_XPATH_FUNCTIONS_STRING =
81             "(re-match|deref|derived-from(-or-self)?|enum-value|bit-is-set)(\\()";
82     private static final Pattern YANG_XPATH_FUNCTIONS_PATTERN = Pattern.compile(YANG_XPATH_FUNCTIONS_STRING);
83
84     private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>() {
85         @Override
86         protected XPathFactory initialValue() {
87             return XPathFactory.newInstance();
88         }
89     };
90
91     private Utils() {
92         throw new UnsupportedOperationException();
93     }
94
95     /**
96      * Cleanup any resources attached to the current thread. Threads interacting with this class can cause thread-local
97      * caches to them. Invoke this method if you want to detach those resources.
98      */
99     public static void detachFromCurrentThread() {
100         XPATH_FACTORY.remove();
101     }
102
103     public static Collection<SchemaNodeIdentifier.Relative> transformKeysStringToKeyNodes(final StmtContext<?, ?, ?> ctx,
104             final String value) {
105         final List<String> keyTokens = SPACE_SPLITTER.splitToList(value);
106
107         // to detect if key contains duplicates
108         if (new HashSet<>(keyTokens).size() < keyTokens.size()) {
109             // FIXME: report all duplicate keys
110             throw new SourceException(ctx.getStatementSourceReference(), "Duplicate value in list key: %s", value);
111         }
112
113         final Set<SchemaNodeIdentifier.Relative> keyNodes = new HashSet<>();
114
115         for (final String keyToken : keyTokens) {
116
117             final SchemaNodeIdentifier.Relative keyNode = (Relative) SchemaNodeIdentifier.Relative.create(false,
118                     Utils.qNameFromArgument(ctx, keyToken));
119             keyNodes.add(keyNode);
120         }
121
122         return keyNodes;
123     }
124
125     static Collection<SchemaNodeIdentifier.Relative> parseUniqueConstraintArgument(final StmtContext<?, ?, ?> ctx,
126             final String argumentValue) {
127         final Set<SchemaNodeIdentifier.Relative> uniqueConstraintNodes = new HashSet<>();
128         for (final String uniqueArgToken : SPACE_SPLITTER.split(argumentValue)) {
129             final SchemaNodeIdentifier nodeIdentifier = Utils.nodeIdentifierFromPath(ctx, uniqueArgToken);
130             SourceException.throwIf(nodeIdentifier.isAbsolute(), ctx.getStatementSourceReference(),
131                     "Unique statement argument '%s' contains schema node identifier '%s' "
132                             + "which is not in the descendant node identifier form.", argumentValue, uniqueArgToken);
133             uniqueConstraintNodes.add((SchemaNodeIdentifier.Relative) nodeIdentifier);
134         }
135         return ImmutableSet.copyOf(uniqueConstraintNodes);
136     }
137
138     private static String trimSingleLastSlashFromXPath(final String path) {
139         return path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
140     }
141
142     static RevisionAwareXPath parseXPath(final StmtContext<?, ?, ?> ctx, final String path) {
143         final XPath xPath = XPATH_FACTORY.get().newXPath();
144         xPath.setNamespaceContext(StmtNamespaceContext.create(ctx,
145                 ImmutableBiMap.of(RFC6020_YANG_NAMESPACE.toString(), YANG_XPATH_FUNCTIONS_PREFIX)));
146
147         final String trimmed = trimSingleLastSlashFromXPath(path);
148         try {
149             // XPath extension functions have to be prefixed
150             // yang-specific XPath functions are in fact extended functions, therefore we have to add
151             // "yang" prefix to them so that they can be properly validated with the XPath.compile() method
152             // the "yang" prefix is bound to RFC6020 YANG namespace
153             final String prefixedXPath = addPrefixToYangXPathFunctions(trimmed, ctx);
154             // TODO: we could capture the result and expose its 'evaluate' method
155             xPath.compile(prefixedXPath);
156         } catch (final XPathExpressionException e) {
157             LOG.warn("Argument \"{}\" is not valid XPath string at \"{}\"", path, ctx.getStatementSourceReference(), e);
158         }
159
160         return new RevisionAwareXPathImpl(path, PATH_ABS.matcher(path).matches());
161     }
162
163     private static String addPrefixToYangXPathFunctions(final String path, final StmtContext<?, ?, ?> ctx) {
164         if (ctx.getRootVersion() == YangVersion.VERSION_1_1) {
165             // FIXME once Java 9 is available, change this to StringBuilder as Matcher.appendReplacement() and
166             // Matcher.appendTail() will accept StringBuilder parameter in Java 9
167             final StringBuffer result = new StringBuffer();
168             final String prefix = YANG_XPATH_FUNCTIONS_PREFIX + ":";
169             final Matcher matcher = YANG_XPATH_FUNCTIONS_PATTERN.matcher(path);
170             while (matcher.find()) {
171                 matcher.appendReplacement(result, prefix + matcher.group());
172             }
173
174             matcher.appendTail(result);
175             return result.toString();
176         }
177
178         return path;
179     }
180
181     public static QName trimPrefix(final QName identifier) {
182         final String prefixedLocalName = identifier.getLocalName();
183         final String[] namesParts = prefixedLocalName.split(":");
184
185         if (namesParts.length == 2) {
186             final String localName = namesParts[1];
187             return QName.create(identifier.getModule(), localName);
188         }
189
190         return identifier;
191     }
192
193     public static String trimPrefix(final String identifier) {
194         final List<String> namesParts = COLON_SPLITTER.splitToList(identifier);
195         if (namesParts.size() == 2) {
196             return namesParts.get(1);
197         }
198         return identifier;
199     }
200
201     static SchemaNodeIdentifier nodeIdentifierFromPath(final StmtContext<?, ?, ?> ctx, final String path) {
202         // FIXME: is the path trimming really necessary??
203         final List<QName> qNames = new ArrayList<>();
204         for (final String nodeName : SLASH_SPLITTER.split(trimSingleLastSlashFromXPath(path))) {
205             try {
206                 final QName qName = Utils.qNameFromArgument(ctx, nodeName);
207                 qNames.add(qName);
208             } catch (final RuntimeException e) {
209                 throw new SourceException(ctx.getStatementSourceReference(), e,
210                         "Failed to parse node '%s' in path '%s'", nodeName, path);
211             }
212         }
213
214         return SchemaNodeIdentifier.create(qNames, PATH_ABS.matcher(path).matches());
215     }
216
217     public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
218             final StatementSourceReference ref) {
219         return stringFromStringContext(context, YangVersion.VERSION_1, ref);
220     }
221
222     public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
223             final YangVersion yangVersion, final StatementSourceReference ref) {
224         final StringBuilder sb = new StringBuilder();
225         List<TerminalNode> strings = context.STRING();
226         if (strings.isEmpty()) {
227             strings = Collections.singletonList(context.IDENTIFIER());
228         }
229         for (final TerminalNode stringNode : strings) {
230             final String str = stringNode.getText();
231             final char firstChar = str.charAt(0);
232             final char lastChar = str.charAt(str.length() - 1);
233             if (firstChar == '"' && lastChar == '"') {
234                 final String innerStr = str.substring(1, str.length() - 1);
235                 /*
236                  * Unescape escaped double quotes, tabs, new line and backslash
237                  * in the inner string and trim the result.
238                  */
239                 checkDoubleQuotedString(innerStr, yangVersion, ref);
240                 sb.append(innerStr.replace("\\\"", "\"").replace("\\\\", "\\").replace("\\n", "\n")
241                         .replace("\\t", "\t"));
242             } else if (firstChar == '\'' && lastChar == '\'') {
243                 /*
244                  * According to RFC6020 a single quote character cannot occur in
245                  * a single-quoted string, even when preceded by a backslash.
246                  */
247                 sb.append(str.substring(1, str.length() - 1));
248             } else {
249                 checkUnquotedString(str, yangVersion, ref);
250                 sb.append(str);
251             }
252         }
253         return sb.toString();
254     }
255
256     private static void checkUnquotedString(final String str, final YangVersion yangVersion,
257             final StatementSourceReference ref) {
258         if (yangVersion == YangVersion.VERSION_1_1) {
259             for (int i = 0; i < str.length(); i++) {
260                 switch (str.charAt(i)) {
261                 case '"':
262                 case '\'':
263                     throw new SourceException(ref, "Yang 1.1: unquoted string (%s) contains illegal characters", str);
264                 }
265             }
266         }
267     }
268
269     private static void checkDoubleQuotedString(final String str, final YangVersion yangVersion,
270             final StatementSourceReference ref) {
271         if (yangVersion == YangVersion.VERSION_1_1) {
272             for (int i = 0; i < str.length() - 1; i++) {
273                 if (str.charAt(i) == '\\') {
274                     switch (str.charAt(i + 1)) {
275                     case 'n':
276                     case 't':
277                     case '\\':
278                     case '\"':
279                         i++;
280                         break;
281                     default:
282                         throw new SourceException(ref,
283                                 "Yang 1.1: illegal double quoted string (%s). In double quoted string the backslash must be followed "
284                                         + "by one of the following character [n,t,\",\\], but was '%s'.", str,
285                                 str.charAt(i + 1));
286                     }
287                 }
288             }
289         }
290     }
291
292     public static QName qNameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
293         if (Strings.isNullOrEmpty(value)) {
294             return ctx.getPublicDefinition().getStatementName();
295         }
296
297         String prefix;
298         QNameModule qNameModule = null;
299         String localName = null;
300
301         final String[] namesParts = value.split(":");
302         switch (namesParts.length) {
303         case 1:
304             localName = namesParts[0];
305             qNameModule = getRootModuleQName(ctx);
306             break;
307         default:
308             prefix = namesParts[0];
309             localName = namesParts[1];
310             qNameModule = getModuleQNameByPrefix(ctx, prefix);
311             // in case of unknown statement argument, we're not going to parse it
312             if (qNameModule == null
313                     && ctx.getPublicDefinition().getDeclaredRepresentationClass()
314                     .isAssignableFrom(UnknownStatementImpl.class)) {
315                 localName = value;
316                 qNameModule = getRootModuleQName(ctx);
317             }
318             if (qNameModule == null
319                     && ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
320                 ctx = ctx.getOriginalCtx();
321                 qNameModule = getModuleQNameByPrefix(ctx, prefix);
322             }
323             break;
324         }
325
326         qNameModule = InferenceException.throwIfNull(qNameModule, ctx.getStatementSourceReference(),
327             "Cannot resolve QNameModule for '%s'", value);
328
329         final QNameModule resultQNameModule;
330         if (qNameModule.getRevision() == null) {
331             resultQNameModule = QNameModule.create(qNameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV)
332                 .intern();
333         } else {
334             resultQNameModule = qNameModule;
335         }
336
337         return ctx.getFromNamespace(QNameCacheNamespace.class, QName.create(resultQNameModule, localName));
338     }
339
340     public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
341         final ModuleIdentifier modId = ctx.getRoot().getFromNamespace(ImpPrefixToModuleIdentifier.class, prefix);
342         final QNameModule qNameModule = ctx.getFromNamespace(ModuleIdentifierToModuleQName.class, modId);
343
344         if (qNameModule == null && StmtContextUtils.producesDeclared(ctx.getRoot(), SubmoduleStatement.class)) {
345             final String moduleName = ctx.getRoot().getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
346             return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
347         }
348         return qNameModule;
349     }
350
351     public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
352         if (ctx == null) {
353             return null;
354         }
355
356         final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
357         final QNameModule qNameModule;
358
359         if (StmtContextUtils.producesDeclared(rootCtx, ModuleStatement.class)) {
360             qNameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
361         } else if (StmtContextUtils.producesDeclared(rootCtx, SubmoduleStatement.class)) {
362             final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
363                 BelongsToStatement.class);
364             qNameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
365         } else {
366             qNameModule = null;
367         }
368
369         Preconditions.checkArgument(qNameModule != null, "Failed to look up root QNameModule for %s", ctx);
370         if (qNameModule.getRevision() != null) {
371             return qNameModule;
372         }
373
374         return QNameModule.create(qNameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV).intern();
375     }
376
377     @Nullable
378     public static StatementContextBase<?, ?, ?> findNode(final StmtContext<?, ?, ?> rootStmtCtx,
379             final SchemaNodeIdentifier node) {
380         return (StatementContextBase<?, ?, ?>) rootStmtCtx.getFromNamespace(SchemaNodeIdentifierBuildNamespace.class, node);
381     }
382
383     public static boolean isUnknownNode(final StmtContext<?, ?, ?> stmtCtx) {
384         return stmtCtx != null && stmtCtx.getPublicDefinition().getDeclaredRepresentationClass()
385                 .isAssignableFrom(UnknownStatementImpl.class);
386     }
387
388     static String internBoolean(final String input) {
389         if ("true".equals(input)) {
390             return "true";
391         } else if ("false".equals(input)) {
392             return "false";
393         } else {
394             return input;
395         }
396     }
397
398     public static Date getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
399         Date revision = null;
400         for (final StmtContext<?, ?, ?> subStmt : subStmts) {
401             if (subStmt.getPublicDefinition().getDeclaredRepresentationClass().isAssignableFrom(RevisionStatement
402                     .class)) {
403                 if (revision == null && subStmt.getStatementArgument() != null) {
404                     revision = (Date) subStmt.getStatementArgument();
405                 } else if (subStmt.getStatementArgument() != null && ((Date) subStmt.getStatementArgument()).compareTo
406                         (revision) > 0) {
407                     revision = (Date) subStmt.getStatementArgument();
408                 }
409             }
410         }
411         return revision;
412     }
413
414     /**
415      * Replaces illegal characters of QName by the name of the character (e.g.
416      * '?' is replaced by "QuestionMark" etc.).
417      *
418      * @param string
419      *            input String
420      * @return result String
421      */
422     public static String replaceIllegalCharsForQName(String string) {
423         string = LEFT_PARENTHESIS_MATCHER.replaceFrom(string, "LeftParenthesis");
424         string = RIGHT_PARENTHESIS_MATCHER.replaceFrom(string, "RightParenthesis");
425         string = AMPERSAND_MATCHER.replaceFrom(string, "Ampersand");
426         string = QUESTION_MARK_MATCHER.replaceFrom(string, "QuestionMark");
427
428         return string;
429     }
430
431     public static boolean belongsToTheSameModule(final QName targetStmtQName, final QName sourceStmtQName) {
432         return targetStmtQName.getModule().equals(sourceStmtQName.getModule());
433     }
434
435     public static SourceIdentifier createSourceIdentifier(final RootStatementContext<?, ?, ?> root) {
436         final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
437         if (qNameModule != null) {
438             // creates SourceIdentifier for a module
439             return RevisionSourceIdentifier.create((String) root.getStatementArgument(),
440                 qNameModule.getFormattedRevision());
441         }
442
443         // creates SourceIdentifier for a submodule
444         final Date revision = Optional.ofNullable(Utils.getLatestRevision(root.declaredSubstatements()))
445                 .orElse(SimpleDateFormatUtil.DEFAULT_DATE_REV);
446         final String formattedRevision = SimpleDateFormatUtil.getRevisionFormat().format(revision);
447         return RevisionSourceIdentifier.create((String) root.getStatementArgument(), formattedRevision);
448     }
449 }