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