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