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