Merge "Fix to feature files to include ietf-yang-types-20130715"
[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 DOUBLE_QUOTE_MATCHER = CharMatcher.is('"');
145     private static final CharMatcher SINGLE_QUOTE_MATCHER = CharMatcher.is('\'');
146
147     private ParserListenerUtils() {
148     }
149
150     /**
151      * Parse given tree and get first string value.
152      *
153      * @param treeNode
154      *            tree to parse
155      * @return first string value from given tree
156      */
157     public static String stringFromNode(final ParseTree treeNode) {
158         String result = "";
159         for (int i = 0; i < treeNode.getChildCount(); ++i) {
160             final ParseTree child = treeNode.getChild(i);
161             if (child instanceof StringContext) {
162                 return stringFromStringContext((StringContext)child);
163             }
164         }
165         return result;
166     }
167
168     private static String stringFromStringContext(final StringContext context) {
169         StringBuilder sb = new StringBuilder();
170         for (TerminalNode stringNode : context.STRING()) {
171             final String str = stringNode.getText();
172             char firstChar = str.charAt(0);
173             final CharMatcher quoteMatcher;
174             if(SINGLE_QUOTE_MATCHER.matches(firstChar)) {
175                 quoteMatcher = SINGLE_QUOTE_MATCHER;
176             } else if (DOUBLE_QUOTE_MATCHER.matches(firstChar)) {
177                 quoteMatcher = DOUBLE_QUOTE_MATCHER;
178             } else {
179                 sb.append(str);
180                 continue;
181             }
182             /*
183              *
184              * It is safe not to check last argument to be same
185              * grammars enforces that.
186              *
187              * FIXME: Introduce proper escaping and translation of escaped
188              * characters here.
189              *
190              */
191             sb.append(quoteMatcher.removeFrom(str.substring(1, str.length()-1)));
192         }
193         return sb.toString();
194     }
195
196     private static String getParentModule(final ParseTree ctx) {
197         ParseTree current = ctx;
198         while (current != null && !(current instanceof Module_stmtContext)) {
199             current = current.getParent();
200         }
201         if (current != null) {
202             Module_stmtContext module = (Module_stmtContext) current;
203             for (int i = 0; i < module.getChildCount(); i++) {
204                 if (module.getChild(i) instanceof StringContext) {
205                     final StringContext str = (StringContext) module.getChild(i);
206                     return str.getChild(0).getText();
207                 }
208             }
209         }
210         return "";
211     }
212
213     /**
214      * Parse 'description', 'reference' and 'status' statements and fill in
215      * given builder.
216      *
217      * @param ctx
218      *            context to parse
219      * @param builder
220      *            builder to fill in with parsed statements
221      */
222     public static void parseSchemaNodeArgs(final ParseTree ctx, final SchemaNodeBuilder builder) {
223         for (int i = 0; i < ctx.getChildCount(); i++) {
224             final ParseTree child = ctx.getChild(i);
225             if (child instanceof Description_stmtContext) {
226                 final String desc = stringFromNode(child);
227                 builder.setDescription(desc);
228             } else if (child instanceof Reference_stmtContext) {
229                 final String ref = stringFromNode(child);
230                 builder.setReference(ref);
231             } else if (child instanceof Status_stmtContext) {
232                 final Status status = parseStatus((Status_stmtContext) child);
233                 builder.setStatus(status);
234             }
235         }
236     }
237
238     /**
239      * Parse given context and return its value;
240      *
241      * @param ctx
242      *            status context
243      * @return value parsed from context
244      */
245     public static Status parseStatus(final Status_stmtContext ctx) {
246         Status result = null;
247         for (int i = 0; i < ctx.getChildCount(); i++) {
248             ParseTree statusArg = ctx.getChild(i);
249             if (statusArg instanceof Status_argContext) {
250                 String statusArgStr = stringFromNode(statusArg);
251                 switch (statusArgStr) {
252                 case "current":
253                     result = Status.CURRENT;
254                     break;
255                 case "deprecated":
256                     result = Status.DEPRECATED;
257                     break;
258                 case "obsolete":
259                     result = Status.OBSOLETE;
260                     break;
261                 default:
262                     LOG.warn("Invalid 'status' statement: " + statusArgStr);
263                 }
264             }
265         }
266         return result;
267     }
268
269     /**
270      * Parse given tree and returns units statement as string.
271      *
272      * @param ctx
273      *            context to parse
274      * @return value of units statement as string or null if there is no units
275      *         statement
276      */
277     public static String parseUnits(final ParseTree ctx) {
278         for (int i = 0; i < ctx.getChildCount(); i++) {
279             ParseTree child = ctx.getChild(i);
280             if (child instanceof Units_stmtContext) {
281                 return stringFromNode(child);
282             }
283         }
284         return null;
285     }
286
287     /**
288      * Parse given tree and returns default statement as string.
289      *
290      * @param ctx
291      *            context to parse
292      * @return value of default statement as string or null if there is no
293      *         default statement
294      */
295     public static String parseDefault(final ParseTree ctx) {
296         for (int i = 0; i < ctx.getChildCount(); i++) {
297             ParseTree child = ctx.getChild(i);
298             if (child instanceof Default_stmtContext) {
299                 return stringFromNode(child);
300             }
301         }
302         return null;
303     }
304
305     /**
306      * Create java.util.List of key node names.
307      *
308      * @param ctx
309      *            Key_stmtContext context
310      * @return YANG list key as java.util.List of key node names
311      */
312     public static List<String> createListKey(final Key_stmtContext ctx) {
313         String keyDefinition = stringFromNode(ctx);
314         return Lists.newArrayList(KEYDEF_SPLITTER.split(keyDefinition));
315     }
316
317     /**
318      * Parse given type body of enumeration statement.
319      *
320      * @param ctx
321      *            type body context to parse
322      * @param path
323      *            actual position in YANG model
324      * @param moduleName
325      *            current module name
326      * @return List of EnumPair object parsed from given context
327      */
328     private static List<EnumTypeDefinition.EnumPair> getEnumConstants(final Type_body_stmtsContext ctx,
329             final SchemaPath path, final String moduleName) {
330         List<EnumTypeDefinition.EnumPair> enumConstants = new ArrayList<>();
331
332         for (int i = 0; i < ctx.getChildCount(); i++) {
333             ParseTree enumSpecChild = ctx.getChild(i);
334             if (enumSpecChild instanceof Enum_specificationContext) {
335                 int highestValue = -1;
336                 for (int j = 0; j < enumSpecChild.getChildCount(); j++) {
337                     ParseTree enumChild = enumSpecChild.getChild(j);
338                     if (enumChild instanceof Enum_stmtContext) {
339                         EnumPair enumPair = createEnumPair((Enum_stmtContext) enumChild, highestValue, path, moduleName);
340                         if (enumPair.getValue() > highestValue) {
341                             highestValue = enumPair.getValue();
342                         }
343                         enumConstants.add(enumPair);
344                     }
345                 }
346             }
347         }
348         return enumConstants;
349     }
350
351     /**
352      * Parse enum statement context
353      *
354      * @param ctx
355      *            enum statement context
356      * @param highestValue
357      *            current highest value in enumeration
358      * @param actualPath
359      *            actual position in YANG model
360      * @param moduleName
361      *            current module name
362      * @return EnumPair object parsed from given context
363      */
364     private static EnumTypeDefinition.EnumPair createEnumPair(final Enum_stmtContext ctx, final int highestValue,
365             final SchemaPath actualPath, final String moduleName) {
366         final String name = stringFromNode(ctx);
367         SchemaPath path = createTypePath(actualPath, name);
368         Integer value = null;
369
370         String description = null;
371         String reference = null;
372         Status status = null;
373
374         for (int i = 0; i < ctx.getChildCount(); i++) {
375             ParseTree child = ctx.getChild(i);
376             if (child instanceof Value_stmtContext) {
377                 String valueStr = stringFromNode(child);
378                 try {
379                     // yang enum value has same restrictions as JAVA Integer
380                     value = Integer.valueOf(valueStr);
381                 } catch (NumberFormatException e) {
382                     String err = String
383                             .format("Error on enum '%s': the enum value MUST be in the range from -2147483648 to 2147483647, but was: %s",
384                                     name, valueStr);
385                     throw new YangParseException(moduleName, ctx.getStart().getLine(), err, e);
386                 }
387             } else if (child instanceof Description_stmtContext) {
388                 description = stringFromNode(child);
389             } else if (child instanceof Reference_stmtContext) {
390                 reference = stringFromNode(child);
391             } else if (child instanceof Status_stmtContext) {
392                 status = parseStatus((Status_stmtContext) child);
393             }
394         }
395
396         if (value == null) {
397             value = highestValue + 1;
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 unknown type with body.
1040      *
1041      * @param typeBody
1042      *            type body
1043      * @param parent
1044      *            current node parent
1045      * @param prefixedQName
1046      *            type qname with prefix
1047      * @param moduleBuilder
1048      *            current module builder
1049      * @param moduleQName
1050      *            current module qname
1051      * @param actualPath
1052      *            actual path in model
1053      */
1054     public static void parseUnknownTypeWithBody(Type_body_stmtsContext typeBody, TypeAwareBuilder parent,
1055             QName prefixedQName, ModuleBuilder moduleBuilder, QName moduleQName, SchemaPath actualPath) {
1056         final int line = typeBody.getStart().getLine();
1057
1058         List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleBuilder.getName());
1059         List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleBuilder.getName());
1060         List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1061         Integer fractionDigits = getFractionDigits(typeBody, moduleBuilder.getName());
1062
1063         if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1064             TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1065             typedef.setRanges(rangeStatements);
1066             typedef.setLengths(lengthStatements);
1067             typedef.setPatterns(patternStatements);
1068             typedef.setFractionDigits(fractionDigits);
1069             typedef.setTypeQName(prefixedQName);
1070             // add parent node of this type statement to dirty nodes
1071             moduleBuilder.markActualNodeDirty();
1072         } else {
1073             QName qname = QName.create(moduleQName, prefixedQName.getLocalName());
1074             SchemaPath schemaPath = createTypePath(actualPath, prefixedQName.getLocalName());
1075             TypeDefinitionBuilder typeBuilder = new TypeDefinitionBuilderImpl(moduleBuilder.getName(), line, qname, schemaPath);
1076             typeBuilder.setRanges(rangeStatements);
1077             typeBuilder.setLengths(lengthStatements);
1078             typeBuilder.setPatterns(patternStatements);
1079             typeBuilder.setFractionDigits(fractionDigits);
1080             typeBuilder.setTypeQName(prefixedQName);
1081             parent.setTypedef(typeBuilder);
1082             moduleBuilder.getDirtyNodes().add(typeBuilder);
1083         }
1084     }
1085
1086     /**
1087      * Create TypeDefinition object based on given type name and type body.
1088      *
1089      * @param typeName
1090      *            name of type
1091      * @param typeBody
1092      *            type body context
1093      * @param actualPath
1094      *            current path in schema
1095      * @param moduleQName
1096      *            current module qname
1097      * @param parent
1098      *            parent builder
1099      * @return TypeDefinition object based on parsed values.
1100      */
1101     public static TypeDefinition<?> parseTypeWithBody(final String typeName, final Type_body_stmtsContext typeBody,
1102             final SchemaPath actualPath, final QName moduleQName, final Builder parent) {
1103
1104         final String moduleName = parent.getModuleName();
1105         final int line = typeBody.getStart().getLine();
1106         TypeDefinition<?> baseType = null;
1107
1108         Integer fractionDigits = getFractionDigits(typeBody, moduleName);
1109         List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody, moduleName);
1110         List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
1111         List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody, moduleName);
1112
1113         TypeConstraints constraints = new TypeConstraints(moduleName, line);
1114         constraints.addFractionDigits(fractionDigits);
1115         constraints.addLengths(lengthStatements);
1116         constraints.addPatterns(patternStatements);
1117         constraints.addRanges(rangeStatements);
1118
1119         SchemaPath baseTypePath = createBaseTypePath(actualPath, typeName);
1120         SchemaPath extBaseTypePath = createExtendedBaseTypePath(actualPath, moduleQName, typeName);
1121
1122         if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1123             extBaseTypePath = baseTypePath;
1124         }
1125
1126         if ("decimal64".equals(typeName)) {
1127             if (rangeStatements.isEmpty()) {
1128                 try {
1129                     return Decimal64.create(baseTypePath, fractionDigits);
1130                 } catch(Exception e) {
1131                     throw new YangParseException(moduleName, line, e.getMessage());
1132                 }
1133             }
1134             Decimal64 decimalType = Decimal64.create(extBaseTypePath, fractionDigits);
1135             constraints.addRanges(decimalType.getRangeConstraints());
1136             baseType = decimalType;
1137         } else if (typeName.startsWith("int")) {
1138             IntegerTypeDefinition intType = null;
1139             switch (typeName) {
1140             case "int8":
1141                 intType = Int8.getInstance();
1142                 break;
1143             case "int16":
1144                 intType = Int16.getInstance();
1145                 break;
1146             case "int32":
1147                 intType = Int32.getInstance();
1148                 break;
1149             case "int64":
1150                 intType = Int64.getInstance();
1151                 break;
1152             }
1153             if (intType == null) {
1154                 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1155             }
1156             constraints.addRanges(intType.getRangeConstraints());
1157             baseType = intType;
1158         } else if (typeName.startsWith("uint")) {
1159             UnsignedIntegerTypeDefinition uintType = null;
1160             switch (typeName) {
1161             case "uint8":
1162                 uintType = Uint8.getInstance();
1163                 break;
1164             case "uint16":
1165                 uintType = Uint16.getInstance();
1166                 break;
1167             case "uint32":
1168                 uintType = Uint32.getInstance();
1169                 break;
1170             case "uint64":
1171                 uintType = Uint64.getInstance();
1172                 break;
1173             }
1174             if (uintType == null) {
1175                 throw new YangParseException(moduleName, line, "Unknown yang type " + typeName);
1176             }
1177             constraints.addRanges(uintType.getRangeConstraints());
1178             baseType = uintType;
1179         } else if ("enumeration".equals(typeName)) {
1180             List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, moduleName);
1181             return EnumerationType.create(baseTypePath, enumConstants, Optional.<EnumPair> absent());
1182         } else if ("string".equals(typeName)) {
1183             StringTypeDefinition stringType = StringType.getInstance();
1184             constraints.addLengths(stringType.getLengthConstraints());
1185             baseType = stringType;
1186         } else if ("bits".equals(typeName)) {
1187             return BitsType.create(baseTypePath, getBits(typeBody, actualPath, moduleName));
1188         } else if ("leafref".equals(typeName)) {
1189             final String path = parseLeafrefPath(typeBody);
1190             final boolean absolute = path.startsWith("/");
1191             RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path, absolute);
1192             return new Leafref(xpath);
1193         } else if ("binary".equals(typeName)) {
1194             BinaryTypeDefinition binaryType = BinaryType.getInstance();
1195             constraints.addLengths(binaryType.getLengthConstraints());
1196             baseType = binaryType;
1197         } else if ("instance-identifier".equals(typeName)) {
1198             return InstanceIdentifierType.create(isRequireInstance(typeBody));
1199         }
1200
1201         if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
1202             TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
1203             typedef.setRanges(constraints.getRange());
1204             typedef.setLengths(constraints.getLength());
1205             typedef.setPatterns(constraints.getPatterns());
1206             typedef.setFractionDigits(constraints.getFractionDigits());
1207             return baseType;
1208         }
1209
1210         QName qname = QName.create(moduleQName, typeName);
1211         SchemaPath schemaPath = actualPath.createChild(qname);
1212         final Optional<String> opt = Optional.of("");
1213         ExtendedType.Builder typeBuilder = ExtendedType.builder(qname, baseType, opt, opt, schemaPath);
1214
1215         typeBuilder.ranges(constraints.getRange());
1216         typeBuilder.lengths(constraints.getLength());
1217         typeBuilder.patterns(constraints.getPatterns());
1218         typeBuilder.fractionDigits(constraints.getFractionDigits());
1219
1220         return typeBuilder.build();
1221     }
1222
1223     private static SchemaPath createTypePath(final SchemaPath actual, final String typeName) {
1224         QName last = actual.getLastComponent();
1225         return actual.createChild(QName.create(last, typeName));
1226     }
1227
1228     private static SchemaPath createBaseTypePath(final SchemaPath actual, final String typeName) {
1229         return actual.createChild(BaseTypes.constructQName(typeName));
1230     }
1231
1232     private static SchemaPath createExtendedBaseTypePath(final SchemaPath actual, final QName moduleQName, final String typeName) {
1233         return actual.createChild(
1234                 QName.create(moduleQName, typeName),
1235                 BaseTypes.constructQName(typeName));
1236     }
1237
1238     /**
1239      * Parse given context and find identityref base value.
1240      *
1241      * @param ctx
1242      *            type body
1243      * @return identityref base value as String
1244      */
1245     public static String getIdentityrefBase(final Type_body_stmtsContext ctx) {
1246         String result = null;
1247         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1248             ParseTree child = ctx.getChild(i);
1249             if (child instanceof Identityref_specificationContext) {
1250                 for (int j = 0; j < child.getChildCount(); j++) {
1251                     ParseTree baseArg = child.getChild(j);
1252                     if (baseArg instanceof Base_stmtContext) {
1253                         result = stringFromNode(baseArg);
1254                         break outer;
1255                     }
1256                 }
1257             }
1258         }
1259         return result;
1260     }
1261
1262     /**
1263      * Parse type body statement and find require-instance value.
1264      *
1265      * @param ctx
1266      *            type body context
1267      * @return require-instance value
1268      */
1269     private static boolean isRequireInstance(final Type_body_stmtsContext ctx) {
1270         for (int i = 0; i < ctx.getChildCount(); i++) {
1271             ParseTree child = ctx.getChild(i);
1272             if (child instanceof Instance_identifier_specificationContext) {
1273                 for (int j = 0; j < child.getChildCount(); j++) {
1274                     ParseTree reqStmt = child.getChild(j);
1275                     if (reqStmt instanceof Require_instance_stmtContext) {
1276                         for (int k = 0; k < reqStmt.getChildCount(); k++) {
1277                             ParseTree reqArg = reqStmt.getChild(k);
1278                             if (reqArg instanceof Require_instance_argContext) {
1279                                 return Boolean.valueOf(stringFromNode(reqArg));
1280                             }
1281                         }
1282                     }
1283                 }
1284             }
1285         }
1286         return true;
1287     }
1288
1289     /**
1290      * Parse type body statement and find leafref path.
1291      *
1292      * @param ctx
1293      *            type body context
1294      * @return leafref path as String
1295      */
1296     private static String parseLeafrefPath(final Type_body_stmtsContext ctx) {
1297         for (int i = 0; i < ctx.getChildCount(); i++) {
1298             ParseTree child = ctx.getChild(i);
1299             if (child instanceof Leafref_specificationContext) {
1300                 for (int j = 0; j < child.getChildCount(); j++) {
1301                     ParseTree leafRefSpec = child.getChild(j);
1302                     if (leafRefSpec instanceof Path_stmtContext) {
1303                         return stringFromNode(leafRefSpec);
1304                     }
1305                 }
1306             }
1307         }
1308         return null;
1309     }
1310
1311     /**
1312      * Internal helper method for parsing must statement.
1313      *
1314      * @param ctx
1315      *            Must_stmtContext
1316      * @return MustDefinition object based on parsed context
1317      */
1318     private static MustDefinition parseMust(final YangParser.Must_stmtContext ctx) {
1319         StringBuilder mustText = new StringBuilder();
1320         Optional<String> description = Optional.absent();
1321         Optional<String> reference = Optional.absent();
1322         Optional<String> errorAppTag = Optional.absent();
1323         Optional<String> errorMessage = Optional.absent();
1324         for (int i = 0; i < ctx.getChildCount(); ++i) {
1325             ParseTree child = ctx.getChild(i);
1326             if (child instanceof StringContext) {
1327                 final StringContext context = (StringContext) child;
1328                 if (context.getChildCount() == 1) {
1329                     String mustPart = context.getChild(0).getText();
1330                     // trim start and end quotation
1331                     mustText.append(mustPart.substring(1, mustPart.length() - 1));
1332                 } else {
1333                     for (int j = 0; j < context.getChildCount(); j++) {
1334                         String mustPart = context.getChild(j).getText();
1335                         if (j == 0) {
1336                             mustText.append(mustPart.substring(0, mustPart.length() - 1));
1337                             continue;
1338                         }
1339                         if (j % 2 == 0) {
1340                             mustText.append(mustPart.substring(1));
1341                         }
1342                     }
1343                 }
1344             } else if (child instanceof Description_stmtContext) {
1345                 description = Optional.of(stringFromNode(child));
1346             } else if (child instanceof Reference_stmtContext) {
1347                 reference = Optional.of(stringFromNode(child));
1348             } else if (child instanceof Error_app_tag_stmtContext) {
1349                 errorAppTag = Optional.of(stringFromNode(child));
1350             } else if (child instanceof Error_message_stmtContext) {
1351                 errorMessage = Optional.of(stringFromNode(child));
1352             }
1353         }
1354
1355         return MustDefinitionImpl.create(mustText.toString(), description, reference, errorAppTag, errorMessage);
1356     }
1357
1358     /**
1359      * Parse given context and set constraints to constraints builder.
1360      *
1361      * @param ctx
1362      *            context to parse
1363      * @param constraints
1364      *            ConstraintsBuilder to fill
1365      */
1366     public static void parseConstraints(final ParseTree ctx, final ConstraintsBuilder constraints) {
1367         for (int i = 0; i < ctx.getChildCount(); ++i) {
1368             final ParseTree childNode = ctx.getChild(i);
1369             if (childNode instanceof Max_elements_stmtContext) {
1370                 Integer max = parseMaxElements((Max_elements_stmtContext) childNode, constraints.getModuleName());
1371                 constraints.setMaxElements(max);
1372             } else if (childNode instanceof Min_elements_stmtContext) {
1373                 Integer min = parseMinElements((Min_elements_stmtContext) childNode, constraints.getModuleName());
1374                 constraints.setMinElements(min);
1375             } else if (childNode instanceof Must_stmtContext) {
1376                 MustDefinition must = parseMust((Must_stmtContext) childNode);
1377                 constraints.addMustDefinition(must);
1378             } else if (childNode instanceof Mandatory_stmtContext) {
1379                 for (int j = 0; j < childNode.getChildCount(); j++) {
1380                     ParseTree mandatoryTree = childNode.getChild(j);
1381                     if (mandatoryTree instanceof Mandatory_argContext) {
1382                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1383                         constraints.setMandatory(mandatory);
1384                     }
1385                 }
1386             } else if (childNode instanceof When_stmtContext) {
1387                 constraints.addWhenCondition(stringFromNode(childNode));
1388             }
1389         }
1390     }
1391
1392     private static Integer parseMinElements(final Min_elements_stmtContext ctx, final String moduleName) {
1393         Integer result = null;
1394         try {
1395             for (int i = 0; i < ctx.getChildCount(); i++) {
1396                 ParseTree minArg = ctx.getChild(i);
1397                 if (minArg instanceof Min_value_argContext) {
1398                     result = Integer.valueOf(stringFromNode(minArg));
1399                 }
1400             }
1401             if (result == null) {
1402                 throw new IllegalArgumentException();
1403             }
1404             return result;
1405         } catch (Exception e) {
1406             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse min-elements.", e);
1407         }
1408     }
1409
1410     private static Integer parseMaxElements(final Max_elements_stmtContext ctx, final String moduleName) {
1411         Integer result = null;
1412         try {
1413             for (int i = 0; i < ctx.getChildCount(); i++) {
1414                 ParseTree maxArg = ctx.getChild(i);
1415                 if (maxArg instanceof Max_value_argContext) {
1416                     String maxValue = stringFromNode(maxArg);
1417                     if ("unbounded".equals(maxValue)) {
1418                         result = Integer.MAX_VALUE;
1419                     } else {
1420                         result = Integer.valueOf(maxValue);
1421                     }
1422                 }
1423             }
1424             if (result == null) {
1425                 throw new IllegalArgumentException();
1426             }
1427             return result;
1428         } catch (Exception e) {
1429             throw new YangParseException(moduleName, ctx.getStart().getLine(), "Failed to parse max-elements.", e);
1430         }
1431     }
1432
1433     /**
1434      * Parse given context and return yin value.
1435      *
1436      * @param ctx
1437      *            context to parse
1438      * @return true if value is 'true', false otherwise
1439      */
1440     public static boolean parseYinValue(final Argument_stmtContext ctx) {
1441         boolean yinValue = false;
1442         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
1443             ParseTree yin = ctx.getChild(i);
1444             if (yin instanceof Yin_element_stmtContext) {
1445                 for (int j = 0; j < yin.getChildCount(); j++) {
1446                     ParseTree yinArg = yin.getChild(j);
1447                     if (yinArg instanceof Yin_element_argContext) {
1448                         String yinString = stringFromNode(yinArg);
1449                         if ("true".equals(yinString)) {
1450                             yinValue = true;
1451                             break outer;
1452                         }
1453                     }
1454                 }
1455             }
1456         }
1457         return yinValue;
1458     }
1459
1460     /**
1461      * Check this base type.
1462      *
1463      * @param typeName
1464      *            base YANG type name
1465      * @param moduleName
1466      *            name of current module
1467      * @param line
1468      *            line in module
1469      * @throws YangParseException
1470      *             if this is one of YANG type which MUST contain additional
1471      *             informations in its body
1472      */
1473     public static void checkMissingBody(final String typeName, final String moduleName, final int line) {
1474         switch (typeName) {
1475         case "decimal64":
1476             throw new YangParseException(moduleName, line,
1477                     "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
1478         case "identityref":
1479             throw new YangParseException(moduleName, line,
1480                     "The 'base' statement MUST be present if the type is 'identityref'.");
1481         case "leafref":
1482             throw new YangParseException(moduleName, line,
1483                     "The 'path' statement MUST be present if the type is 'leafref'.");
1484         case "bits":
1485             throw new YangParseException(moduleName, line, "The 'bit' statement MUST be present if the type is 'bits'.");
1486         case "enumeration":
1487             throw new YangParseException(moduleName, line,
1488                     "The 'enum' statement MUST be present if the type is 'enumeration'.");
1489         }
1490     }
1491
1492     /**
1493      * Parse refine statement.
1494      *
1495      * @param refineCtx
1496      *            refine statement
1497      * @param moduleName
1498      *            name of current module
1499      * @return RefineHolder object representing this refine statement
1500      */
1501     public static RefineHolderImpl parseRefine(final Refine_stmtContext refineCtx, final String moduleName) {
1502         final String refineTarget = stringFromNode(refineCtx);
1503         final RefineHolderImpl refine = new RefineHolderImpl(moduleName, refineCtx.getStart().getLine(), refineTarget);
1504         for (int i = 0; i < refineCtx.getChildCount(); i++) {
1505             ParseTree refinePom = refineCtx.getChild(i);
1506             if (refinePom instanceof Refine_pomContext) {
1507                 for (int j = 0; j < refinePom.getChildCount(); j++) {
1508                     ParseTree refineStmt = refinePom.getChild(j);
1509                     parseRefineDefault(refine, refineStmt);
1510
1511                     if (refineStmt instanceof Refine_leaf_stmtsContext) {
1512                         parseRefine(refine, (Refine_leaf_stmtsContext) refineStmt);
1513                     } else if (refineStmt instanceof Refine_container_stmtsContext) {
1514                         parseRefine(refine, (Refine_container_stmtsContext) refineStmt);
1515                     } else if (refineStmt instanceof Refine_list_stmtsContext) {
1516                         parseRefine(refine, (Refine_list_stmtsContext) refineStmt);
1517                     } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
1518                         parseRefine(refine, (Refine_leaf_list_stmtsContext) refineStmt);
1519                     } else if (refineStmt instanceof Refine_choice_stmtsContext) {
1520                         parseRefine(refine, (Refine_choice_stmtsContext) refineStmt);
1521                     } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
1522                         parseRefine(refine, (Refine_anyxml_stmtsContext) refineStmt);
1523                     }
1524                 }
1525             }
1526         }
1527         return refine;
1528     }
1529
1530     private static void parseRefineDefault(final RefineHolderImpl refine, final ParseTree refineStmt) {
1531         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1532             ParseTree refineArg = refineStmt.getChild(i);
1533             if (refineArg instanceof Description_stmtContext) {
1534                 String description = stringFromNode(refineArg);
1535                 refine.setDescription(description);
1536             } else if (refineArg instanceof Reference_stmtContext) {
1537                 String reference = stringFromNode(refineArg);
1538                 refine.setReference(reference);
1539             } else if (refineArg instanceof Config_stmtContext) {
1540                 Boolean config = parseConfig((Config_stmtContext) refineArg, refine.getModuleName());
1541                 refine.setConfiguration(config);
1542             }
1543         }
1544     }
1545
1546     private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_stmtsContext refineStmt) {
1547         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1548             ParseTree refineArg = refineStmt.getChild(i);
1549             if (refineArg instanceof Default_stmtContext) {
1550                 String defaultStr = stringFromNode(refineArg);
1551                 refine.setDefaultStr(defaultStr);
1552             } else if (refineArg instanceof Mandatory_stmtContext) {
1553                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1554                     ParseTree mandatoryTree = refineArg.getChild(j);
1555                     if (mandatoryTree instanceof Mandatory_argContext) {
1556                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1557                         refine.setMandatory(mandatory);
1558                     }
1559                 }
1560             } else if (refineArg instanceof Must_stmtContext) {
1561                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1562                 refine.setMust(must);
1563
1564             }
1565         }
1566         return refine;
1567     }
1568
1569     private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_container_stmtsContext refineStmt) {
1570         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1571             ParseTree refineArg = refineStmt.getChild(i);
1572             if (refineArg instanceof Must_stmtContext) {
1573                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1574                 refine.setMust(must);
1575             } else if (refineArg instanceof Presence_stmtContext) {
1576                 refine.setPresence(true);
1577             }
1578         }
1579         return refine;
1580     }
1581
1582     private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_list_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 Max_elements_stmtContext) {
1589                 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1590                 refine.setMaxElements(max);
1591             } else if (refineArg instanceof Min_elements_stmtContext) {
1592                 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1593                 refine.setMinElements(min);
1594             }
1595         }
1596         return refine;
1597     }
1598
1599     private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_leaf_list_stmtsContext refineStmt) {
1600         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1601             ParseTree refineArg = refineStmt.getChild(i);
1602             if (refineArg instanceof Must_stmtContext) {
1603                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1604                 refine.setMust(must);
1605             } else if (refineArg instanceof Max_elements_stmtContext) {
1606                 Integer max = parseMaxElements((Max_elements_stmtContext) refineArg, refine.getModuleName());
1607                 refine.setMaxElements(max);
1608             } else if (refineArg instanceof Min_elements_stmtContext) {
1609                 Integer min = parseMinElements((Min_elements_stmtContext) refineArg, refine.getModuleName());
1610                 refine.setMinElements(min);
1611             }
1612         }
1613         return refine;
1614     }
1615
1616     private static RefineBuilder parseRefine(final RefineHolderImpl refine, final Refine_choice_stmtsContext refineStmt) {
1617         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1618             ParseTree refineArg = refineStmt.getChild(i);
1619             if (refineArg instanceof Default_stmtContext) {
1620                 String defaultStr = stringFromNode(refineArg);
1621                 refine.setDefaultStr(defaultStr);
1622             } else if (refineArg instanceof Mandatory_stmtContext) {
1623                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1624                     ParseTree mandatoryTree = refineArg.getChild(j);
1625                     if (mandatoryTree instanceof Mandatory_argContext) {
1626                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1627                         refine.setMandatory(mandatory);
1628                     }
1629                 }
1630             }
1631         }
1632         return refine;
1633     }
1634
1635     private static RefineBuilder parseRefine(final RefineBuilder refine, final Refine_anyxml_stmtsContext refineStmt) {
1636         for (int i = 0; i < refineStmt.getChildCount(); i++) {
1637             ParseTree refineArg = refineStmt.getChild(i);
1638             if (refineArg instanceof Must_stmtContext) {
1639                 MustDefinition must = parseMust((Must_stmtContext) refineArg);
1640                 refine.setMust(must);
1641             } else if (refineArg instanceof Mandatory_stmtContext) {
1642                 for (int j = 0; j < refineArg.getChildCount(); j++) {
1643                     ParseTree mandatoryTree = refineArg.getChild(j);
1644                     if (mandatoryTree instanceof Mandatory_argContext) {
1645                         Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
1646                         refine.setMandatory(mandatory);
1647                     }
1648                 }
1649             }
1650         }
1651         return refine;
1652     }
1653
1654     public static String getArgumentString(final org.antlr.v4.runtime.ParserRuleContext ctx) {
1655         List<StringContext> potentialValues = ctx.getRuleContexts(StringContext.class);
1656         checkState(!potentialValues.isEmpty());
1657         return ParserListenerUtils.stringFromStringContext(potentialValues.get(0));
1658     }
1659
1660     public static <T extends ParserRuleContext> Optional<T> getFirstContext(final ParserRuleContext context,final Class<T> contextType) {
1661         List<T> potential = context.getRuleContexts(contextType);
1662         if(potential.isEmpty()) {
1663             return Optional.absent();
1664         }
1665         return Optional.of(potential.get(0));
1666     }
1667
1668 }