2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.model.export;
10 import static java.util.Objects.requireNonNull;
11 import static org.eclipse.jdt.annotation.DefaultLocation.PARAMETER;
12 import static org.eclipse.jdt.annotation.DefaultLocation.RETURN_TYPE;
14 import com.google.common.base.CharMatcher;
15 import com.google.common.base.Splitter;
16 import com.google.common.collect.AbstractIterator;
17 import com.google.common.collect.ImmutableMap;
18 import com.google.common.collect.ImmutableSet;
19 import java.util.ArrayDeque;
20 import java.util.Collection;
21 import java.util.Deque;
22 import java.util.Iterator;
24 import java.util.Optional;
25 import java.util.Queue;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.common.QNameModule;
32 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
33 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
34 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
37 * This is an iterator over strings needed to assemble a YANG snippet.
39 * @author Robert Varga
41 @NonNullByDefault({ PARAMETER, RETURN_TYPE })
42 final class YangTextSnippetIterator extends AbstractIterator<@NonNull String> {
43 // https://tools.ietf.org/html/rfc7950#section-6.1.3
44 // An unquoted string is any sequence of characters that does not
45 // contain any space, tab, carriage return, or line feed characters, a
46 // single or double quote character, a semicolon (";"), braces ("{" or
47 // "}"), or comment sequences ("//", "/*", or "*/").
48 // Newline is treated separately, so it is not included here
49 private static final CharMatcher NEED_QUOTE_MATCHER = CharMatcher.anyOf(" \t\r'\";{}");
50 private static final CharMatcher DQUOT_MATCHER = CharMatcher.is('"');
51 private static final Splitter NEWLINE_SPLITTER = Splitter.on('\n');
52 private static final ImmutableSet<StatementDefinition> QUOTE_MULTILINE_STATEMENTS = ImmutableSet.of(
53 YangStmtMapping.CONTACT,
54 YangStmtMapping.DESCRIPTION,
55 YangStmtMapping.ERROR_MESSAGE,
56 YangStmtMapping.ORGANIZATION,
57 YangStmtMapping.REFERENCE);
60 * https://tools.ietf.org/html/rfc6087#section-4.3:
61 * In general, it is suggested that substatements containing very common
62 * default values SHOULD NOT be present. The following substatements
63 * are commonly used with the default value, which would make the module
64 * difficult to read if used everywhere they are allowed.
66 private static final ImmutableMap<StatementDefinition, String> DEFAULT_STATEMENTS =
67 ImmutableMap.<StatementDefinition, String>builder()
68 .put(YangStmtMapping.CONFIG, "true")
69 .put(YangStmtMapping.MANDATORY, "true")
70 .put(YangStmtMapping.MAX_ELEMENTS, "unbounded")
71 .put(YangStmtMapping.MIN_ELEMENTS, "0")
72 .put(YangStmtMapping.ORDERED_BY, "system")
73 .put(YangStmtMapping.REQUIRE_INSTANCE, "true")
74 .put(YangStmtMapping.STATUS, "current")
75 .put(YangStmtMapping.YIN_ELEMENT, "false")
78 private static final String INDENT = " ";
79 private static final int INDENT_STRINGS_SIZE = 16;
80 private static final String[] INDENT_STRINGS = new String[INDENT_STRINGS_SIZE];
83 for (int i = 0; i < INDENT_STRINGS_SIZE; i++) {
84 INDENT_STRINGS[i] = INDENT.repeat(i).intern();
88 private enum Quoting {
90 * No quoting necessary.
94 * Argument is empty, quote an empty string.
98 * Quote on the same line.
102 * Quote starting on next line.
108 * We normally have up to 10 strings:
120 * But all of this is typically not used:
121 * - statements usually do not have a prefix, saving two items
122 * - arguments are not typically quoted, saving another two
124 * In case we get into a multi-line argument, we are already splitting strings, so the cost of growing
125 * the queue is negligible
127 private final Queue<String> strings = new ArrayDeque<>(8);
128 // Let's be modest, 16-level deep constructs are not exactly common.
129 private final Deque<Iterator<? extends DeclaredStatement<?>>> stack = new ArrayDeque<>(8);
130 private final Map<QNameModule, @NonNull String> namespaces;
131 private final Set<StatementDefinition> ignoredStatements;
132 private final boolean omitDefaultStatements;
134 YangTextSnippetIterator(final DeclaredStatement<?> stmt, final Map<QNameModule, @NonNull String> namespaces,
135 final Set<StatementDefinition> ignoredStatements, final boolean omitDefaultStatements) {
136 this.namespaces = requireNonNull(namespaces);
137 this.ignoredStatements = requireNonNull(ignoredStatements);
138 this.omitDefaultStatements = omitDefaultStatements;
139 pushStatement(requireNonNull(stmt));
143 protected @NonNull String computeNext() {
144 // We may have some strings stashed, take one out, if that is the case
145 final String nextString = strings.poll();
146 if (nextString != null) {
150 final Iterator<? extends DeclaredStatement<?>> it = stack.peek();
153 // Post-end of data, the user will never see this
157 // Try to push next child
158 while (it.hasNext()) {
159 if (pushStatement(it.next())) {
160 return strings.remove();
164 // End of children, close the parent statement
168 return strings.remove();
172 * Push a statement to the stack. A successfully-pushed statement results in strings not being empty.
174 * @param stmt Statement to push into strings
175 * @return True if the statement was pushed. False if the statement was suppressed.
177 private boolean pushStatement(final DeclaredStatement<?> stmt) {
178 final StatementDefinition def = stmt.statementDefinition();
179 if (ignoredStatements.contains(def)) {
183 final Collection<? extends DeclaredStatement<?>> children = stmt.declaredSubstatements();
184 if (omitDefaultStatements && children.isEmpty()) {
185 // This statement does not have substatements, check if its value matches the declared default, like
186 // "config true", "mandatory false", etc.
187 final String suppressValue = DEFAULT_STATEMENTS.get(def);
188 if (suppressValue != null && suppressValue.equals(stmt.rawArgument())) {
193 // New statement: push indent
196 // Add statement prefixed with namespace if needed
197 final QName stmtName = def.getStatementName();
198 final Optional<String> prefix = ExportUtils.statementPrefix(namespaces, stmtName);
199 if (prefix.isPresent()) {
200 strings.add(prefix.get());
203 strings.add(stmtName.getLocalName());
205 // Add argument, quoted and properly indented if need be
206 addArgument(def, stmt.rawArgument());
208 if (!children.isEmpty()) {
209 // Open the statement and push child iterator
211 stack.push(children.iterator());
213 // Close the statement
220 private void addIndent() {
221 int depth = stack.size();
222 while (depth >= INDENT_STRINGS_SIZE) {
223 strings.add(INDENT_STRINGS[INDENT_STRINGS_SIZE - 1]);
224 depth -= INDENT_STRINGS_SIZE;
227 strings.add(INDENT_STRINGS[depth]);
231 private void addArgument(final StatementDefinition def, final @Nullable String arg) {
233 // No argument, nothing to do
237 switch (quoteKind(def, arg)) {
239 strings.add(" \"\"");
247 strings.add(DQUOT_MATCHER.replaceFrom(arg, "\\\""));
253 strings.add(INDENT + '\"');
255 final Iterator<String> it = NEWLINE_SPLITTER.split(DQUOT_MATCHER.replaceFrom(arg, "\\\"")).iterator();
256 final String first = it.next();
257 if (!first.isEmpty()) {
261 while (it.hasNext()) {
263 final String str = it.next();
264 if (!str.isEmpty()) {
266 strings.add(INDENT + ' ');
273 throw new IllegalStateException("Illegal quoting for " + def + " argument \"" + arg + "\"");
277 private static Quoting quoteKind(final StatementDefinition def, final String str) {
279 return Quoting.EMPTY;
281 if (QUOTE_MULTILINE_STATEMENTS.contains(def) || str.indexOf('\n') != -1) {
282 return Quoting.MULTILINE;
284 if (NEED_QUOTE_MATCHER.matchesAnyOf(str) || str.contains("//") || str.contains("/*") || str.contains("*/")) {
285 return Quoting.SIMPLE;