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