BUG-1382: eliminate use of QName.getPrefix from yang parser
[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.InstanceIdentifierType;
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.parser.builder.api.Builder;
122 import org.opendaylight.yangtools.yang.parser.builder.api.ConstraintsBuilder;
123 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
124 import org.opendaylight.yangtools.yang.parser.builder.api.RefineBuilder;
125 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
126 import org.opendaylight.yangtools.yang.parser.builder.api.TypeAwareBuilder;
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.ModuleBuilder;
130 import org.opendaylight.yangtools.yang.parser.builder.impl.RefineHolderImpl;
131 import org.opendaylight.yangtools.yang.parser.builder.impl.TypeDefinitionBuilderImpl;
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         Optional<String> description = Optional.absent();
748         Optional<String> reference = Optional.absent();
749         for (int i = 0; i < ctx.getChildCount(); i++) {
750             ParseTree child = ctx.getChild(i);
751             if (child instanceof Description_stmtContext) {
752                 description = Optional.of(stringFromNode(child));
753             } else if (child instanceof Reference_stmtContext) {
754                 reference = Optional.of(stringFromNode(child));
755             }
756         }
757         String pattern = parsePatternString(ctx);
758         return BaseConstraints.newPatternConstraint(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 unknown type with body.
1042      *
1043      * @param typeBody
1044      *            type body
1045      * @param parent
1046      *            current node parent
1047      * @param prefixedQName
1048      *            type qname with prefix
1049      * @param moduleBuilder
1050      *            current module builder
1051      * @param moduleQName
1052      *            current module qname
1053      * @param actualPath
1054      *            actual path in model
1055      */
1056     public static void parseUnknownTypeWithBody(Type_body_stmtsContext typeBody, TypeAwareBuilder parent,
1057             QName prefixedQName, ModuleBuilder moduleBuilder, QName moduleQName, SchemaPath actualPath) {
1058         final int line = typeBody.getStart().getLine();
1059
1060         List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleBuilder.getName());
1061         List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleBuilder.getName());
1062         List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1063         Integer fractionDigits = getFractionDigits(typeBody, moduleBuilder.getName());
1064
1065         if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1066             TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1067             typedef.setRanges(rangeStatements);
1068             typedef.setLengths(lengthStatements);
1069             typedef.setPatterns(patternStatements);
1070             typedef.setFractionDigits(fractionDigits);
1071             typedef.setTypeQName(prefixedQName);
1072             // add parent node of this type statement to dirty nodes
1073             moduleBuilder.markActualNodeDirty();
1074         } else {
1075             QName qname = QName.create(moduleQName, prefixedQName.getLocalName());
1076             SchemaPath schemaPath = createTypePath(actualPath, prefixedQName.getLocalName());
1077             TypeDefinitionBuilder typeBuilder = new TypeDefinitionBuilderImpl(moduleBuilder.getName(), line, qname, schemaPath);
1078             typeBuilder.setRanges(rangeStatements);
1079             typeBuilder.setLengths(lengthStatements);
1080             typeBuilder.setPatterns(patternStatements);
1081             typeBuilder.setFractionDigits(fractionDigits);
1082             typeBuilder.setTypeQName(prefixedQName);
1083             parent.setTypedef(typeBuilder);
1084             moduleBuilder.getDirtyNodes().add(typeBuilder);
1085         }
1086     }
1087
1088     /**
1089      * Create TypeDefinition object based on given type name and type body.
1090      *
1091      * @param typeName
1092      *            name of type
1093      * @param typeBody
1094      *            type body context
1095      * @param actualPath
1096      *            current path in schema
1097      * @param namespace
1098      *            current namespace
1099      * @param revision
1100      *            current revision
1101      * @param prefix
1102      *            current prefix
1103      * @param parent
1104      *            parent builder
1105      * @return TypeDefinition object based on parsed values.
1106      */
1107     public static TypeDefinition<?> parseTypeWithBody(final String typeName, final Type_body_stmtsContext typeBody,
1108             final SchemaPath actualPath, final QName moduleQName, final Builder parent) {
1109
1110         final String moduleName = parent.getModuleName();
1111         final int line = typeBody.getStart().getLine();
1112         TypeDefinition<?> baseType = null;
1113
1114         Integer fractionDigits = getFractionDigits(typeBody, moduleName);
1115         List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleName);
1116         List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1117         List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleName);
1118
1119         TypeConstraints constraints = new TypeConstraints(moduleName, line);
1120         constraints.addFractionDigits(fractionDigits);
1121         constraints.addLengths(lengthStatements);
1122         constraints.addPatterns(patternStatements);
1123         constraints.addRanges(rangeStatements);
1124
1125         SchemaPath baseTypePath = createBaseTypePath(actualPath, typeName);
1126         SchemaPath extBaseTypePath = createExtendedBaseTypePath(actualPath, moduleQName, typeName);
1127
1128         if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1129             extBaseTypePath = baseTypePath;
1130         }
1131
1132         if ("decimal64".equals(typeName)) {
1133             if (rangeStatements.isEmpty()) {
1134                 try {
1135                     return Decimal64.create(baseTypePath, fractionDigits);
1136                 } catch(Exception e) {
1137                     throw new YangParseException(moduleName, line, e.getMessage());
1138                 }
1139             }
1140             Decimal64 decimalType = Decimal64.create(extBaseTypePath, fractionDigits);
1141             constraints.addRanges(decimalType.getRangeConstraints());
1142             baseType = decimalType;
1143         } else if (typeName.startsWith("int")) {
1144             IntegerTypeDefinition intType = null;
1145             switch (typeName) {
1146             case "int8":
1147                 intType = Int8.getInstance();
1148                 break;
1149             case "int16":
1150                 intType = Int16.getInstance();
1151                 break;
1152             case "int32":
1153                 intType = Int32.getInstance();
1154                 break;
1155             case "int64":
1156                 intType = Int64.getInstance();
1157                 break;
1158             }
1159             if (intType == null) {
1160                 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1161             }
1162             constraints.addRanges(intType.getRangeConstraints());
1163             baseType = intType;
1164         } else if (typeName.startsWith("uint")) {
1165             UnsignedIntegerTypeDefinition uintType = null;
1166             switch (typeName) {
1167             case "uint8":
1168                 uintType = Uint8.getInstance();
1169                 break;
1170             case "uint16":
1171                 uintType = Uint16.getInstance();
1172                 break;
1173             case "uint32":
1174                 uintType = Uint32.getInstance();
1175                 break;
1176             case "uint64":
1177                 uintType = Uint64.getInstance();
1178                 break;
1179             }
1180             if (uintType == null) {
1181                 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1182             }
1183             constraints.addRanges(uintType.getRangeConstraints());
1184             baseType = uintType;
1185         } else if ("enumeration".equals(typeName)) {
1186             List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, moduleName);
1187             return EnumerationType.create(baseTypePath, enumConstants, Optional.<EnumPair> absent());
1188         } else if ("string".equals(typeName)) {
1189             StringTypeDefinition stringType = StringType.getInstance();
1190             constraints.addLengths(stringType.getLengthConstraints());
1191             baseType = stringType;
1192         } else if ("bits".equals(typeName)) {
1193             return BitsType.create(baseTypePath, getBits(typeBody, actualPath, moduleName));
1194         } else if ("leafref".equals(typeName)) {
1195             final String path = parseLeafrefPath(typeBody);
1196             final boolean absolute = path.startsWith("/");
1197             RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path, absolute);
1198             return new Leafref(xpath);
1199         } else if ("binary".equals(typeName)) {
1200             BinaryTypeDefinition binaryType = BinaryType.getInstance();
1201             constraints.addLengths(binaryType.getLengthConstraints());
1202             baseType = binaryType;
1203         } else if ("instance-identifier".equals(typeName)) {
1204             return InstanceIdentifierType.create(isRequireInstance(typeBody));
1205         }
1206
1207         if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1208             TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1209             typedef.setRanges(constraints.getRange());
1210             typedef.setLengths(constraints.getLength());
1211             typedef.setPatterns(constraints.getPatterns());
1212             typedef.setFractionDigits(constraints.getFractionDigits());
1213             return baseType;
1214         }
1215
1216         QName qname = QName.create(moduleQName, typeName);
1217         SchemaPath schemaPath = actualPath.createChild(qname);
1218         final Optional<String> opt = Optional.of("");
1219         ExtendedType.Builder typeBuilder = ExtendedType.builder(qname, baseType, opt, opt, schemaPath);
1220
1221         typeBuilder.ranges(constraints.getRange());
1222         typeBuilder.lengths(constraints.getLength());
1223         typeBuilder.patterns(constraints.getPatterns());
1224         typeBuilder.fractionDigits(constraints.getFractionDigits());
1225
1226         return typeBuilder.build();
1227     }
1228
1229     private static SchemaPath createTypePath(final SchemaPath actual, final String typeName) {
1230         QName last = actual.getLastComponent();
1231         return actual.createChild(QName.create(last, typeName));
1232     }
1233
1234     private static SchemaPath createBaseTypePath(final SchemaPath actual, final String typeName) {
1235         return actual.createChild(BaseTypes.constructQName(typeName));
1236     }
1237
1238     private static SchemaPath createExtendedBaseTypePath(final SchemaPath actual, final QName moduleQName, final String typeName) {
1239         return actual.createChild(
1240                 QName.create(moduleQName, typeName),
1241                 BaseTypes.constructQName(typeName));
1242     }
1243
1244     /**
1245      * Parse given context and find identityref base value.
1246      *
1247      * @param ctx
1248      *            type body
1249      * @return identityref base value as String
1250      */
1251     public static String getIdentityrefBase(final Type_body_stmtsContext ctx) {
1252         String result = null;
1253         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1254             ParseTree child = ctx.getChild(i);
1255             if (child instanceof Identityref_specificationContext) {
1256                 for (int j = 0; j < child.getChildCount(); j++) {
1257                     ParseTree baseArg = child.getChild(j);
1258                     if (baseArg instanceof Base_stmtContext) {
1259                         result = stringFromNode(baseArg);
1260                         break outer;
1261                     }
1262                 }
1263             }
1264         }
1265         return result;
1266     }
1267
1268     /**
1269      * Parse type body statement and find require-instance value.
1270      *
1271      * @param ctx
1272      *            type body context
1273      * @return require-instance value
1274      */
1275     private static boolean isRequireInstance(final Type_body_stmtsContext ctx) {
1276         for (int i = 0; i < ctx.getChildCount(); i++) {
1277             ParseTree child = ctx.getChild(i);
1278             if (child instanceof Instance_identifier_specificationContext) {
1279                 for (int j = 0; j < child.getChildCount(); j++) {
1280                     ParseTree reqStmt = child.getChild(j);
1281                     if (reqStmt instanceof Require_instance_stmtContext) {
1282                         for (int k = 0; k < reqStmt.getChildCount(); k++) {
1283                             ParseTree reqArg = reqStmt.getChild(k);
1284                             if (reqArg instanceof Require_instance_argContext) {
1285                                 return Boolean.valueOf(stringFromNode(reqArg));
1286                             }
1287                         }
1288                     }
1289                 }
1290             }
1291         }
1292         return true;
1293     }
1294
1295     /**
1296      * Parse type body statement and find leafref path.
1297      *
1298      * @param ctx
1299      *            type body context
1300      * @return leafref path as String
1301      */
1302     private static String parseLeafrefPath(final Type_body_stmtsContext ctx) {
1303         for (int i = 0; i < ctx.getChildCount(); i++) {
1304             ParseTree child = ctx.getChild(i);
1305             if (child instanceof Leafref_specificationContext) {
1306                 for (int j = 0; j < child.getChildCount(); j++) {
1307                     ParseTree leafRefSpec = child.getChild(j);
1308                     if (leafRefSpec instanceof Path_stmtContext) {
1309                         return stringFromNode(leafRefSpec);
1310                     }
1311                 }
1312             }
1313         }
1314         return null;
1315     }
1316
1317     /**
1318      * Internal helper method for parsing must statement.
1319      *
1320      * @param ctx
1321      *            Must_stmtContext
1322      * @return MustDefinition object based on parsed context
1323      */
1324     private static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1325         StringBuilder mustText = new StringBuilder();
1326         Optional<String> description = Optional.absent();
1327         Optional<String> reference = Optional.absent();
1328         Optional<String> errorAppTag = Optional.absent();
1329         Optional<String> errorMessage = Optional.absent();
1330         for (int i = 0; i < ctx.getChildCount(); ++i) {
1331             ParseTree child = ctx.getChild(i);
1332             if (child instanceof StringContext) {
1333                 final StringContext context = (StringContext) child;
1334                 if (context.getChildCount() == 1) {
1335                     String mustPart = context.getChild(0).getText();
1336                     // trim start and end quotation
1337                     mustText.append(mustPart.substring(1, mustPart.length() - 1));
1338                 } else {
1339                     for (int j = 0; j < context.getChildCount(); j++) {
1340                         String mustPart = context.getChild(j).getText();
1341                         if (j == 0) {
1342                             mustText.append(mustPart.substring(0, mustPart.length() - 1));
1343                             continue;
1344                         }
1345                         if (j % 2 == 0) {
1346                             mustText.append(mustPart.substring(1));
1347                         }
1348                     }
1349                 }
1350             } else if (child instanceof Description_stmtContext) {
1351                 description = Optional.of(stringFromNode(child));
1352             } else if (child instanceof Reference_stmtContext) {
1353                 reference = Optional.of(stringFromNode(child));
1354             } else if (child instanceof Error_app_tag_stmtContext) {
1355                 errorAppTag = Optional.of(stringFromNode(child));
1356             } else if (child instanceof Error_message_stmtContext) {
1357                 errorMessage = Optional.of(stringFromNode(child));
1358             }
1359         }
1360
1361         return MustDefinitionImpl.create(mustText.toString(), description, reference, errorAppTag, errorMessage);
1362     }
1363
1364     /**
1365      * Parse given context and set constraints to constraints builder.
1366      *
1367      * @param ctx
1368      *            context to parse
1369      * @param constraints
1370      *            ConstraintsBuilder to fill
1371      */
1372     public static void parseConstraints(final ParseTree ctx, final ConstraintsBuilder constraints) {
1373         for (int i = 0; i < ctx.getChildCount(); ++i) {
1374             final ParseTree childNode = ctx.getChild(i);
1375             if (childNode instanceof Max_elements_stmtContext) {
1376                 Integer max = parseMaxElements((Max_elements_stmtContext) childNode, constraints.getModuleName());
1377                 constraints.setMaxElements(max);
1378             } else if (childNode instanceof Min_elements_stmtContext) {
1379                 Integer min = parseMinElements((Min_elements_stmtContext) childNode, constraints.getModuleName());
1380                 constraints.setMinElements(min);
1381             } else if (childNode instanceof Must_stmtContext) {
1382                 MustDefinition must = parseMust((Must_stmtContext) childNode);
1383                 constraints.addMustDefinition(must);
1384             } else if (childNode instanceof Mandatory_stmtContext) {
1385                 for (int j = 0; j < childNode.getChildCount(); j++) {
1386                     ParseTree mandatoryTree = childNode.getChild(j);
1387                     if (mandatoryTree instanceof Mandatory_argContext) {
1388                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1389                         constraints.setMandatory(mandatory);
1390                     }
1391                 }
1392             } else if (childNode instanceof When_stmtContext) {
1393                 constraints.addWhenCondition(stringFromNode(childNode));
1394             }
1395         }
1396     }
1397
1398     private static Integer parseMinElements(final Min_elements_stmtContext ctx, final String moduleName) {
1399         Integer result = null;
1400         try {
1401             for (int i = 0; i < ctx.getChildCount(); i++) {
1402                 ParseTree minArg = ctx.getChild(i);
1403                 if (minArg instanceof Min_value_argContext) {
1404                     result = Integer.valueOf(stringFromNode(minArg));
1405                 }
1406             }
1407             if (result == null) {
1408                 throw new IllegalArgumentException();
1409             }
1410             return result;
1411         } catch (Exception e) {
1412             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse min-elements.", e);
1413         }
1414     }
1415
1416     private static Integer parseMaxElements(final Max_elements_stmtContext ctx, final String moduleName) {
1417         Integer result = null;
1418         try {
1419             for (int i = 0; i < ctx.getChildCount(); i++) {
1420                 ParseTree maxArg = ctx.getChild(i);
1421                 if (maxArg instanceof Max_value_argContext) {
1422                     String maxValue = stringFromNode(maxArg);
1423                     if ("unbounded".equals(maxValue)) {
1424                         result = Integer.MAX_VALUE;
1425                     } else {
1426                         result = Integer.valueOf(maxValue);
1427                     }
1428                 }
1429             }
1430             if (result == null) {
1431                 throw new IllegalArgumentException();
1432             }
1433             return result;
1434         } catch (Exception e) {
1435             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse max-elements.", e);
1436         }
1437     }
1438
1439     /**
1440      * Parse given context and return yin value.
1441      *
1442      * @param ctx
1443      *            context to parse
1444      * @return true if value is 'true', false otherwise
1445      */
1446     public static boolean parseYinValue(final Argument_stmtContext ctx) {
1447         boolean yinValue = false;
1448         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1449             ParseTree yin = ctx.getChild(i);
1450             if (yin instanceof Yin_element_stmtContext) {
1451                 for (int j = 0; j < yin.getChildCount(); j++) {
1452                     ParseTree yinArg = yin.getChild(j);
1453                     if (yinArg instanceof Yin_element_argContext) {
1454                         String yinString = stringFromNode(yinArg);
1455                         if ("true".equals(yinString)) {
1456                             yinValue = true;
1457                             break outer;
1458                         }
1459                     }
1460                 }
1461             }
1462         }
1463         return yinValue;
1464     }
1465
1466     /**
1467      * Check this base type.
1468      *
1469      * @param typeName
1470      *            base YANG type name
1471      * @param moduleName
1472      *            name of current module
1473      * @param line
1474      *            line in module
1475      * @throws YangParseException
1476      *             if this is one of YANG type which MUST contain additional
1477      *             informations in its body
1478      */
1479     public static void checkMissingBody(final String typeName, final String moduleName, final int line) {
1480         switch (typeName) {
1481         case "decimal64":
1482             throw new YangParseException(moduleName, line,
1483                     "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1484         case "identityref":
1485             throw new YangParseException(moduleName, line,
1486                     "The 'base' statement MUST be present if the type is 'identityref'.");
1487         case "leafref":
1488             throw new YangParseException(moduleName, line,
1489                     "The 'path' statement MUST be present if the type is 'leafref'.");
1490         case "bits":
1491             throw new YangParseException(moduleName, line, "The 'bit' statement MUST be present if the type is 'bits'.");
1492         case "enumeration":
1493             throw new YangParseException(moduleName, line,
1494                     "The 'enum' statement MUST be present if the type is 'enumeration'.");
1495         }
1496     }
1497
1498     /**
1499      * Parse refine statement.
1500      *
1501      * @param refineCtx
1502      *            refine statement
1503      * @param moduleName
1504      *            name of current module
1505      * @return RefineHolder object representing this refine statement
1506      */
1507     public static RefineHolderImpl parseRefine(final Refine_stmtContext refineCtx, final String moduleName) {
1508         final String refineTarget = stringFromNode(refineCtx);
1509         final RefineHolderImpl refine = new RefineHolderImpl(moduleName, refineCtx.getStart().getLine(), refineTarget);
1510         for (int i = 0; i < refineCtx.getChildCount(); i++) {
1511             ParseTree refinePom = refineCtx.getChild(i);
1512             if (refinePom instanceof Refine_pomContext) {
1513                 for (int j = 0; j < refinePom.getChildCount(); j++) {
1514                     ParseTree refineStmt = refinePom.getChild(j);
1515                     parseRefineDefault(refine, refineStmt);
1516
1517                     if (refineStmt instanceof Refine_leaf_stmtsContext) {
1518                         parseRefine(refine, (Refine_leaf_stmtsContext) refineStmt);
1519                     } else if (refineStmt instanceof Refine_container_stmtsContext) {
1520                         parseRefine(refine, (Refine_container_stmtsContext) refineStmt);
1521                     } else if (refineStmt instanceof Refine_list_stmtsContext) {
1522                         parseRefine(refine, (Refine_list_stmtsContext) refineStmt);
1523                     } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1524                         parseRefine(refine, (Refine_leaf_list_stmtsContext) refineStmt);
1525                     } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1526                         parseRefine(refine, (Refine_choice_stmtsContext) refineStmt);
1527                     } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1528                         parseRefine(refine, (Refine_anyxml_stmtsContext) refineStmt);
1529                     }
1530                 }
1531             }
1532         }
1533         return refine;
1534     }
1535
1536     private static void parseRefineDefault(final RefineHolderImpl refine, final ParseTree refineStmt) {
1537         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1538             ParseTree refineArg = refineStmt.getChild(i);
1539             if (refineArg instanceof Description_stmtContext) {
1540                 String description = stringFromNode(refineArg);
1541                 refine.setDescription(description);
1542             } else if (refineArg instanceof Reference_stmtContext) {
1543                 String reference = stringFromNode(refineArg);
1544                 refine.setReference(reference);
1545             } else if (refineArg instanceof Config_stmtContext) {
1546                 Boolean config = parseConfig((Config_stmtContext) refineArg, refine.getModuleName());
1547                 refine.setConfiguration(config);
1548             }
1549         }
1550     }
1551
1552     private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_stmtsContext refineStmt) {
1553         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1554             ParseTree refineArg = refineStmt.getChild(i);
1555             if (refineArg instanceof Default_stmtContext) {
1556                 String defaultStr = stringFromNode(refineArg);
1557                 refine.setDefaultStr(defaultStr);
1558             } else if (refineArg instanceof Mandatory_stmtContext) {
1559                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1560                     ParseTree mandatoryTree = refineArg.getChild(j);
1561                     if (mandatoryTree instanceof Mandatory_argContext) {
1562                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1563                         refine.setMandatory(mandatory);
1564                     }
1565                 }
1566             } else if (refineArg instanceof Must_stmtContext) {
1567                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1568                 refine.setMust(must);
1569
1570             }
1571         }
1572         return refine;
1573     }
1574
1575     private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_container_stmtsContext refineStmt) {
1576         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1577             ParseTree refineArg = refineStmt.getChild(i);
1578             if (refineArg instanceof Must_stmtContext) {
1579                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1580                 refine.setMust(must);
1581             } else if (refineArg instanceof Presence_stmtContext) {
1582                 refine.setPresence(true);
1583             }
1584         }
1585         return refine;
1586     }
1587
1588     private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_list_stmtsContext refineStmt) {
1589         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1590             ParseTree refineArg = refineStmt.getChild(i);
1591             if (refineArg instanceof Must_stmtContext) {
1592                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1593                 refine.setMust(must);
1594             } else if (refineArg instanceof Max_elements_stmtContext) {
1595                 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1596                 refine.setMaxElements(max);
1597             } else if (refineArg instanceof Min_elements_stmtContext) {
1598                 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1599                 refine.setMinElements(min);
1600             }
1601         }
1602         return refine;
1603     }
1604
1605     private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_list_stmtsContext refineStmt) {
1606         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1607             ParseTree refineArg = refineStmt.getChild(i);
1608             if (refineArg instanceof Must_stmtContext) {
1609                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1610                 refine.setMust(must);
1611             } else if (refineArg instanceof Max_elements_stmtContext) {
1612                 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1613                 refine.setMaxElements(max);
1614             } else if (refineArg instanceof Min_elements_stmtContext) {
1615                 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1616                 refine.setMinElements(min);
1617             }
1618         }
1619         return refine;
1620     }
1621
1622     private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_choice_stmtsContext refineStmt) {
1623         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1624             ParseTree refineArg = refineStmt.getChild(i);
1625             if (refineArg instanceof Default_stmtContext) {
1626                 String defaultStr = stringFromNode(refineArg);
1627                 refine.setDefaultStr(defaultStr);
1628             } else if (refineArg instanceof Mandatory_stmtContext) {
1629                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1630                     ParseTree mandatoryTree = refineArg.getChild(j);
1631                     if (mandatoryTree instanceof Mandatory_argContext) {
1632                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1633                         refine.setMandatory(mandatory);
1634                     }
1635                 }
1636             }
1637         }
1638         return refine;
1639     }
1640
1641     private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_anyxml_stmtsContext refineStmt) {
1642         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1643             ParseTree refineArg = refineStmt.getChild(i);
1644             if (refineArg instanceof Must_stmtContext) {
1645                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1646                 refine.setMust(must);
1647             } else if (refineArg instanceof Mandatory_stmtContext) {
1648                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1649                     ParseTree mandatoryTree = refineArg.getChild(j);
1650                     if (mandatoryTree instanceof Mandatory_argContext) {
1651                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1652                         refine.setMandatory(mandatory);
1653                     }
1654                 }
1655             }
1656         }
1657         return refine;
1658     }
1659
1660     public static String getArgumentString(final org.antlr.v4.runtime.ParserRuleContext ctx) {
1661         List<StringContext> potentialValues = ctx.getRuleContexts(StringContext.class);
1662         checkState(!potentialValues.isEmpty());
1663         return ParserListenerUtils.stringFromStringContext(potentialValues.get(0));
1664     }
1665
1666     public static <T extends ParserRuleContext> Optional<T> getFirstContext(final ParserRuleContext context,final Class<T> contextType) {
1667         List<T> potential = context.getRuleContexts(contextType);
1668         if(potential.isEmpty()) {
1669             return Optional.absent();
1670         }
1671         return Optional.of(potential.get(0));
1672     }
1673
1674 }