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