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