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