Merge branch 'master' of ../controller
[yangtools.git] / yang / yang-model-export / src / main / java / org / opendaylight / yangtools / yang / model / export / YangTextSnippetIterator.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o. 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.model.export;
9
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;
13
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;
23 import java.util.Map;
24 import java.util.Optional;
25 import java.util.Queue;
26 import java.util.Set;
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;
35
36 /**
37  * This is an iterator over strings needed to assemble a YANG snippet.
38  *
39  * @author Robert Varga
40  */
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);
58
59     /*
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.
65      */
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")
76             .build();
77
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];
81
82     static {
83         for (int i = 0; i < INDENT_STRINGS_SIZE; i++) {
84             INDENT_STRINGS[i] = INDENT.repeat(i).intern();
85         }
86     }
87
88     private enum Quoting {
89         /**
90          * No quoting necessary.
91          */
92         NONE,
93         /**
94          * Argument is empty, quote an empty string.
95          */
96         EMPTY,
97         /**
98          * Quote on the same line.
99          */
100         SIMPLE,
101         /**
102          * Quote starting on next line.
103          */
104         MULTILINE;
105     }
106
107     /*
108      * We normally have up to 10 strings:
109      *               <indent>
110      *               <prefix>
111      *               ":"
112      *               <name>
113      *               " \n"
114      *               <indent>
115      *               "\""
116      *               <argument>
117      *               "\""
118      *               ";\n"
119      *
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
123      *
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
126      */
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;
133
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));
140     }
141
142     @Override
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) {
147             return nextString;
148         }
149
150         final Iterator<? extends DeclaredStatement<?>> it = stack.peek();
151         if (it == null) {
152             endOfData();
153             // Post-end of data, the user will never see this
154             return "";
155         }
156
157         // Try to push next child
158         while (it.hasNext()) {
159             if (pushStatement(it.next())) {
160                 return strings.remove();
161             }
162         }
163
164         // End of children, close the parent statement
165         stack.pop();
166         addIndent();
167         strings.add("}\n");
168         return strings.remove();
169     }
170
171     /**
172      * Push a statement to the stack. A successfully-pushed statement results in strings not being empty.
173      *
174      * @param stmt Statement to push into strings
175      * @return True if the statement was pushed. False if the statement was suppressed.
176      */
177     private boolean pushStatement(final DeclaredStatement<?> stmt) {
178         final StatementDefinition def = stmt.statementDefinition();
179         if (ignoredStatements.contains(def)) {
180             return false;
181         }
182
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())) {
189                 return false;
190             }
191         }
192
193         // New statement: push indent
194         addIndent();
195
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());
201             strings.add(":");
202         }
203         strings.add(stmtName.getLocalName());
204
205         // Add argument, quoted and properly indented if need be
206         addArgument(def, stmt.rawArgument());
207
208         if (!children.isEmpty()) {
209             // Open the statement and push child iterator
210             strings.add(" {\n");
211             stack.push(children.iterator());
212         } else {
213             // Close the statement
214             strings.add(";\n");
215         }
216
217         return true;
218     }
219
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;
225         }
226         if (depth > 0) {
227             strings.add(INDENT_STRINGS[depth]);
228         }
229     }
230
231     private void addArgument(final StatementDefinition def, final @Nullable String arg) {
232         if (arg == null) {
233             // No argument, nothing to do
234             return;
235         }
236
237         switch (quoteKind(def, arg)) {
238             case EMPTY:
239                 strings.add(" \"\"");
240                 break;
241             case NONE:
242                 strings.add(" ");
243                 strings.add(arg);
244                 break;
245             case SIMPLE:
246                 strings.add(" \"");
247                 strings.add(DQUOT_MATCHER.replaceFrom(arg, "\\\""));
248                 strings.add("\"");
249                 break;
250             case MULTILINE:
251                 strings.add("\n");
252                 addIndent();
253                 strings.add(INDENT + '\"');
254
255                 final Iterator<String> it = NEWLINE_SPLITTER.split(DQUOT_MATCHER.replaceFrom(arg, "\\\"")).iterator();
256                 final String first = it.next();
257                 if (!first.isEmpty()) {
258                     strings.add(first);
259                 }
260
261                 while (it.hasNext()) {
262                     strings.add("\n");
263                     final String str = it.next();
264                     if (!str.isEmpty()) {
265                         addIndent();
266                         strings.add(INDENT + ' ');
267                         strings.add(str);
268                     }
269                 }
270                 strings.add("\"");
271                 break;
272             default:
273                 throw new IllegalStateException("Illegal quoting for " + def + " argument \"" + arg + "\"");
274         }
275     }
276
277     private static Quoting quoteKind(final StatementDefinition def, final String str) {
278         if (str.isEmpty()) {
279             return Quoting.EMPTY;
280         }
281         if (QUOTE_MULTILINE_STATEMENTS.contains(def) || str.indexOf('\n') != -1) {
282             return Quoting.MULTILINE;
283         }
284         if (NEED_QUOTE_MATCHER.matchesAnyOf(str) || str.contains("//") || str.contains("/*") || str.contains("*/")) {
285             return Quoting.SIMPLE;
286         }
287
288         return Quoting.NONE;
289     }
290 }