Introduce moduleQName for sharing
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / impl / ParserListenerUtils.java
1 /*
2  * Copyright (c) 2013 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/eplv10.html
7  */
8 package org.opendaylight.yangtools.yang.parser.impl;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import com.google.common.base.CharMatcher;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Splitter;
15 import com.google.common.collect.Lists;
16
17 import java.math.BigDecimal;
18 import java.math.BigInteger;
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.Iterator;
22 import java.util.List;
23
24 import org.antlr.v4.runtime.ParserRuleContext;
25 import org.antlr.v4.runtime.tree.ParseTree;
26 import org.antlr.v4.runtime.tree.TerminalNode;
27 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
28 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
29 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Base_stmtContext;
30 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bit_stmtContext;
31 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bits_specificationContext;
32 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Config_argContext;
33 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Config_stmtContext;
34 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Decimal64_specificationContext;
35 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Default_stmtContext;
36 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Description_stmtContext;
37 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Enum_specificationContext;
38 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Enum_stmtContext;
39 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Error_app_tag_stmtContext;
40 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Error_message_stmtContext;
41 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Fraction_digits_stmtContext;
42 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Identityref_specificationContext;
43 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Instance_identifier_specificationContext;
44 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Key_stmtContext;
45 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Leafref_specificationContext;
46 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Length_stmtContext;
47 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Mandatory_argContext;
48 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Mandatory_stmtContext;
49 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Max_elements_stmtContext;
50 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Max_value_argContext;
51 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Min_elements_stmtContext;
52 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Min_value_argContext;
53 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_stmtContext;
54 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Must_stmtContext;
55 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Numerical_restrictionsContext;
56 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_argContext;
57 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_stmtContext;
58 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Path_stmtContext;
59 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Pattern_stmtContext;
60 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Position_stmtContext;
61 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Presence_stmtContext;
62 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Range_stmtContext;
63 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Reference_stmtContext;
64 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_anyxml_stmtsContext;
65 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_choice_stmtsContext;
66 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_container_stmtsContext;
67 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_leaf_list_stmtsContext;
68 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_leaf_stmtsContext;
69 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_list_stmtsContext;
70 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_pomContext;
71 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Refine_stmtContext;
72 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Require_instance_argContext;
73 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Require_instance_stmtContext;
74 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_argContext;
75 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_stmtContext;
76 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.StringContext;
77 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.String_restrictionsContext;
78 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Type_body_stmtsContext;
79 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Units_stmtContext;
80 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Value_stmtContext;
81 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.When_stmtContext;
82 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_argContext;
83 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_stmtContext;
84 import org.opendaylight.yangtools.yang.common.QName;
85 import org.opendaylight.yangtools.yang.model.api.MustDefinition;
86 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
87 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
88 import org.opendaylight.yangtools.yang.model.api.Status;
89 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
90 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
92 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
93 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
94 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
95 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
96 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
97 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
98 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
99 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
100 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
101 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
102 import org.opendaylight.yangtools.yang.model.util.BaseConstraints;
103 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
104 import org.opendaylight.yangtools.yang.model.util.BinaryType;
105 import org.opendaylight.yangtools.yang.model.util.BitImpl;
106 import org.opendaylight.yangtools.yang.model.util.BitsType;
107 import org.opendaylight.yangtools.yang.model.util.Decimal64;
108 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
109 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
110 import org.opendaylight.yangtools.yang.model.util.InstanceIdentifier;
111 import org.opendaylight.yangtools.yang.model.util.Int16;
112 import org.opendaylight.yangtools.yang.model.util.Int32;
113 import org.opendaylight.yangtools.yang.model.util.Int64;
114 import org.opendaylight.yangtools.yang.model.util.Int8;
115 import org.opendaylight.yangtools.yang.model.util.Leafref;
116 import org.opendaylight.yangtools.yang.model.util.MustDefinitionImpl;
117 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
118 import org.opendaylight.yangtools.yang.model.util.StringType;
119 import org.opendaylight.yangtools.yang.model.util.Uint16;
120 import org.opendaylight.yangtools.yang.model.util.Uint32;
121 import org.opendaylight.yangtools.yang.model.util.Uint64;
122 import org.opendaylight.yangtools.yang.model.util.Uint8;
123 import org.opendaylight.yangtools.yang.model.util.UnknownType;
124 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
125 import org.opendaylight.yangtools.yang.parser.builder.api.ConstraintsBuilder;
126 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
127 import org.opendaylight.yangtools.yang.parser.builder.api.RefineBuilder;
128 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
129 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
130 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceCaseBuilder;
131 import org.opendaylight.yangtools.yang.parser.builder.impl.RefineHolderImpl;
132 import org.opendaylight.yangtools.yang.parser.builder.impl.UnionTypeBuilder;
133 import org.opendaylight.yangtools.yang.parser.util.TypeConstraints;
134 import org.opendaylight.yangtools.yang.parser.util.UnknownBoundaryNumber;
135 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
136 import org.slf4j.Logger;
137 import org.slf4j.LoggerFactory;
138
139 public final class ParserListenerUtils {
140     private static final Logger LOG = LoggerFactory.getLogger(ParserListenerUtils.class);
141     private static final Splitter KEYDEF_SPLITTER = Splitter.on(' ').omitEmptyStrings();
142     private static final Splitter PIPE_SPLITTER = Splitter.on('|').trimResults();
143     private static final Splitter DOT_DOT_SPLITTER = Splitter.on("..").trimResults();
144     private static final CharMatcher QUOTE_MATCHER = CharMatcher.is('"');
145
146     private ParserListenerUtils() {
147     }
148
149     /**
150      * Parse given tree and get first string value.
151      *
152      * @param treeNode
153      *            tree to parse
154      * @return first string value from given tree
155      */
156     public static String stringFromNode(final ParseTree treeNode) {
157         String result = "";
158         for (int i = 0; i < treeNode.getChildCount(); ++i) {
159             final ParseTree child = treeNode.getChild(i);
160             if (child instanceof StringContext) {
161                 return stringFromStringContext((StringContext)child);
162             }
163         }
164         return result;
165     }
166
167     private static String stringFromStringContext(final StringContext context) {
168         StringBuilder sb = new StringBuilder();
169         for (TerminalNode stringNode : context.STRING()) {
170             final String str = stringNode.getText();
171             final int i = str.indexOf('"');
172
173             if (i == -1) {
174                 sb.append(str);
175                 continue;
176             }
177
178             /*
179              * The string contains quotes, so we have to tread carefully.
180              *
181              * FIXME: I think this code is broken, but proving that requires
182              *        making sense of the parser/lexer and how they tie into
183              *        this method. Especially what format 'str' can have and
184              *        how we need to handle it. The original check was:
185              *
186              *        if (!(result.startsWith("\"")) && result.endsWith("\""))
187              *
188              *        Looking at the parentheses it is hard to justify the
189              *        pair right after negation -- the intent may have been
190              *        to negate the entire expression.
191              */
192             if (i != 0 && str.endsWith("\"")) {
193                 LOG.error("Syntax error in module {} at line {}: missing '\"'.", getParentModule(context),
194                         context.getStart().getLine());
195             } else {
196                 sb.append(QUOTE_MATCHER.removeFrom(str));
197             }
198         }
199         return sb.toString();
200     }
201
202     private static String getParentModule(final ParseTree ctx) {
203         ParseTree current = ctx;
204         while (current != null && !(current instanceof Module_stmtContext)) {
205             current = current.getParent();
206         }
207         if (current != null) {
208             Module_stmtContext module = (Module_stmtContext) current;
209             for (int i = 0; i < module.getChildCount(); i++) {
210                 if (module.getChild(i) instanceof StringContext) {
211                     final StringContext str = (StringContext) module.getChild(i);
212                     return str.getChild(0).getText();
213                 }
214             }
215         }
216         return "";
217     }
218
219     /**
220      * Parse 'description', 'reference' and 'status' statements and fill in
221      * given builder.
222      *
223      * @param ctx
224      *            context to parse
225      * @param builder
226      *            builder to fill in with parsed statements
227      */
228     public static void parseSchemaNodeArgs(final ParseTree ctx, final SchemaNodeBuilder builder) {
229         for (int i = 0; i < ctx.getChildCount(); i++) {
230             final ParseTree child = ctx.getChild(i);
231             if (child instanceof Description_stmtContext) {
232                 final String desc = stringFromNode(child);
233                 builder.setDescription(desc);
234             } else if (child instanceof Reference_stmtContext) {
235                 final String ref = stringFromNode(child);
236                 builder.setReference(ref);
237             } else if (child instanceof Status_stmtContext) {
238                 final Status status = parseStatus((Status_stmtContext) child);
239                 builder.setStatus(status);
240             }
241         }
242     }
243
244     /**
245      * Parse given context and return its value;
246      *
247      * @param ctx
248      *            status context
249      * @return value parsed from context
250      */
251     public static Status parseStatus(final Status_stmtContext ctx) {
252         Status result = null;
253         for (int i = 0; i < ctx.getChildCount(); i++) {
254             ParseTree statusArg = ctx.getChild(i);
255             if (statusArg instanceof Status_argContext) {
256                 String statusArgStr = stringFromNode(statusArg);
257                 switch (statusArgStr) {
258                 case "current":
259                     result = Status.CURRENT;
260                     break;
261                 case "deprecated":
262                     result = Status.DEPRECATED;
263                     break;
264                 case "obsolete":
265                     result = Status.OBSOLETE;
266                     break;
267                 default:
268                     LOG.warn("Invalid 'status' statement: " + statusArgStr);
269                 }
270             }
271         }
272         return result;
273     }
274
275     /**
276      * Parse given tree and returns units statement as string.
277      *
278      * @param ctx
279      *            context to parse
280      * @return value of units statement as string or null if there is no units
281      *         statement
282      */
283     public static String parseUnits(final ParseTree ctx) {
284         for (int i = 0; i < ctx.getChildCount(); i++) {
285             ParseTree child = ctx.getChild(i);
286             if (child instanceof Units_stmtContext) {
287                 return stringFromNode(child);
288             }
289         }
290         return null;
291     }
292
293     /**
294      * Parse given tree and returns default statement as string.
295      *
296      * @param ctx
297      *            context to parse
298      * @return value of default statement as string or null if there is no
299      *         default statement
300      */
301     public static String parseDefault(final ParseTree ctx) {
302         for (int i = 0; i < ctx.getChildCount(); i++) {
303             ParseTree child = ctx.getChild(i);
304             if (child instanceof Default_stmtContext) {
305                 return stringFromNode(child);
306             }
307         }
308         return null;
309     }
310
311     /**
312      * Create java.util.List of key node names.
313      *
314      * @param ctx
315      *            Key_stmtContext context
316      * @return YANG list key as java.util.List of key node names
317      */
318     public static List<String> createListKey(final Key_stmtContext ctx) {
319         String keyDefinition = stringFromNode(ctx);
320         return Lists.newArrayList(KEYDEF_SPLITTER.split(keyDefinition));
321     }
322
323     /**
324      * Parse given type body of enumeration statement.
325      *
326      * @param ctx
327      *            type body context to parse
328      * @param path
329      *            actual position in YANG model
330      * @param moduleName
331      *            current module name
332      * @return List of EnumPair object parsed from given context
333      */
334     private static List<EnumTypeDefinition.EnumPair> getEnumConstants(final Type_body_stmtsContext ctx,
335             final SchemaPath path, final String moduleName) {
336         List<EnumTypeDefinition.EnumPair> enumConstants = new ArrayList<>();
337
338         for (int i = 0; i < ctx.getChildCount(); i++) {
339             ParseTree enumSpecChild = ctx.getChild(i);
340             if (enumSpecChild instanceof Enum_specificationContext) {
341                 int highestValue = -1;
342                 for (int j = 0; j < enumSpecChild.getChildCount(); j++) {
343                     ParseTree enumChild = enumSpecChild.getChild(j);
344                     if (enumChild instanceof Enum_stmtContext) {
345                         EnumPair enumPair = createEnumPair((Enum_stmtContext) enumChild, highestValue, path, moduleName);
346                         if (enumPair.getValue() > highestValue) {
347                             highestValue = enumPair.getValue();
348                         }
349                         enumConstants.add(enumPair);
350                     }
351                 }
352             }
353         }
354         return enumConstants;
355     }
356
357     /**
358      * Parse enum statement context
359      *
360      * @param ctx
361      *            enum statement context
362      * @param highestValue
363      *            current highest value in enumeration
364      * @param actualPath
365      *            actual position in YANG model
366      * @param moduleName
367      *            current module name
368      * @return EnumPair object parsed from given context
369      */
370     private static EnumTypeDefinition.EnumPair createEnumPair(final Enum_stmtContext ctx, final int highestValue,
371             final SchemaPath actualPath, final String moduleName) {
372         final String name = stringFromNode(ctx);
373         SchemaPath path = createTypePath(actualPath, name);
374         Integer value = null;
375
376         String description = null;
377         String reference = null;
378         Status status = null;
379
380         for (int i = 0; i < ctx.getChildCount(); i++) {
381             ParseTree child = ctx.getChild(i);
382             if (child instanceof Value_stmtContext) {
383                 String valueStr = stringFromNode(child);
384                 value = Integer.valueOf(valueStr);
385             } else if (child instanceof Description_stmtContext) {
386                 description = stringFromNode(child);
387             } else if (child instanceof Reference_stmtContext) {
388                 reference = stringFromNode(child);
389             } else if (child instanceof Status_stmtContext) {
390                 status = parseStatus((Status_stmtContext) child);
391             }
392         }
393
394         if (value == null) {
395             value = highestValue + 1;
396         }
397         if (value < -2147483648 || value > 2147483647) {
398             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on enum '" + name
399                     + "': the enum value MUST be in the range from -2147483648 to 2147483647, but was: " + value);
400         }
401
402         EnumPairImpl result = new EnumPairImpl();
403         result.qname = path.getPathTowardsRoot().iterator().next();
404         result.path = path;
405         result.description = description;
406         result.reference = reference;
407         result.status = status;
408         result.name = name;
409         result.value = value;
410         return result;
411     }
412
413     /**
414      * Internal implementation of EnumPair.
415      */
416     private static class EnumPairImpl implements EnumTypeDefinition.EnumPair {
417         private QName qname;
418         private SchemaPath path;
419         private String description;
420         private String reference;
421         private Status status;
422         private final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
423         private String name;
424         private Integer value;
425
426         @Override
427         public QName getQName() {
428             return qname;
429         }
430
431         @Override
432         public SchemaPath getPath() {
433             return path;
434         }
435
436         @Override
437         public String getDescription() {
438             return description;
439         }
440
441         @Override
442         public String getReference() {
443             return reference;
444         }
445
446         @Override
447         public Status getStatus() {
448             return status;
449         }
450
451         @Override
452         public List<UnknownSchemaNode> getUnknownSchemaNodes() {
453             return unknownNodes;
454         }
455
456         @Override
457         public String getName() {
458             return name;
459         }
460
461         @Override
462         public Integer getValue() {
463             return value;
464         }
465
466         @Override
467         public int hashCode() {
468             final int prime = 31;
469             int result = 1;
470             result = prime * result + ((qname == null) ? 0 : qname.hashCode());
471             result = prime * result + ((path == null) ? 0 : path.hashCode());
472             result = prime * result + ((unknownNodes == null) ? 0 : unknownNodes.hashCode());
473             result = prime * result + ((name == null) ? 0 : name.hashCode());
474             result = prime * result + ((value == null) ? 0 : value.hashCode());
475             return result;
476         }
477
478         @Override
479         public boolean equals(final Object obj) {
480             if (this == obj) {
481                 return true;
482             }
483             if (obj == null) {
484                 return false;
485             }
486             if (getClass() != obj.getClass()) {
487                 return false;
488             }
489             EnumPairImpl other = (EnumPairImpl) obj;
490             if (qname == null) {
491                 if (other.qname != null) {
492                     return false;
493                 }
494             } else if (!qname.equals(other.qname)) {
495                 return false;
496             }
497             if (path == null) {
498                 if (other.path != null) {
499                     return false;
500                 }
501             } else if (!path.equals(other.path)) {
502                 return false;
503             }
504             if (unknownNodes == null) {
505                 if (other.unknownNodes != null) {
506                     return false;
507                 }
508             } else if (!unknownNodes.equals(other.unknownNodes)) {
509                 return false;
510             }
511             if (name == null) {
512                 if (other.name != null) {
513                     return false;
514                 }
515             } else if (!name.equals(other.name)) {
516                 return false;
517             }
518             if (value == null) {
519                 if (other.value != null) {
520                     return false;
521                 }
522             } else if (!value.equals(other.value)) {
523                 return false;
524             }
525             return true;
526         }
527
528         @Override
529         public String toString() {
530             return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name=" + name + ", value=" + value + "]";
531         }
532     }
533
534     /**
535      * Get and parse range from given type body context.
536      *
537      * @param ctx
538      *            type body context to parse
539      * @param moduleName
540      *            name of current module
541      * @return List of RangeConstraint created from this context
542      */
543     private static List<RangeConstraint> getRangeConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
544         for (int i = 0; i < ctx.getChildCount(); i++) {
545             ParseTree numRestrChild = ctx.getChild(i);
546
547             if (numRestrChild instanceof Numerical_restrictionsContext) {
548                 for (int j = 0; j < numRestrChild.getChildCount(); j++) {
549                     ParseTree rangeChild = numRestrChild.getChild(j);
550                     if (rangeChild instanceof Range_stmtContext) {
551                         return parseRangeConstraints((Range_stmtContext) rangeChild, moduleName);
552                     }
553                 }
554             }
555
556             if (numRestrChild instanceof Decimal64_specificationContext) {
557                 for (int j = 0; j < numRestrChild.getChildCount(); j++) {
558                     ParseTree decRestr = numRestrChild.getChild(j);
559                     if (decRestr instanceof Numerical_restrictionsContext) {
560                         for (int k = 0; k < decRestr.getChildCount(); k++) {
561                             ParseTree rangeChild = decRestr.getChild(k);
562                             if (rangeChild instanceof Range_stmtContext) {
563                                 return parseRangeConstraints((Range_stmtContext) rangeChild, moduleName);
564                             }
565                         }
566                     }
567                 }
568             }
569         }
570         return Collections.emptyList();
571     }
572
573     /**
574      * Parse given range context.
575      *
576      * @param ctx
577      *            range context to parse
578      * @param moduleName
579      *            name of current module
580      * @return List of RangeConstraints parsed from this context
581      */
582     private static List<RangeConstraint> parseRangeConstraints(final Range_stmtContext ctx, final String moduleName) {
583         final int line = ctx.getStart().getLine();
584         Optional<String> description = Optional.absent();
585         Optional<String> reference = Optional.absent();
586
587         for (int i = 0; i < ctx.getChildCount(); i++) {
588             ParseTree child = ctx.getChild(i);
589             if (child instanceof Description_stmtContext) {
590                 description = Optional.fromNullable(stringFromNode(child));
591             } else if (child instanceof Reference_stmtContext) {
592                 reference = Optional.fromNullable(stringFromNode(child));
593             }
594         }
595
596         List<RangeConstraint> rangeConstraints = new ArrayList<>();
597         for (String def : PIPE_SPLITTER.split(stringFromNode(ctx))) {
598             final Iterator<String> split = DOT_DOT_SPLITTER.split(def).iterator();
599             final Number min = parseNumberConstraintValue(split.next(), moduleName, line);
600
601             final Number max;
602             if (split.hasNext()) {
603                 max = parseNumberConstraintValue(split.next(), moduleName, line);
604                 if (split.hasNext()) {
605                     throw new YangParseException(moduleName, ctx.getStart().getLine(), "Malformed length constraint \"" + def + "\".");
606                 }
607             } else {
608                 max = min;
609             }
610
611             RangeConstraint range = BaseConstraints.newRangeConstraint(min, max, description, reference);
612             rangeConstraints.add(range);
613         }
614
615         return rangeConstraints;
616     }
617
618     /**
619      * Get and parse length from given type body context.
620      *
621      * @param ctx
622      *            type body context to parse
623      * @param moduleName
624      *            name of current module
625      * @return List of LengthConstraint created from this context
626      */
627     private static List<LengthConstraint> getLengthConstraints(final Type_body_stmtsContext ctx, final String moduleName) {
628         for (int i = 0; i < ctx.getChildCount(); i++) {
629             ParseTree stringRestrChild = ctx.getChild(i);
630             if (stringRestrChild instanceof String_restrictionsContext) {
631                 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
632                     ParseTree lengthChild = stringRestrChild.getChild(j);
633                     if (lengthChild instanceof Length_stmtContext) {
634                         return parseLengthConstraints((Length_stmtContext) lengthChild, moduleName);
635                     }
636                 }
637             }
638         }
639         return Collections.emptyList();
640     }
641
642     /**
643      * Parse given length context.
644      *
645      * @param ctx
646      *            length context to parse
647      * @param moduleName
648      *            name of current module
649      * @return List of LengthConstraints parsed from this context
650      */
651     private static List<LengthConstraint> parseLengthConstraints(final Length_stmtContext ctx, final String moduleName) {
652         final int line = ctx.getStart().getLine();
653         Optional<String> description = Optional.absent();
654         Optional<String> reference = Optional.absent();
655
656         for (int i = 0; i < ctx.getChildCount(); i++) {
657             ParseTree child = ctx.getChild(i);
658             if (child instanceof Description_stmtContext) {
659                 description = Optional.fromNullable(stringFromNode(child));
660             } else if (child instanceof Reference_stmtContext) {
661                 reference = Optional.fromNullable(stringFromNode(child));
662             }
663         }
664
665         List<LengthConstraint> lengthConstraints = new ArrayList<>();
666         for (String def : PIPE_SPLITTER.split(stringFromNode(ctx))) {
667             final Iterator<String> split = DOT_DOT_SPLITTER.split(def).iterator();
668             final Number min = parseNumberConstraintValue(split.next(), moduleName, line);
669
670             final Number max;
671             if (split.hasNext()) {
672                 max = parseNumberConstraintValue(split.next(), moduleName, line);
673                 if (split.hasNext()) {
674                     throw new YangParseException(moduleName, ctx.getStart().getLine(), "Malformed length constraint \"" + def + "\".");
675                 }
676             } else {
677                 max = min;
678             }
679
680             LengthConstraint range = BaseConstraints.newLengthConstraint(min, max, description, reference);
681             lengthConstraints.add(range);
682         }
683
684         return lengthConstraints;
685     }
686
687     /**
688      * @param value
689      *            value to parse
690      * @param moduleName
691      *            name of current module
692      * @param line
693      *            current line in module
694      * @return wrapper object of primitive java type or UnknownBoundaryNumber if
695      *         type is one of special YANG values 'min' or 'max'
696      */
697     private static Number parseNumberConstraintValue(final String value, final String moduleName, final int line) {
698         Number result;
699         if ("min".equals(value) || "max".equals(value)) {
700             result = new UnknownBoundaryNumber(value);
701         } else {
702             try {
703                 if (value.indexOf('.') != -1) {
704                     result = new BigDecimal(value);
705                 } else {
706                     result = new BigInteger(value);
707                 }
708             } catch (NumberFormatException e) {
709                 throw new YangParseException(moduleName, line, "Unable to parse range value '" + value + "'.", e);
710             }
711         }
712         return result;
713     }
714
715     /**
716      * Parse type body and return pattern constraints.
717      *
718      * @param ctx
719      *            type body
720      * @return list of pattern constraints
721      */
722     private static List<PatternConstraint> getPatternConstraint(final Type_body_stmtsContext ctx) {
723         List<PatternConstraint> patterns = new ArrayList<>();
724
725         for (int i = 0; i < ctx.getChildCount(); i++) {
726             ParseTree stringRestrChild = ctx.getChild(i);
727             if (stringRestrChild instanceof String_restrictionsContext) {
728                 for (int j = 0; j < stringRestrChild.getChildCount(); j++) {
729                     ParseTree lengthChild = stringRestrChild.getChild(j);
730                     if (lengthChild instanceof Pattern_stmtContext) {
731                         patterns.add(parsePatternConstraint((Pattern_stmtContext) lengthChild));
732                     }
733                 }
734             }
735         }
736         return patterns;
737     }
738
739     /**
740      * Internal helper method.
741      *
742      * @param ctx
743      *            pattern context
744      * @return PatternConstraint object
745      */
746     private static PatternConstraint parsePatternConstraint(final Pattern_stmtContext ctx) {
747         String description = null;
748         String reference = null;
749         for (int i = 0; i < ctx.getChildCount(); i++) {
750             ParseTree child = ctx.getChild(i);
751             if (child instanceof Description_stmtContext) {
752                 description = stringFromNode(child);
753             } else if (child instanceof Reference_stmtContext) {
754                 reference = stringFromNode(child);
755             }
756         }
757         String pattern = parsePatternString(ctx);
758         return BaseConstraints.patternConstraint(pattern, description, reference);
759     }
760
761     /**
762      * Parse given context and return pattern value.
763      *
764      * @param ctx
765      *            context to parse
766      * @return pattern value as String
767      */
768     private static String parsePatternString(final Pattern_stmtContext ctx) {
769         StringBuilder result = new StringBuilder();
770         for (int i = 0; i < ctx.getChildCount(); ++i) {
771             ParseTree child = ctx.getChild(i);
772             if (child instanceof StringContext) {
773                 for (int j = 0; j < child.getChildCount(); j++) {
774                     if (j % 2 == 0) {
775                         String patternToken = child.getChild(j).getText();
776                         result.append(patternToken.substring(1, patternToken.length() - 1));
777                     }
778                 }
779             }
780         }
781         return result.toString();
782     }
783
784     /**
785      * Get fraction digits value from type body.
786      *
787      * @param ctx
788      *            type body context to parse
789      * @param moduleName
790      *            name of current module
791      * @return 'fraction-digits' value if present in given context, null
792      *         otherwise
793      */
794     private static Integer getFractionDigits(final Type_body_stmtsContext ctx, final String moduleName) {
795         Integer result = null;
796         for (int i = 0; i < ctx.getChildCount(); i++) {
797             ParseTree dec64specChild = ctx.getChild(i);
798             if (dec64specChild instanceof Decimal64_specificationContext) {
799                 result = parseFractionDigits((Decimal64_specificationContext) dec64specChild, moduleName);
800             }
801         }
802         return result;
803     }
804
805     /**
806      * Parse decimal64 fraction-digits value.
807      *
808      * @param ctx
809      *            decimal64 context
810      * @param moduleName
811      *            name of current module
812      * @return fraction-digits value as Integer
813      */
814     private static Integer parseFractionDigits(final Decimal64_specificationContext ctx, final String moduleName) {
815         Integer result = null;
816         for (int i = 0; i < ctx.getChildCount(); i++) {
817             ParseTree fdChild = ctx.getChild(i);
818             if (fdChild instanceof Fraction_digits_stmtContext) {
819                 String value = stringFromNode(fdChild);
820                 try {
821                     result = Integer.valueOf(value);
822                 } catch (NumberFormatException e) {
823                     throw new YangParseException(moduleName, ctx.getStart().getLine(),
824                             "Unable to parse fraction digits value '" + value + "'.", e);
825                 }
826             }
827         }
828         return result;
829     }
830
831     /**
832      * Internal helper method for parsing bit statements from given type body
833      * context.
834      *
835      * @param ctx
836      *            type body context to parse
837      * @param actualPath
838      *            current position in YANG model
839      * @param moduleName
840      *            current module name
841      * @return List of Bit objects created from this context
842      */
843     private static List<BitsTypeDefinition.Bit> getBits(final Type_body_stmtsContext ctx, final SchemaPath actualPath,
844             final String moduleName) {
845         final List<BitsTypeDefinition.Bit> bits = new ArrayList<>();
846         for (int j = 0; j < ctx.getChildCount(); j++) {
847             ParseTree bitsSpecChild = ctx.getChild(j);
848             if (bitsSpecChild instanceof Bits_specificationContext) {
849                 long highestPosition = -1;
850                 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
851                     ParseTree bitChild = bitsSpecChild.getChild(k);
852                     if (bitChild instanceof Bit_stmtContext) {
853                         Bit bit = parseBit((Bit_stmtContext) bitChild, highestPosition, actualPath, moduleName);
854                         if (bit.getPosition() > highestPosition) {
855                             highestPosition = bit.getPosition();
856                         }
857                         bits.add(bit);
858                     }
859                 }
860             }
861         }
862         return bits;
863     }
864
865     /**
866      * Internal helper method for parsing bit context.
867      *
868      * @param ctx
869      *            bit statement context to parse
870      * @param highestPosition
871      *            current highest position in bits type
872      * @param actualPath
873      *            current position in YANG model
874      * @param moduleName
875      *            current module name
876      * @return Bit object parsed from this context
877      */
878     private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, final long highestPosition,
879             final SchemaPath actualPath, final String moduleName) {
880         String name = stringFromNode(ctx);
881         Long position = null;
882
883         String description = null;
884         String reference = null;
885         Status status = Status.CURRENT;
886
887         SchemaPath schemaPath = createBaseTypePath(actualPath, name);
888
889         for (int i = 0; i < ctx.getChildCount(); i++) {
890             ParseTree child = ctx.getChild(i);
891             if (child instanceof Position_stmtContext) {
892                 String positionStr = stringFromNode(child);
893                 position = Long.valueOf(positionStr);
894             } else if (child instanceof Description_stmtContext) {
895                 description = stringFromNode(child);
896             } else if (child instanceof Reference_stmtContext) {
897                 reference = stringFromNode(child);
898             } else if (child instanceof Status_stmtContext) {
899                 status = parseStatus((Status_stmtContext) child);
900             }
901         }
902
903         if (position == null) {
904             position = highestPosition + 1;
905         }
906         if (position < 0 || position > 4294967295L) {
907             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Error on bit '" + name
908                     + "': the position value MUST be in the range 0 to 4294967295");
909         }
910
911         final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
912         return new BitImpl(position, schemaPath.getPathTowardsRoot().iterator().next(), schemaPath,
913                 description, reference, status, unknownNodes);
914     }
915
916     /**
917      * Parse 'ordered-by' statement.
918      *
919      * The 'ordered-by' statement defines whether the order of entries within a
920      * list are determined by the user or the system. The argument is one of the
921      * strings "system" or "user". If not present, order defaults to "system".
922      *
923      * @param ctx
924      *            Ordered_by_stmtContext
925      * @return true, if ordered-by contains value 'user', false otherwise
926      */
927     public static boolean parseUserOrdered(final Ordered_by_stmtContext ctx) {
928         boolean result = false;
929         for (int j = 0; j < ctx.getChildCount(); j++) {
930             ParseTree orderArg = ctx.getChild(j);
931             if (orderArg instanceof Ordered_by_argContext) {
932                 String orderStr = stringFromNode(orderArg);
933                 switch (orderStr) {
934                 case "system":
935                     result = false;
936                     break;
937                 case "user":
938                     result = true;
939                     break;
940                 default:
941                     LOG.warn("Invalid 'ordered-by' statement.");
942                 }
943             }
944         }
945         return result;
946     }
947
948     /**
949      * Get config statement from given context. If there is no config statement,
950      * return config value of parent
951      *
952      * @param ctx
953      *            context to parse
954      * @param node
955      *            current node
956      * @param moduleName
957      *            name of current module
958      * @param line
959      *            line in current module
960      * @return config statement parsed from given context
961      */
962     public static boolean getConfig(final ParseTree ctx, final Builder node, final String moduleName, final int line) {
963         boolean result;
964         // parse configuration statement
965         Boolean config = null;
966         for (int i = 0; i < ctx.getChildCount(); i++) {
967             ParseTree child = ctx.getChild(i);
968             if (child instanceof Config_stmtContext) {
969                 config = parseConfig((Config_stmtContext) child, moduleName);
970                 break;
971             }
972         }
973
974         // If 'config' is not specified, the default is the same as the parent
975         // schema node's 'config' value
976         boolean parentConfig = getParentConfig(node);
977         if (config == null) {
978             result = parentConfig;
979         } else {
980             // Check: if a node has 'config' set to 'false', no node underneath
981             // it can have 'config' set to 'true'
982             if (!parentConfig && config) {
983                 throw new YangParseException(moduleName, line,
984                         "Can not set 'config' to 'true' if parent node has 'config' set to 'false'");
985             }
986             result = config;
987         }
988
989         return result;
990     }
991
992     private static boolean getParentConfig(final Builder node) {
993         Builder parent = node.getParent();
994         boolean config;
995
996         if (parent instanceof ChoiceCaseBuilder) {
997             parent = parent.getParent();
998         }
999         if (parent instanceof DataSchemaNodeBuilder) {
1000             config = ((DataSchemaNodeBuilder) parent).isConfiguration();
1001         } else {
1002             config = true;
1003         }
1004         return config;
1005     }
1006
1007     /**
1008      * Parse config statement.
1009      *
1010      * @param ctx
1011      *            config context to parse
1012      * @param moduleName
1013      *            current module name
1014      * @return true if given context contains string 'true', false otherwise
1015      */
1016     private static Boolean parseConfig(final Config_stmtContext ctx, final String moduleName) {
1017         Boolean result = null;
1018         if (ctx != null) {
1019             for (int i = 0; i < ctx.getChildCount(); ++i) {
1020                 final ParseTree configContext = ctx.getChild(i);
1021                 if (configContext instanceof Config_argContext) {
1022                     final String value = stringFromNode(configContext);
1023                     switch (value) {
1024                     case "true":
1025                         result = true;
1026                         break;
1027                     case "false":
1028                         result = false;
1029                         break;
1030                     default:
1031                         throw new YangParseException(moduleName, ctx.getStart().getLine(),
1032                                 "Failed to parse 'config' statement value: '" + value + "'.");
1033                     }
1034                 }
1035             }
1036         }
1037         return result;
1038     }
1039
1040     /**
1041      * Parse type body and create UnknownType definition.
1042      *
1043      * @param typedefQName
1044      *            qname of current type
1045      * @param ctx
1046      *            type body
1047      * @param actualPath
1048      *            actual path in model
1049      * @param namespace
1050      *            module namespace
1051      * @param revision
1052      *            module revision
1053      * @param prefix
1054      *            module prefix
1055      * @param parent
1056      *            current node parent
1057      * @return UnknownType object with constraints from parsed type body
1058      */
1059     public static TypeDefinition<?> parseUnknownTypeWithBody(final QName typedefQName,
1060             final Type_body_stmtsContext ctx, final SchemaPath actualPath, final QName moduleQName, final Builder parent) {
1061         String moduleName = parent.getModuleName();
1062         String typeName = typedefQName.getLocalName();
1063
1064         UnknownType.Builder unknownType = new UnknownType.Builder(typedefQName);
1065
1066         if (ctx != null) {
1067             List<RangeConstraint> rangeStatements = getRangeConstraints(ctx, moduleName);
1068             List<LengthConstraint> lengthStatements = getLengthConstraints(ctx, moduleName);
1069             List<PatternConstraint> patternStatements = getPatternConstraint(ctx);
1070             Integer fractionDigits = getFractionDigits(ctx, moduleName);
1071
1072             if (parent instanceof TypeDefinitionBuilder) {
1073                 TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1074                 typedef.setRanges(rangeStatements);
1075                 typedef.setLengths(lengthStatements);
1076                 typedef.setPatterns(patternStatements);
1077                 typedef.setFractionDigits(fractionDigits);
1078                 return unknownType.build();
1079             } else {
1080                 TypeDefinition<?> baseType = unknownType.build();
1081                 QName qname = QName.create(moduleQName, typeName);
1082                 SchemaPath schemaPath = createTypePath(actualPath, typeName);
1083
1084                 ExtendedType.Builder typeBuilder = new ExtendedType.Builder(qname, baseType, null, null, schemaPath);
1085                 typeBuilder.ranges(rangeStatements);
1086                 typeBuilder.lengths(lengthStatements);
1087                 typeBuilder.patterns(patternStatements);
1088                 typeBuilder.fractionDigits(fractionDigits);
1089
1090                 return typeBuilder.build();
1091             }
1092         }
1093
1094         return unknownType.build();
1095     }
1096
1097     /**
1098      * Create TypeDefinition object based on given type name and type body.
1099      *
1100      * @param typeName
1101      *            name of type
1102      * @param typeBody
1103      *            type body context
1104      * @param actualPath
1105      *            current path in schema
1106      * @param namespace
1107      *            current namespace
1108      * @param revision
1109      *            current revision
1110      * @param prefix
1111      *            current prefix
1112      * @param parent
1113      *            parent builder
1114      * @return TypeDefinition object based on parsed values.
1115      */
1116     public static TypeDefinition<?> parseTypeWithBody(final String typeName, final Type_body_stmtsContext typeBody,
1117             final SchemaPath actualPath, final QName moduleQName, final Builder parent) {
1118
1119         final String moduleName = parent.getModuleName();
1120         final int line = typeBody.getStart().getLine();
1121         TypeDefinition<?> baseType = null;
1122
1123         Integer fractionDigits = getFractionDigits(typeBody, moduleName);
1124         List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleName);
1125         List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1126         List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleName);
1127
1128         TypeConstraints constraints = new TypeConstraints(moduleName, line);
1129         constraints.addFractionDigits(fractionDigits);
1130         constraints.addLengths(lengthStatements);
1131         constraints.addPatterns(patternStatements);
1132         constraints.addRanges(rangeStatements);
1133
1134         SchemaPath baseTypePath = createBaseTypePath(actualPath, typeName);
1135         SchemaPath extBaseTypePath = createExtendedBaseTypePath(actualPath, moduleQName, typeName);
1136
1137         if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1138             extBaseTypePath = baseTypePath;
1139         }
1140
1141         if ("decimal64".equals(typeName)) {
1142             if (rangeStatements.isEmpty()) {
1143                 try {
1144                     return Decimal64.create(baseTypePath, fractionDigits);
1145                 } catch(Exception e) {
1146                     throw new YangParseException(moduleName, line, e.getMessage());
1147                 }
1148             }
1149             Decimal64 decimalType = Decimal64.create(extBaseTypePath, fractionDigits);
1150             constraints.addRanges(decimalType.getRangeConstraints());
1151             baseType = decimalType;
1152         } else if (typeName.startsWith("int")) {
1153             IntegerTypeDefinition intType = null;
1154             switch (typeName) {
1155             case "int8":
1156                 intType = Int8.getInstance();
1157                 break;
1158             case "int16":
1159                 intType = Int16.getInstance();
1160                 break;
1161             case "int32":
1162                 intType = Int32.getInstance();
1163                 break;
1164             case "int64":
1165                 intType = Int64.getInstance();
1166                 break;
1167             }
1168             if (intType == null) {
1169                 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1170             }
1171             constraints.addRanges(intType.getRangeConstraints());
1172             baseType = intType;
1173         } else if (typeName.startsWith("uint")) {
1174             UnsignedIntegerTypeDefinition uintType = null;
1175             switch (typeName) {
1176             case "uint8":
1177                 uintType = Uint8.getInstance();
1178                 break;
1179             case "uint16":
1180                 uintType = Uint16.getInstance();
1181                 break;
1182             case "uint32":
1183                 uintType = Uint32.getInstance();
1184                 break;
1185             case "uint64":
1186                 uintType = Uint64.getInstance();
1187                 break;
1188             }
1189             if (uintType == null) {
1190                 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1191             }
1192             constraints.addRanges(uintType.getRangeConstraints());
1193             baseType = uintType;
1194         } else if ("enumeration".equals(typeName)) {
1195             List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, moduleName);
1196             return EnumerationType.create(baseTypePath, enumConstants, Optional.<EnumPair> absent());
1197         } else if ("string".equals(typeName)) {
1198             StringTypeDefinition stringType = StringType.getInstance();
1199             constraints.addLengths(stringType.getLengthConstraints());
1200             baseType = stringType;
1201         } else if ("bits".equals(typeName)) {
1202             return BitsType.create(baseTypePath, getBits(typeBody, actualPath, moduleName));
1203         } else if ("leafref".equals(typeName)) {
1204             final String path = parseLeafrefPath(typeBody);
1205             final boolean absolute = path.startsWith("/");
1206             RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path, absolute);
1207             return new Leafref(xpath);
1208         } else if ("binary".equals(typeName)) {
1209             BinaryTypeDefinition binaryType = BinaryType.getInstance();
1210             constraints.addLengths(binaryType.getLengthConstraints());
1211             baseType = binaryType;
1212         } else if ("instance-identifier".equals(typeName)) {
1213             return InstanceIdentifier.create(isRequireInstance(typeBody));
1214         }
1215
1216         if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1217             TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1218             typedef.setRanges(constraints.getRange());
1219             typedef.setLengths(constraints.getLength());
1220             typedef.setPatterns(constraints.getPatterns());
1221             typedef.setFractionDigits(constraints.getFractionDigits());
1222             return baseType;
1223         }
1224
1225         QName qname = QName.create(moduleQName, typeName);
1226         SchemaPath schemaPath = actualPath.createChild(qname);
1227         ExtendedType.Builder typeBuilder = new ExtendedType.Builder(qname, baseType, "", "", schemaPath);
1228
1229         typeBuilder.ranges(constraints.getRange());
1230         typeBuilder.lengths(constraints.getLength());
1231         typeBuilder.patterns(constraints.getPatterns());
1232         typeBuilder.fractionDigits(constraints.getFractionDigits());
1233
1234         return typeBuilder.build();
1235     }
1236
1237     private static SchemaPath createTypePath(final SchemaPath actual, final String typeName) {
1238         QName last = actual.getLastComponent();
1239         return actual.createChild(QName.create(last, typeName));
1240     }
1241
1242     private static SchemaPath createBaseTypePath(final SchemaPath actual, final String typeName) {
1243         return actual.createChild(BaseTypes.constructQName(typeName));
1244     }
1245
1246     private static SchemaPath createExtendedBaseTypePath(final SchemaPath actual, final QName moduleQName, final String typeName) {
1247         return actual.createChild(
1248                 QName.create(moduleQName, typeName),
1249                 BaseTypes.constructQName(typeName));
1250     }
1251
1252     /**
1253      * Parse given context and find identityref base value.
1254      *
1255      * @param ctx
1256      *            type body
1257      * @return identityref base value as String
1258      */
1259     public static String getIdentityrefBase(final Type_body_stmtsContext ctx) {
1260         String result = null;
1261         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1262             ParseTree child = ctx.getChild(i);
1263             if (child instanceof Identityref_specificationContext) {
1264                 for (int j = 0; j < child.getChildCount(); j++) {
1265                     ParseTree baseArg = child.getChild(j);
1266                     if (baseArg instanceof Base_stmtContext) {
1267                         result = stringFromNode(baseArg);
1268                         break outer;
1269                     }
1270                 }
1271             }
1272         }
1273         return result;
1274     }
1275
1276     /**
1277      * Parse type body statement and find require-instance value.
1278      *
1279      * @param ctx
1280      *            type body context
1281      * @return require-instance value
1282      */
1283     private static boolean isRequireInstance(final Type_body_stmtsContext ctx) {
1284         for (int i = 0; i < ctx.getChildCount(); i++) {
1285             ParseTree child = ctx.getChild(i);
1286             if (child instanceof Instance_identifier_specificationContext) {
1287                 for (int j = 0; j < child.getChildCount(); j++) {
1288                     ParseTree reqStmt = child.getChild(j);
1289                     if (reqStmt instanceof Require_instance_stmtContext) {
1290                         for (int k = 0; k < reqStmt.getChildCount(); k++) {
1291                             ParseTree reqArg = reqStmt.getChild(k);
1292                             if (reqArg instanceof Require_instance_argContext) {
1293                                 return Boolean.valueOf(stringFromNode(reqArg));
1294                             }
1295                         }
1296                     }
1297                 }
1298             }
1299         }
1300         return true;
1301     }
1302
1303     /**
1304      * Parse type body statement and find leafref path.
1305      *
1306      * @param ctx
1307      *            type body context
1308      * @return leafref path as String
1309      */
1310     private static String parseLeafrefPath(final Type_body_stmtsContext ctx) {
1311         for (int i = 0; i < ctx.getChildCount(); i++) {
1312             ParseTree child = ctx.getChild(i);
1313             if (child instanceof Leafref_specificationContext) {
1314                 for (int j = 0; j < child.getChildCount(); j++) {
1315                     ParseTree leafRefSpec = child.getChild(j);
1316                     if (leafRefSpec instanceof Path_stmtContext) {
1317                         return stringFromNode(leafRefSpec);
1318                     }
1319                 }
1320             }
1321         }
1322         return null;
1323     }
1324
1325     /**
1326      * Internal helper method for parsing must statement.
1327      *
1328      * @param ctx
1329      *            Must_stmtContext
1330      * @return MustDefinition object based on parsed context
1331      */
1332     private static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1333         StringBuilder mustText = new StringBuilder();
1334         String description = null;
1335         String reference = null;
1336         String errorAppTag = null;
1337         String errorMessage = null;
1338         for (int i = 0; i < ctx.getChildCount(); ++i) {
1339             ParseTree child = ctx.getChild(i);
1340             if (child instanceof StringContext) {
1341                 final StringContext context = (StringContext) child;
1342                 if (context.getChildCount() == 1) {
1343                     String mustPart = context.getChild(0).getText();
1344                     // trim start and end quotation
1345                     mustText.append(mustPart.substring(1, mustPart.length() - 1));
1346                 } else {
1347                     for (int j = 0; j < context.getChildCount(); j++) {
1348                         String mustPart = context.getChild(j).getText();
1349                         if (j == 0) {
1350                             mustText.append(mustPart.substring(0, mustPart.length() - 1));
1351                             continue;
1352                         }
1353                         if (j % 2 == 0) {
1354                             mustText.append(mustPart.substring(1));
1355                         }
1356                     }
1357                 }
1358             } else if (child instanceof Description_stmtContext) {
1359                 description = stringFromNode(child);
1360             } else if (child instanceof Reference_stmtContext) {
1361                 reference = stringFromNode(child);
1362             } else if (child instanceof Error_app_tag_stmtContext) {
1363                 errorAppTag = stringFromNode(child);
1364             } else if (child instanceof Error_message_stmtContext) {
1365                 errorMessage = stringFromNode(child);
1366             }
1367         }
1368
1369         return new MustDefinitionImpl(mustText.toString(), description, reference, errorAppTag, errorMessage);
1370     }
1371
1372     /**
1373      * Parse given context and set constraints to constraints builder.
1374      *
1375      * @param ctx
1376      *            context to parse
1377      * @param constraints
1378      *            ConstraintsBuilder to fill
1379      */
1380     public static void parseConstraints(final ParseTree ctx, final ConstraintsBuilder constraints) {
1381         for (int i = 0; i < ctx.getChildCount(); ++i) {
1382             final ParseTree childNode = ctx.getChild(i);
1383             if (childNode instanceof Max_elements_stmtContext) {
1384                 Integer max = parseMaxElements((Max_elements_stmtContext) childNode, constraints.getModuleName());
1385                 constraints.setMaxElements(max);
1386             } else if (childNode instanceof Min_elements_stmtContext) {
1387                 Integer min = parseMinElements((Min_elements_stmtContext) childNode, constraints.getModuleName());
1388                 constraints.setMinElements(min);
1389             } else if (childNode instanceof Must_stmtContext) {
1390                 MustDefinition must = parseMust((Must_stmtContext) childNode);
1391                 constraints.addMustDefinition(must);
1392             } else if (childNode instanceof Mandatory_stmtContext) {
1393                 for (int j = 0; j < childNode.getChildCount(); j++) {
1394                     ParseTree mandatoryTree = childNode.getChild(j);
1395                     if (mandatoryTree instanceof Mandatory_argContext) {
1396                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1397                         constraints.setMandatory(mandatory);
1398                     }
1399                 }
1400             } else if (childNode instanceof When_stmtContext) {
1401                 constraints.addWhenCondition(stringFromNode(childNode));
1402             }
1403         }
1404     }
1405
1406     private static Integer parseMinElements(final Min_elements_stmtContext ctx, final String moduleName) {
1407         Integer result = null;
1408         try {
1409             for (int i = 0; i < ctx.getChildCount(); i++) {
1410                 ParseTree minArg = ctx.getChild(i);
1411                 if (minArg instanceof Min_value_argContext) {
1412                     result = Integer.valueOf(stringFromNode(minArg));
1413                 }
1414             }
1415             if (result == null) {
1416                 throw new IllegalArgumentException();
1417             }
1418             return result;
1419         } catch (Exception e) {
1420             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse min-elements.", e);
1421         }
1422     }
1423
1424     private static Integer parseMaxElements(final Max_elements_stmtContext ctx, final String moduleName) {
1425         Integer result = null;
1426         try {
1427             for (int i = 0; i < ctx.getChildCount(); i++) {
1428                 ParseTree maxArg = ctx.getChild(i);
1429                 if (maxArg instanceof Max_value_argContext) {
1430                     result = Integer.valueOf(stringFromNode(maxArg));
1431                 }
1432             }
1433             if (result == null) {
1434                 throw new IllegalArgumentException();
1435             }
1436             return result;
1437         } catch (Exception e) {
1438             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse max-elements.", e);
1439         }
1440     }
1441
1442     /**
1443      * Parse given context and return yin value.
1444      *
1445      * @param ctx
1446      *            context to parse
1447      * @return true if value is 'true', false otherwise
1448      */
1449     public static boolean parseYinValue(final Argument_stmtContext ctx) {
1450         boolean yinValue = false;
1451         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1452             ParseTree yin = ctx.getChild(i);
1453             if (yin instanceof Yin_element_stmtContext) {
1454                 for (int j = 0; j < yin.getChildCount(); j++) {
1455                     ParseTree yinArg = yin.getChild(j);
1456                     if (yinArg instanceof Yin_element_argContext) {
1457                         String yinString = stringFromNode(yinArg);
1458                         if ("true".equals(yinString)) {
1459                             yinValue = true;
1460                             break outer;
1461                         }
1462                     }
1463                 }
1464             }
1465         }
1466         return yinValue;
1467     }
1468
1469     /**
1470      * Check this base type.
1471      *
1472      * @param typeName
1473      *            base YANG type name
1474      * @param moduleName
1475      *            name of current module
1476      * @param line
1477      *            line in module
1478      * @throws YangParseException
1479      *             if this is one of YANG type which MUST contain additional
1480      *             informations in its body
1481      */
1482     public static void checkMissingBody(final String typeName, final String moduleName, final int line) {
1483         switch (typeName) {
1484         case "decimal64":
1485             throw new YangParseException(moduleName, line,
1486                     "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1487         case "identityref":
1488             throw new YangParseException(moduleName, line,
1489                     "The 'base' statement MUST be present if the type is 'identityref'.");
1490         case "leafref":
1491             throw new YangParseException(moduleName, line,
1492                     "The 'path' statement MUST be present if the type is 'leafref'.");
1493         case "bits":
1494             throw new YangParseException(moduleName, line, "The 'bit' statement MUST be present if the type is 'bits'.");
1495         case "enumeration":
1496             throw new YangParseException(moduleName, line,
1497                     "The 'enum' statement MUST be present if the type is 'enumeration'.");
1498         }
1499     }
1500
1501     /**
1502      * Parse refine statement.
1503      *
1504      * @param refineCtx
1505      *            refine statement
1506      * @param moduleName
1507      *            name of current module
1508      * @return RefineHolder object representing this refine statement
1509      */
1510     public static RefineHolderImpl parseRefine(final Refine_stmtContext refineCtx, final String moduleName) {
1511         final String refineTarget = stringFromNode(refineCtx);
1512         final RefineHolderImpl refine = new RefineHolderImpl(moduleName, refineCtx.getStart().getLine(), refineTarget);
1513         for (int i = 0; i < refineCtx.getChildCount(); i++) {
1514             ParseTree refinePom = refineCtx.getChild(i);
1515             if (refinePom instanceof Refine_pomContext) {
1516                 for (int j = 0; j < refinePom.getChildCount(); j++) {
1517                     ParseTree refineStmt = refinePom.getChild(j);
1518                     parseRefineDefault(refine, refineStmt);
1519
1520                     if (refineStmt instanceof Refine_leaf_stmtsContext) {
1521                         parseRefine(refine, (Refine_leaf_stmtsContext) refineStmt);
1522                     } else if (refineStmt instanceof Refine_container_stmtsContext) {
1523                         parseRefine(refine, (Refine_container_stmtsContext) refineStmt);
1524                     } else if (refineStmt instanceof Refine_list_stmtsContext) {
1525                         parseRefine(refine, (Refine_list_stmtsContext) refineStmt);
1526                     } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1527                         parseRefine(refine, (Refine_leaf_list_stmtsContext) refineStmt);
1528                     } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1529                         parseRefine(refine, (Refine_choice_stmtsContext) refineStmt);
1530                     } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1531                         parseRefine(refine, (Refine_anyxml_stmtsContext) refineStmt);
1532                     }
1533                 }
1534             }
1535         }
1536         return refine;
1537     }
1538
1539     private static void parseRefineDefault(final RefineHolderImpl refine, final ParseTree refineStmt) {
1540         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1541             ParseTree refineArg = refineStmt.getChild(i);
1542             if (refineArg instanceof Description_stmtContext) {
1543                 String description = stringFromNode(refineArg);
1544                 refine.setDescription(description);
1545             } else if (refineArg instanceof Reference_stmtContext) {
1546                 String reference = stringFromNode(refineArg);
1547                 refine.setReference(reference);
1548             } else if (refineArg instanceof Config_stmtContext) {
1549                 Boolean config = parseConfig((Config_stmtContext) refineArg, refine.getModuleName());
1550                 refine.setConfiguration(config);
1551             }
1552         }
1553     }
1554
1555     private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_stmtsContext refineStmt) {
1556         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1557             ParseTree refineArg = refineStmt.getChild(i);
1558             if (refineArg instanceof Default_stmtContext) {
1559                 String defaultStr = stringFromNode(refineArg);
1560                 refine.setDefaultStr(defaultStr);
1561             } else if (refineArg instanceof Mandatory_stmtContext) {
1562                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1563                     ParseTree mandatoryTree = refineArg.getChild(j);
1564                     if (mandatoryTree instanceof Mandatory_argContext) {
1565                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1566                         refine.setMandatory(mandatory);
1567                     }
1568                 }
1569             } else if (refineArg instanceof Must_stmtContext) {
1570                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1571                 refine.setMust(must);
1572
1573             }
1574         }
1575         return refine;
1576     }
1577
1578     private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_container_stmtsContext refineStmt) {
1579         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1580             ParseTree refineArg = refineStmt.getChild(i);
1581             if (refineArg instanceof Must_stmtContext) {
1582                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1583                 refine.setMust(must);
1584             } else if (refineArg instanceof Presence_stmtContext) {
1585                 refine.setPresence(true);
1586             }
1587         }
1588         return refine;
1589     }
1590
1591     private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_list_stmtsContext refineStmt) {
1592         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1593             ParseTree refineArg = refineStmt.getChild(i);
1594             if (refineArg instanceof Must_stmtContext) {
1595                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1596                 refine.setMust(must);
1597             } else if (refineArg instanceof Max_elements_stmtContext) {
1598                 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1599                 refine.setMaxElements(max);
1600             } else if (refineArg instanceof Min_elements_stmtContext) {
1601                 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1602                 refine.setMinElements(min);
1603             }
1604         }
1605         return refine;
1606     }
1607
1608     private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_list_stmtsContext refineStmt) {
1609         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1610             ParseTree refineArg = refineStmt.getChild(i);
1611             if (refineArg instanceof Must_stmtContext) {
1612                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1613                 refine.setMust(must);
1614             } else if (refineArg instanceof Max_elements_stmtContext) {
1615                 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1616                 refine.setMaxElements(max);
1617             } else if (refineArg instanceof Min_elements_stmtContext) {
1618                 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1619                 refine.setMinElements(min);
1620             }
1621         }
1622         return refine;
1623     }
1624
1625     private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_choice_stmtsContext refineStmt) {
1626         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1627             ParseTree refineArg = refineStmt.getChild(i);
1628             if (refineArg instanceof Default_stmtContext) {
1629                 String defaultStr = stringFromNode(refineArg);
1630                 refine.setDefaultStr(defaultStr);
1631             } else if (refineArg instanceof Mandatory_stmtContext) {
1632                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1633                     ParseTree mandatoryTree = refineArg.getChild(j);
1634                     if (mandatoryTree instanceof Mandatory_argContext) {
1635                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1636                         refine.setMandatory(mandatory);
1637                     }
1638                 }
1639             }
1640         }
1641         return refine;
1642     }
1643
1644     private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_anyxml_stmtsContext refineStmt) {
1645         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1646             ParseTree refineArg = refineStmt.getChild(i);
1647             if (refineArg instanceof Must_stmtContext) {
1648                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1649                 refine.setMust(must);
1650             } else if (refineArg instanceof Mandatory_stmtContext) {
1651                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1652                     ParseTree mandatoryTree = refineArg.getChild(j);
1653                     if (mandatoryTree instanceof Mandatory_argContext) {
1654                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1655                         refine.setMandatory(mandatory);
1656                     }
1657                 }
1658             }
1659         }
1660         return refine;
1661     }
1662
1663     public static String getArgumentString(final org.antlr.v4.runtime.ParserRuleContext ctx) {
1664         List<StringContext> potentialValues = ctx.getRuleContexts(StringContext.class);
1665         checkState(!potentialValues.isEmpty());
1666         return ParserListenerUtils.stringFromStringContext(potentialValues.get(0));
1667     }
1668
1669     public static <T extends ParserRuleContext> Optional<T> getFirstContext(final ParserRuleContext context,final Class<T> contextType) {
1670         List<T> potential = context.getRuleContexts(contextType);
1671         if(potential.isEmpty()) {
1672             return Optional.absent();
1673         }
1674         return Optional.of(potential.get(0));
1675     }
1676
1677 }