BUG-1382: eliminate use of QName.getPrefix from yang parser
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / impl / YangParserListenerImpl.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/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.parser.impl;
9
10 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.checkMissingBody;
11 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.createListKey;
12 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.getConfig;
13 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.getIdentityrefBase;
14 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.parseConstraints;
15 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.parseDefault;
16 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.parseRefine;
17 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.parseSchemaNodeArgs;
18 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.parseStatus;
19 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.parseTypeWithBody;
20 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.parseUnits;
21 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.parseUserOrdered;
22 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.parseYinValue;
23 import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.stringFromNode;
24
25 import com.google.common.base.Splitter;
26 import com.google.common.base.Strings;
27 import com.google.common.collect.Iterables;
28 import java.net.URI;
29 import java.text.DateFormat;
30 import java.text.ParseException;
31 import java.text.SimpleDateFormat;
32 import java.util.ArrayList;
33 import java.util.Date;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.TreeMap;
38 import org.antlr.v4.runtime.tree.ParseTree;
39 import org.antlr.v4.runtime.tree.ParseTreeWalker;
40 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
41 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
42 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Base_stmtContext;
43 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Contact_stmtContext;
44 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Container_stmtContext;
45 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Default_stmtContext;
46 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Description_stmtContext;
47 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Deviate_add_stmtContext;
48 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Deviate_delete_stmtContext;
49 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Deviate_not_supported_stmtContext;
50 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Deviate_replace_stmtContext;
51 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Import_stmtContext;
52 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Key_stmtContext;
53 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Leaf_list_stmtContext;
54 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Leaf_stmtContext;
55 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.List_stmtContext;
56 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_header_stmtsContext;
57 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Namespace_stmtContext;
58 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Ordered_by_stmtContext;
59 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Organization_stmtContext;
60 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Prefix_stmtContext;
61 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Presence_stmtContext;
62 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Reference_stmtContext;
63 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Revision_date_stmtContext;
64 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Revision_stmtContext;
65 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Revision_stmtsContext;
66 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Status_stmtContext;
67 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Type_body_stmtsContext;
68 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Units_stmtContext;
69 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.When_stmtContext;
70 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yang_version_stmtContext;
71 import org.opendaylight.yangtools.antlrv4.code.gen.YangParserBaseListener;
72 import org.opendaylight.yangtools.yang.common.QName;
73 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
74 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
75 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
76 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
77 import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
78 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
79 import org.opendaylight.yangtools.yang.parser.builder.api.ExtensionBuilder;
80 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
81 import org.opendaylight.yangtools.yang.parser.builder.api.TypeAwareBuilder;
82 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
83 import org.opendaylight.yangtools.yang.parser.builder.api.UsesNodeBuilder;
84 import org.opendaylight.yangtools.yang.parser.builder.impl.AnyXmlBuilder;
85 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceBuilder;
86 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceCaseBuilder;
87 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
88 import org.opendaylight.yangtools.yang.parser.builder.impl.DeviationBuilder;
89 import org.opendaylight.yangtools.yang.parser.builder.impl.FeatureBuilder;
90 import org.opendaylight.yangtools.yang.parser.builder.impl.IdentitySchemaNodeBuilder;
91 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafListSchemaNodeBuilder;
92 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
93 import org.opendaylight.yangtools.yang.parser.builder.impl.ListSchemaNodeBuilder;
94 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
95 import org.opendaylight.yangtools.yang.parser.builder.impl.NotificationBuilder;
96 import org.opendaylight.yangtools.yang.parser.builder.impl.RefineHolderImpl;
97 import org.opendaylight.yangtools.yang.parser.builder.impl.RpcDefinitionBuilder;
98 import org.opendaylight.yangtools.yang.parser.builder.impl.UnionTypeBuilder;
99 import org.opendaylight.yangtools.yang.parser.builder.impl.UnknownSchemaNodeBuilderImpl;
100 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
103
104
105 public final class YangParserListenerImpl extends YangParserBaseListener {
106     private static final Logger LOG = LoggerFactory.getLogger(YangParserListenerImpl.class);
107     private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings();
108     private static final Splitter COLON_SPLITTER = Splitter.on(':');
109     private static final String AUGMENT_STR = "augment";
110
111     private final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
112     private final SchemaPathStack stack = new SchemaPathStack();
113     private final Map<String, TreeMap<Date, URI>> namespaceContext;
114     private final String sourcePath;
115     private QName moduleQName = new QName(null, new Date(0L), null, "dummy");
116     private ModuleBuilder moduleBuilder;
117     private String moduleName;
118     private int augmentOrder;
119     private String yangModelPrefix;
120
121     public YangParserListenerImpl(final Map<String, TreeMap<Date, URI>> namespaceContext, final String sourcePath) {
122         this.namespaceContext = namespaceContext;
123         this.sourcePath = sourcePath;
124     }
125
126     /**
127      * Create a new instance.
128      *
129      * FIXME: the resulting type needs to be extracted, such that we can reuse
130      *        the "BaseListener" aspect, which need not be exposed to the user.
131      *        Maybe factor out a base class into repo.spi?
132      *
133      * @param namespaceContext
134      * @param sourcePath
135      * @param walker
136      * @param tree
137      * @return
138      */
139     public static YangParserListenerImpl create(final Map<String, TreeMap<Date, URI>> namespaceContext,
140             final String sourcePath, final ParseTreeWalker walker, final ParseTree tree) {
141         final YangParserListenerImpl ret = new YangParserListenerImpl(namespaceContext, sourcePath);
142         walker.walk(ret, tree);
143         return ret;
144     }
145
146
147
148     @Override
149     public void enterModule_stmt(final YangParser.Module_stmtContext ctx) {
150         moduleName = stringFromNode(ctx);
151         LOG.trace("entering module {}", moduleName);
152         enterLog("module", moduleName, 0);
153         stack.push();
154
155         moduleBuilder = new ModuleBuilder(moduleName, sourcePath);
156
157         String description = null;
158         String reference = null;
159         for (int i = 0; i < ctx.getChildCount(); i++) {
160             ParseTree child = ctx.getChild(i);
161             if (child instanceof Description_stmtContext) {
162                 description = stringFromNode(child);
163             } else if (child instanceof Reference_stmtContext) {
164                 reference = stringFromNode(child);
165             } else {
166                 if (description != null && reference != null) {
167                     break;
168                 }
169             }
170         }
171         moduleBuilder.setDescription(description);
172         moduleBuilder.setReference(reference);
173     }
174
175     @Override
176     public void exitModule_stmt(final YangParser.Module_stmtContext ctx) {
177         exitLog("module");
178         stack.pop();
179     }
180
181     @Override
182     public void enterSubmodule_stmt(final YangParser.Submodule_stmtContext ctx) {
183         moduleName = stringFromNode(ctx);
184         LOG.trace("entering submodule {}", moduleName);
185         enterLog("submodule", moduleName, 0);
186         stack.push();
187
188         moduleBuilder = new ModuleBuilder(moduleName, true, sourcePath);
189
190         String description = null;
191         String reference = null;
192         for (int i = 0; i < ctx.getChildCount(); i++) {
193             ParseTree child = ctx.getChild(i);
194             if (child instanceof Description_stmtContext) {
195                 description = stringFromNode(child);
196             } else if (child instanceof Reference_stmtContext) {
197                 reference = stringFromNode(child);
198             } else {
199                 if (description != null && reference != null) {
200                     break;
201                 }
202             }
203         }
204         moduleBuilder.setDescription(description);
205         moduleBuilder.setReference(reference);
206     }
207
208     @Override
209     public void exitSubmodule_stmt(final YangParser.Submodule_stmtContext ctx) {
210         exitLog("submodule");
211         stack.pop();
212     }
213
214     @Override
215     public void enterBelongs_to_stmt(final YangParser.Belongs_to_stmtContext ctx) {
216         moduleBuilder.setBelongsTo(stringFromNode(ctx));
217     }
218
219     @Override
220     public void enterModule_header_stmts(final Module_header_stmtsContext ctx) {
221         enterLog("module_header", "", ctx.getStart().getLine());
222         String yangVersion = null;
223         for (int i = 0; i < ctx.getChildCount(); ++i) {
224             final ParseTree treeNode = ctx.getChild(i);
225             if (treeNode instanceof Namespace_stmtContext) {
226                 final String namespaceStr = stringFromNode(treeNode);
227                 final URI namespace = URI.create(namespaceStr);
228                 this.moduleQName = QName.create(namespace, moduleQName.getRevision(), moduleQName.getLocalName());
229                 moduleBuilder.setQNameModule(moduleQName.getModule());
230                 setLog("namespace", namespaceStr);
231             } else if (treeNode instanceof Prefix_stmtContext) {
232                 yangModelPrefix = stringFromNode(treeNode);
233                 this.moduleQName = QName.create(moduleQName.getModule(), yangModelPrefix, moduleQName.getLocalName());
234                 moduleBuilder.setPrefix(yangModelPrefix);
235                 setLog("prefix", yangModelPrefix);
236             } else if (treeNode instanceof Yang_version_stmtContext) {
237                 yangVersion = stringFromNode(treeNode);
238                 setLog("yang-version", yangVersion);
239             }
240         }
241
242         if (yangVersion == null) {
243             yangVersion = "1";
244         }
245         moduleBuilder.setYangVersion(yangVersion);
246     }
247
248     @Override
249     public void exitModule_header_stmts(final Module_header_stmtsContext ctx) {
250         exitLog("module_header");
251     }
252
253     @Override
254     public void enterMeta_stmts(final YangParser.Meta_stmtsContext ctx) {
255         enterLog("meta_stmt", "", ctx.getStart().getLine());
256         for (int i = 0; i < ctx.getChildCount(); i++) {
257             ParseTree child = ctx.getChild(i);
258             if (child instanceof Organization_stmtContext) {
259                 final String organization = stringFromNode(child);
260                 moduleBuilder.setOrganization(organization);
261                 setLog("organization", organization);
262             } else if (child instanceof Contact_stmtContext) {
263                 final String contact = stringFromNode(child);
264                 moduleBuilder.setContact(contact);
265                 setLog("contact", contact);
266             } else if (child instanceof Description_stmtContext) {
267                 final String description = stringFromNode(child);
268                 moduleBuilder.setDescription(description);
269                 setLog("description", description);
270             } else if (child instanceof Reference_stmtContext) {
271                 final String reference = stringFromNode(child);
272                 moduleBuilder.setReference(reference);
273                 setLog("reference", reference);
274             }
275         }
276     }
277
278     @Override
279     public void exitMeta_stmts(final YangParser.Meta_stmtsContext ctx) {
280         exitLog("meta_stmt");
281     }
282
283     @Override
284     public void enterRevision_stmts(final Revision_stmtsContext ctx) {
285         enterLog("revisions", "", ctx.getStart().getLine());
286         for (int i = 0; i < ctx.getChildCount(); ++i) {
287             final ParseTree treeNode = ctx.getChild(i);
288             if (treeNode instanceof Revision_stmtContext) {
289                 updateRevisionForRevisionStatement(treeNode);
290             }
291         }
292     }
293
294     @Override
295     public void exitRevision_stmts(final Revision_stmtsContext ctx) {
296         exitLog("revisions");
297     }
298
299     private void updateRevisionForRevisionStatement(final ParseTree treeNode) {
300         final String revisionDateStr = stringFromNode(treeNode);
301         try {
302             final Date revisionDate = SIMPLE_DATE_FORMAT.parse(revisionDateStr);
303             if ((revisionDate != null) && (this.moduleQName.getRevision().compareTo(revisionDate) < 0)) {
304                 this.moduleQName = QName.create(moduleQName.getNamespace(), revisionDate, moduleQName.getLocalName());
305                 moduleBuilder.setQNameModule(moduleQName.getModule());
306                 setLog("revision", revisionDate.toString());
307                 for (int i = 0; i < treeNode.getChildCount(); ++i) {
308                     ParseTree child = treeNode.getChild(i);
309                     if (child instanceof Reference_stmtContext) {
310                         moduleBuilder.setReference(stringFromNode(child));
311                     }
312                 }
313             }
314         } catch (ParseException e) {
315             LOG.warn("Failed to parse revision string: {}", revisionDateStr, e);
316         }
317     }
318
319     @Override
320     public void enterImport_stmt(final Import_stmtContext ctx) {
321         final int line = ctx.getStart().getLine();
322         final String importName = stringFromNode(ctx);
323         enterLog("import", importName, line);
324
325         String importPrefix = null;
326         Date importRevision = null;
327
328         for (int i = 0; i < ctx.getChildCount(); ++i) {
329             final ParseTree treeNode = ctx.getChild(i);
330             if (treeNode instanceof Prefix_stmtContext) {
331                 importPrefix = stringFromNode(treeNode);
332             }
333             if (treeNode instanceof Revision_date_stmtContext) {
334                 String importRevisionStr = stringFromNode(treeNode);
335                 try {
336                     importRevision = SIMPLE_DATE_FORMAT.parse(importRevisionStr);
337                 } catch (ParseException e) {
338                     LOG.warn("Failed to parse import revision-date at line {}: {}", line, importRevisionStr, e);
339                 }
340             }
341         }
342         moduleBuilder.addModuleImport(importName, importRevision, importPrefix);
343         LOG.trace("setting import ({}; {}; {})", importName, importRevision, importPrefix);
344     }
345
346     @Override
347     public void exitImport_stmt(final Import_stmtContext ctx) {
348         exitLog("import");
349     }
350
351     @Override
352     public void enterAugment_stmt(final YangParser.Augment_stmtContext ctx) {
353         final int line = ctx.getStart().getLine();
354         final String augmentPath = stringFromNode(ctx);
355         enterLog(AUGMENT_STR, augmentPath, line);
356         stack.push();
357
358         SchemaPath targetPath = parseXPathString(augmentPath, line);
359         AugmentationSchemaBuilder builder = moduleBuilder.addAugment(line, augmentPath, targetPath, augmentOrder++);
360
361         for (int i = 0; i < ctx.getChildCount(); i++) {
362             ParseTree child = ctx.getChild(i);
363             if (child instanceof Description_stmtContext) {
364                 builder.setDescription(stringFromNode(child));
365             } else if (child instanceof Reference_stmtContext) {
366                 builder.setReference(stringFromNode(child));
367             } else if (child instanceof Status_stmtContext) {
368                 builder.setStatus(parseStatus((Status_stmtContext) child));
369             } else if (child instanceof When_stmtContext) {
370                 builder.addWhenCondition(stringFromNode(child));
371             }
372         }
373
374         moduleBuilder.enterNode(builder);
375     }
376
377     @Override
378     public void exitAugment_stmt(final YangParser.Augment_stmtContext ctx) {
379         moduleBuilder.exitNode();
380         exitLog(AUGMENT_STR);
381         stack.pop();
382     }
383
384     @Override
385     public void enterExtension_stmt(final YangParser.Extension_stmtContext ctx) {
386         final int line = ctx.getStart().getLine();
387         final String extName = stringFromNode(ctx);
388         enterLog("extension", extName, line);
389         QName qname = QName.create(moduleQName, extName);
390         SchemaPath path = stack.addNodeToPath(qname);
391
392         ExtensionBuilder builder = moduleBuilder.addExtension(qname, line, path);
393         parseSchemaNodeArgs(ctx, builder);
394
395         String argument = null;
396         boolean yin = false;
397         for (int i = 0; i < ctx.getChildCount(); i++) {
398             ParseTree child = ctx.getChild(i);
399             if (child instanceof Argument_stmtContext) {
400                 argument = stringFromNode(child);
401                 yin = parseYinValue((Argument_stmtContext) child);
402                 break;
403             }
404         }
405         builder.setArgument(argument);
406         builder.setYinElement(yin);
407
408         moduleBuilder.enterNode(builder);
409     }
410
411     @Override
412     public void exitExtension_stmt(final YangParser.Extension_stmtContext ctx) {
413         moduleBuilder.exitNode();
414         exitLog("extension", stack.removeNodeFromPath());
415     }
416
417     @Override
418     public void enterTypedef_stmt(final YangParser.Typedef_stmtContext ctx) {
419         final int line = ctx.getStart().getLine();
420         final String typedefName = stringFromNode(ctx);
421         enterLog("typedef", typedefName, line);
422         QName typedefQName = QName.create(moduleQName, typedefName);
423         SchemaPath path = stack.addNodeToPath(typedefQName);
424
425         TypeDefinitionBuilder builder = moduleBuilder.addTypedef(line, typedefQName, path);
426         parseSchemaNodeArgs(ctx, builder);
427         builder.setUnits(parseUnits(ctx));
428         builder.setDefaultValue(parseDefault(ctx));
429
430         moduleBuilder.enterNode(builder);
431     }
432
433     @Override
434     public void exitTypedef_stmt(final YangParser.Typedef_stmtContext ctx) {
435         moduleBuilder.exitNode();
436         exitLog("typedef", stack.removeNodeFromPath());
437     }
438
439     @Override
440     public void enterType_stmt(final YangParser.Type_stmtContext ctx) {
441         final int line = ctx.getStart().getLine();
442         final String typeName = stringFromNode(ctx);
443         enterLog("type", typeName, line);
444
445         final QName typeQName = parseQName(typeName, line);
446
447         TypeDefinition<?> type;
448         Type_body_stmtsContext typeBody = null;
449         for (int i = 0; i < ctx.getChildCount(); i++) {
450             if (ctx.getChild(i) instanceof Type_body_stmtsContext) {
451                 typeBody = (Type_body_stmtsContext) ctx.getChild(i);
452                 break;
453             }
454         }
455
456         // if this is base yang type...
457         if (BaseTypes.isYangBuildInType(typeName)) {
458             if (typeBody == null) {
459                 // check for types which must have body
460                 checkMissingBody(typeName, moduleName, line);
461                 // if there are no constraints, just grab default base yang type
462                 type = BaseTypes.defaultBaseTypeFor(typeName).orNull();
463                 stack.addNodeToPath(type.getQName());
464                 moduleBuilder.setType(type);
465             } else {
466                 QName qname;
467                 switch (typeName) {
468                 case "union":
469                     qname = BaseTypes.UNION_QNAME;
470                     stack.addNodeToPath(qname);
471                     UnionTypeBuilder unionBuilder = moduleBuilder.addUnionType(line, moduleQName.getModule());
472                     Builder parent = moduleBuilder.getActualNode();
473                     unionBuilder.setParent(parent);
474                     moduleBuilder.enterNode(unionBuilder);
475                     break;
476                 case "identityref":
477                     qname = BaseTypes.IDENTITYREF_QNAME;
478                     SchemaPath path = stack.addNodeToPath(qname);
479                     moduleBuilder.addIdentityrefType(line, path, getIdentityrefBase(typeBody));
480                     break;
481                 default:
482                     type = parseTypeWithBody(typeName, typeBody, stack.currentSchemaPath(), moduleQName,
483                             moduleBuilder.getActualNode());
484                     moduleBuilder.setType(type);
485                     stack.addNodeToPath(type.getQName());
486                 }
487             }
488         } else {
489             TypeAwareBuilder parent = (TypeAwareBuilder) moduleBuilder.getActualNode();
490             if (typeBody == null) {
491                 parent.setTypeQName(typeQName);
492                 moduleBuilder.markActualNodeDirty();
493             } else {
494                 ParserListenerUtils.parseUnknownTypeWithBody(typeBody, parent, typeQName, moduleBuilder,
495                         moduleQName, stack.currentSchemaPath());
496             }
497             stack.addNodeToPath(QName.create(moduleQName.getModule(), typeQName.getLocalName()));
498         }
499     }
500
501     private QName parseQName(final String qnameString, final int line) {
502         final QName qname;
503         if (qnameString.indexOf(':') == -1) {
504             qname = QName.create(moduleQName.getNamespace(), moduleQName.getRevision(), qnameString);
505         } else {
506             final Iterator<String> split = COLON_SPLITTER.split(qnameString).iterator();
507             final String prefix = split.next();
508             final String name = split.next();
509             if (prefix.equals(moduleBuilder.getPrefix())) {
510                 qname = QName.create(moduleQName.getNamespace(), moduleQName.getRevision(), name);
511             } else {
512                 ModuleImport imp = moduleBuilder.getImport(prefix);
513                 if (imp == null) {
514                     LOG.warn("Error in module {} at line {}: No import found with prefix {}", moduleName, line, prefix);
515                     return QName.create(name);
516                 }
517                 Date revision = imp.getRevision();
518                 TreeMap<Date, URI> namespaces = namespaceContext.get(imp.getModuleName());
519                 URI namespace;
520                 if (revision == null) {
521                     revision = namespaces.lastEntry().getKey();
522                     namespace = namespaces.lastEntry().getValue();
523                 } else {
524                     namespace = namespaces.get(revision);
525                 }
526                 qname = QName.create(namespace, revision, name);
527             }
528         }
529         return qname;
530     }
531
532     @Override
533     public void exitType_stmt(final YangParser.Type_stmtContext ctx) {
534         final String typeName = stringFromNode(ctx);
535         if ("union".equals(typeName)) {
536             moduleBuilder.exitNode();
537         }
538         exitLog("type", stack.removeNodeFromPath());
539     }
540
541     @Override
542     public void enterGrouping_stmt(final YangParser.Grouping_stmtContext ctx) {
543         final int line = ctx.getStart().getLine();
544         final String groupName = stringFromNode(ctx);
545         enterLog("grouping", groupName, line);
546         QName groupQName = QName.create(moduleQName, groupName);
547         SchemaPath path = stack.addNodeToPath(groupQName);
548
549         GroupingBuilder builder = moduleBuilder.addGrouping(ctx.getStart().getLine(), groupQName, path);
550         parseSchemaNodeArgs(ctx, builder);
551
552         moduleBuilder.enterNode(builder);
553     }
554
555     @Override
556     public void exitGrouping_stmt(final YangParser.Grouping_stmtContext ctx) {
557         moduleBuilder.exitNode();
558         exitLog("grouping", stack.removeNodeFromPath());
559     }
560
561     @Override
562     public void enterContainer_stmt(final Container_stmtContext ctx) {
563         final int line = ctx.getStart().getLine();
564         final String containerName = stringFromNode(ctx);
565         enterLog("container", containerName, line);
566
567         QName containerQName = QName.create(moduleQName, containerName);
568         SchemaPath path = stack.addNodeToPath(containerQName);
569
570         ContainerSchemaNodeBuilder builder = moduleBuilder.addContainerNode(line, containerQName, path);
571         parseSchemaNodeArgs(ctx, builder);
572         parseConstraints(ctx, builder.getConstraints());
573         builder.setConfiguration(getConfig(ctx, builder, moduleName, line));
574
575         for (int i = 0; i < ctx.getChildCount(); ++i) {
576             final ParseTree childNode = ctx.getChild(i);
577             if (childNode instanceof Presence_stmtContext) {
578                 builder.setPresence(true);
579                 break;
580             }
581         }
582
583         moduleBuilder.enterNode(builder);
584     }
585
586     @Override
587     public void exitContainer_stmt(final Container_stmtContext ctx) {
588         moduleBuilder.exitNode();
589         exitLog("container", stack.removeNodeFromPath());
590     }
591
592     @Override
593     public void enterLeaf_stmt(final Leaf_stmtContext ctx) {
594         final int line = ctx.getStart().getLine();
595         final String leafName = stringFromNode(ctx);
596         enterLog("leaf", leafName, line);
597
598         QName leafQName = QName.create(moduleQName, leafName);
599         SchemaPath path = stack.addNodeToPath(leafQName);
600
601         LeafSchemaNodeBuilder builder = moduleBuilder.addLeafNode(line, leafQName, path);
602         parseSchemaNodeArgs(ctx, builder);
603         parseConstraints(ctx, builder.getConstraints());
604         builder.setConfiguration(getConfig(ctx, builder, moduleName, line));
605
606         String defaultStr = null;
607         String unitsStr = null;
608         for (int i = 0; i < ctx.getChildCount(); i++) {
609             ParseTree child = ctx.getChild(i);
610             if (child instanceof Default_stmtContext) {
611                 defaultStr = stringFromNode(child);
612             } else if (child instanceof Units_stmtContext) {
613                 unitsStr = stringFromNode(child);
614             }
615         }
616         builder.setDefaultStr(defaultStr);
617         builder.setUnits(unitsStr);
618
619         moduleBuilder.enterNode(builder);
620     }
621
622     @Override
623     public void exitLeaf_stmt(final YangParser.Leaf_stmtContext ctx) {
624         moduleBuilder.exitNode();
625         exitLog("leaf", stack.removeNodeFromPath());
626     }
627
628     @Override
629     public void enterUses_stmt(final YangParser.Uses_stmtContext ctx) {
630         final int line = ctx.getStart().getLine();
631         final String groupingPathStr = stringFromNode(ctx);
632         final SchemaPath groupingPath = parseXPathString(groupingPathStr, line);
633         enterLog("uses", groupingPathStr, line);
634
635         UsesNodeBuilder builder = moduleBuilder.addUsesNode(line, groupingPath);
636
637         moduleBuilder.enterNode(builder);
638     }
639
640     @Override
641     public void exitUses_stmt(final YangParser.Uses_stmtContext ctx) {
642         moduleBuilder.exitNode();
643         exitLog("uses");
644     }
645
646     @Override
647     public void enterUses_augment_stmt(final YangParser.Uses_augment_stmtContext ctx) {
648         final int line = ctx.getStart().getLine();
649         final String augmentPath = stringFromNode(ctx);
650         enterLog(AUGMENT_STR, augmentPath, line);
651         stack.push();
652
653         SchemaPath targetPath = parseXPathString(augmentPath, line);
654         AugmentationSchemaBuilder builder = moduleBuilder.addAugment(line, augmentPath, targetPath, augmentOrder++);
655
656         for (int i = 0; i < ctx.getChildCount(); i++) {
657             ParseTree child = ctx.getChild(i);
658             if (child instanceof Description_stmtContext) {
659                 builder.setDescription(stringFromNode(child));
660             } else if (child instanceof Reference_stmtContext) {
661                 builder.setReference(stringFromNode(child));
662             } else if (child instanceof Status_stmtContext) {
663                 builder.setStatus(parseStatus((Status_stmtContext) child));
664             } else if (child instanceof When_stmtContext) {
665                 builder.addWhenCondition(stringFromNode(child));
666             }
667         }
668
669         moduleBuilder.enterNode(builder);
670     }
671
672     @Override
673     public void exitUses_augment_stmt(final YangParser.Uses_augment_stmtContext ctx) {
674         moduleBuilder.exitNode();
675         exitLog(AUGMENT_STR);
676         stack.pop();
677     }
678
679     @Override
680     public void enterRefine_stmt(final YangParser.Refine_stmtContext ctx) {
681         final String refineString = stringFromNode(ctx);
682         enterLog("refine", refineString, ctx.getStart().getLine());
683
684         RefineHolderImpl refine = parseRefine(ctx, moduleName);
685         moduleBuilder.addRefine(refine);
686         moduleBuilder.enterNode(refine);
687     }
688
689     @Override
690     public void exitRefine_stmt(final YangParser.Refine_stmtContext ctx) {
691         moduleBuilder.exitNode();
692         exitLog("refine");
693     }
694
695     @Override
696     public void enterLeaf_list_stmt(final Leaf_list_stmtContext ctx) {
697         final int line = ctx.getStart().getLine();
698         final String leafListName = stringFromNode(ctx);
699         enterLog("leaf-list", leafListName, line);
700         QName leafListQName = QName.create(moduleQName, leafListName);
701         SchemaPath path = stack.addNodeToPath(leafListQName);
702
703         LeafListSchemaNodeBuilder builder = moduleBuilder.addLeafListNode(line, leafListQName, path);
704         moduleBuilder.enterNode(builder);
705
706         parseSchemaNodeArgs(ctx, builder);
707         parseConstraints(ctx, builder.getConstraints());
708         builder.setConfiguration(getConfig(ctx, builder, moduleName, ctx.getStart().getLine()));
709
710         for (int i = 0; i < ctx.getChildCount(); ++i) {
711             final ParseTree childNode = ctx.getChild(i);
712             if (childNode instanceof Ordered_by_stmtContext) {
713                 final Ordered_by_stmtContext orderedBy = (Ordered_by_stmtContext) childNode;
714                 final boolean userOrdered = parseUserOrdered(orderedBy);
715                 builder.setUserOrdered(userOrdered);
716                 break;
717             }
718         }
719     }
720
721     @Override
722     public void exitLeaf_list_stmt(final YangParser.Leaf_list_stmtContext ctx) {
723         moduleBuilder.exitNode();
724         exitLog("leaf-list", stack.removeNodeFromPath());
725     }
726
727     @Override
728     public void enterList_stmt(final List_stmtContext ctx) {
729         final int line = ctx.getStart().getLine();
730         final String listName = stringFromNode(ctx);
731         enterLog("list", listName, line);
732
733         QName listQName = QName.create(moduleQName, listName);
734         SchemaPath path = stack.addNodeToPath(listQName);
735
736         ListSchemaNodeBuilder builder = moduleBuilder.addListNode(line, listQName, path);
737         moduleBuilder.enterNode(builder);
738
739         parseSchemaNodeArgs(ctx, builder);
740         parseConstraints(ctx, builder.getConstraints());
741         builder.setConfiguration(getConfig(ctx, builder, moduleName, line));
742
743         for (int i = 0; i < ctx.getChildCount(); ++i) {
744             ParseTree childNode = ctx.getChild(i);
745             if (childNode instanceof Ordered_by_stmtContext) {
746                 final Ordered_by_stmtContext orderedBy = (Ordered_by_stmtContext) childNode;
747                 final boolean userOrdered = parseUserOrdered(orderedBy);
748                 builder.setUserOrdered(userOrdered);
749             } else if (childNode instanceof Key_stmtContext) {
750                 List<String> key = createListKey((Key_stmtContext) childNode);
751                 builder.setKeys(key);
752             }
753         }
754     }
755
756     @Override
757     public void exitList_stmt(final List_stmtContext ctx) {
758         moduleBuilder.exitNode();
759         exitLog("list", stack.removeNodeFromPath());
760     }
761
762     @Override
763     public void enterAnyxml_stmt(final YangParser.Anyxml_stmtContext ctx) {
764         final int line = ctx.getStart().getLine();
765         final String anyXmlName = stringFromNode(ctx);
766         enterLog("anyxml", anyXmlName, line);
767
768         QName anyXmlQName = QName.create(moduleQName, anyXmlName);
769         SchemaPath path = stack.addNodeToPath(anyXmlQName);
770
771         AnyXmlBuilder builder = moduleBuilder.addAnyXml(line, anyXmlQName, path);
772         moduleBuilder.enterNode(builder);
773
774         parseSchemaNodeArgs(ctx, builder);
775         parseConstraints(ctx, builder.getConstraints());
776         builder.setConfiguration(getConfig(ctx, builder, moduleName, line));
777     }
778
779     @Override
780     public void exitAnyxml_stmt(final YangParser.Anyxml_stmtContext ctx) {
781         moduleBuilder.exitNode();
782         exitLog("anyxml", stack.removeNodeFromPath());
783     }
784
785     @Override
786     public void enterChoice_stmt(final YangParser.Choice_stmtContext ctx) {
787         final int line = ctx.getStart().getLine();
788         final String choiceName = stringFromNode(ctx);
789         enterLog("choice", choiceName, line);
790
791         QName choiceQName = QName.create(moduleQName, choiceName);
792         SchemaPath path = stack.addNodeToPath(choiceQName);
793
794         ChoiceBuilder builder = moduleBuilder.addChoice(line, choiceQName, path);
795         moduleBuilder.enterNode(builder);
796
797         parseSchemaNodeArgs(ctx, builder);
798         parseConstraints(ctx, builder.getConstraints());
799         builder.setConfiguration(getConfig(ctx, builder, moduleName, line));
800
801         // set 'default' case
802         for (int i = 0; i < ctx.getChildCount(); i++) {
803             ParseTree child = ctx.getChild(i);
804             if (child instanceof Default_stmtContext) {
805                 String defaultCase = stringFromNode(child);
806                 builder.setDefaultCase(defaultCase);
807                 break;
808             }
809         }
810     }
811
812     @Override
813     public void exitChoice_stmt(final YangParser.Choice_stmtContext ctx) {
814         moduleBuilder.exitNode();
815         exitLog("choice", stack.removeNodeFromPath());
816     }
817
818     @Override
819     public void enterCase_stmt(final YangParser.Case_stmtContext ctx) {
820         final int line = ctx.getStart().getLine();
821         final String caseName = stringFromNode(ctx);
822         enterLog("case", caseName, line);
823
824         QName caseQName = QName.create(moduleQName, caseName);
825         SchemaPath path = stack.addNodeToPath(caseQName);
826
827         ChoiceCaseBuilder builder = moduleBuilder.addCase(line, caseQName, path);
828         moduleBuilder.enterNode(builder);
829
830         parseSchemaNodeArgs(ctx, builder);
831         parseConstraints(ctx, builder.getConstraints());
832     }
833
834     @Override
835     public void exitCase_stmt(final YangParser.Case_stmtContext ctx) {
836         moduleBuilder.exitNode();
837         exitLog("case", stack.removeNodeFromPath());
838     }
839
840     @Override
841     public void enterNotification_stmt(final YangParser.Notification_stmtContext ctx) {
842         final int line = ctx.getStart().getLine();
843         final String notificationName = stringFromNode(ctx);
844         enterLog("notification", notificationName, line);
845
846         QName notificationQName = QName.create(moduleQName, notificationName);
847         SchemaPath path = stack.addNodeToPath(notificationQName);
848
849         NotificationBuilder builder = moduleBuilder.addNotification(line, notificationQName, path);
850         moduleBuilder.enterNode(builder);
851
852         parseSchemaNodeArgs(ctx, builder);
853     }
854
855     @Override
856     public void exitNotification_stmt(final YangParser.Notification_stmtContext ctx) {
857         moduleBuilder.exitNode();
858         exitLog("notification", stack.removeNodeFromPath());
859     }
860
861     // Unknown nodes
862     @Override
863     public void enterIdentifier_stmt(final YangParser.Identifier_stmtContext ctx) {
864         handleUnknownNode(ctx.getStart().getLine(), ctx);
865     }
866
867     @Override
868     public void exitIdentifier_stmt(final YangParser.Identifier_stmtContext ctx) {
869         moduleBuilder.exitNode();
870         exitLog("unknown-node", stack.removeNodeFromPath());
871     }
872
873     @Override public void enterUnknown_statement(final YangParser.Unknown_statementContext ctx) {
874         handleUnknownNode(ctx.getStart().getLine(), ctx);
875     }
876
877     @Override public void exitUnknown_statement(final YangParser.Unknown_statementContext ctx) {
878         moduleBuilder.exitNode();
879         exitLog("unknown-node", stack.removeNodeFromPath());
880     }
881
882     @Override
883     public void enterRpc_stmt(final YangParser.Rpc_stmtContext ctx) {
884         final int line = ctx.getStart().getLine();
885         final String rpcName = stringFromNode(ctx);
886         enterLog("rpc", rpcName, line);
887
888         QName rpcQName = QName.create(moduleQName, rpcName);
889         SchemaPath path = stack.addNodeToPath(rpcQName);
890
891         RpcDefinitionBuilder rpcBuilder = moduleBuilder.addRpc(line, rpcQName, path);
892         moduleBuilder.enterNode(rpcBuilder);
893
894
895         parseSchemaNodeArgs(ctx, rpcBuilder);
896     }
897
898     @Override
899     public void exitRpc_stmt(final YangParser.Rpc_stmtContext ctx) {
900         moduleBuilder.exitNode();
901         exitLog("rpc", stack.removeNodeFromPath());
902     }
903
904     @Override
905     public void enterInput_stmt(final YangParser.Input_stmtContext ctx) {
906         final int line = ctx.getStart().getLine();
907         final String input = "input";
908         enterLog(input, input, line);
909
910         QName rpcQName = QName.create(moduleQName, input);
911         SchemaPath path = stack.addNodeToPath(rpcQName);
912
913         ContainerSchemaNodeBuilder builder = moduleBuilder.addRpcInput(line, rpcQName, path);
914         moduleBuilder.enterNode(builder);
915         builder.setConfiguration(true);
916
917         parseSchemaNodeArgs(ctx, builder);
918         parseConstraints(ctx, builder.getConstraints());
919     }
920
921     @Override
922     public void exitInput_stmt(final YangParser.Input_stmtContext ctx) {
923         moduleBuilder.exitNode();
924         exitLog("input", stack.removeNodeFromPath());
925     }
926
927     @Override
928     public void enterOutput_stmt(final YangParser.Output_stmtContext ctx) {
929         final int line = ctx.getStart().getLine();
930         final String output = "output";
931         enterLog(output, output, line);
932
933         QName rpcQName = QName.create(moduleQName, output);
934         SchemaPath path = stack.addNodeToPath(rpcQName);
935
936         ContainerSchemaNodeBuilder builder = moduleBuilder.addRpcOutput(path, rpcQName, line);
937         moduleBuilder.enterNode(builder);
938         builder.setConfiguration(true);
939
940         parseSchemaNodeArgs(ctx, builder);
941         parseConstraints(ctx, builder.getConstraints());
942     }
943
944     @Override
945     public void exitOutput_stmt(final YangParser.Output_stmtContext ctx) {
946         moduleBuilder.exitNode();
947         exitLog("output", stack.removeNodeFromPath());
948     }
949
950     @Override
951     public void enterFeature_stmt(final YangParser.Feature_stmtContext ctx) {
952         final int line = ctx.getStart().getLine();
953         final String featureName = stringFromNode(ctx);
954         enterLog("feature", featureName, line);
955
956         QName featureQName = QName.create(moduleQName, featureName);
957         SchemaPath path = stack.addNodeToPath(featureQName);
958
959         FeatureBuilder featureBuilder = moduleBuilder.addFeature(line, featureQName, path);
960         moduleBuilder.enterNode(featureBuilder);
961
962         parseSchemaNodeArgs(ctx, featureBuilder);
963     }
964
965     @Override
966     public void exitFeature_stmt(final YangParser.Feature_stmtContext ctx) {
967         moduleBuilder.exitNode();
968         exitLog("feature", stack.removeNodeFromPath());
969     }
970
971     @Override
972     public void enterDeviation_stmt(final YangParser.Deviation_stmtContext ctx) {
973         final int line = ctx.getStart().getLine();
974         final String targetPathStr = stringFromNode(ctx);
975         if (!targetPathStr.startsWith("/")) {
976             throw new YangParseException(moduleName, line,
977                     "Deviation argument string must be an absolute schema node identifier.");
978         }
979         enterLog("deviation", targetPathStr, line);
980
981         String reference = null;
982         String deviate = null;
983
984         SchemaPath targetPath = parseXPathString(targetPathStr, line);
985         DeviationBuilder builder = moduleBuilder.addDeviation(line, targetPath);
986         moduleBuilder.enterNode(builder);
987
988         for (int i = 0; i < ctx.getChildCount(); i++) {
989             ParseTree child = ctx.getChild(i);
990             if (child instanceof Reference_stmtContext) {
991                 reference = stringFromNode(child);
992             } else if (child instanceof Deviate_not_supported_stmtContext) {
993                 deviate = stringFromNode(child);
994             } else if (child instanceof Deviate_add_stmtContext) {
995                 deviate = stringFromNode(child);
996             } else if (child instanceof Deviate_replace_stmtContext) {
997                 deviate = stringFromNode(child);
998             } else if (child instanceof Deviate_delete_stmtContext) {
999                 deviate = stringFromNode(child);
1000             }
1001         }
1002         builder.setReference(reference);
1003         builder.setDeviate(deviate);
1004     }
1005
1006     public SchemaPath parseXPathString(final String xpathString, final int line) {
1007         final boolean absolute = !xpathString.isEmpty() && xpathString.charAt(0) == '/';
1008
1009         final List<QName> path = new ArrayList<>();
1010         for (String pathElement : SLASH_SPLITTER.split(xpathString)) {
1011             final Iterator<String> it = COLON_SPLITTER.split(pathElement).iterator();
1012             final String s = it.next();
1013             if (it.hasNext()) {
1014                 path.add(parseQName(pathElement, line));
1015             } else {
1016                 path.add(QName.create(moduleQName, s));
1017             }
1018         }
1019         return SchemaPath.create(path, absolute);
1020     }
1021
1022     @Override
1023     public void exitDeviation_stmt(final YangParser.Deviation_stmtContext ctx) {
1024         moduleBuilder.exitNode();
1025         exitLog("deviation");
1026     }
1027
1028     @Override
1029     public void enterIdentity_stmt(final YangParser.Identity_stmtContext ctx) {
1030         final int line = ctx.getStart().getLine();
1031         final String identityName = stringFromNode(ctx);
1032         enterLog("identity", identityName, line);
1033
1034         final QName identityQName = QName.create(moduleQName, identityName);
1035         SchemaPath path = stack.addNodeToPath(identityQName);
1036
1037         IdentitySchemaNodeBuilder builder = moduleBuilder.addIdentity(identityQName, line, path);
1038         moduleBuilder.enterNode(builder);
1039
1040         parseSchemaNodeArgs(ctx, builder);
1041
1042         for (int i = 0; i < ctx.getChildCount(); i++) {
1043             ParseTree child = ctx.getChild(i);
1044             if (child instanceof Base_stmtContext) {
1045                 String baseIdentityName = stringFromNode(child);
1046                 builder.setBaseIdentityName(baseIdentityName);
1047             }
1048         }
1049     }
1050
1051     @Override
1052     public void exitIdentity_stmt(final YangParser.Identity_stmtContext ctx) {
1053         moduleBuilder.exitNode();
1054         exitLog("identity", stack.removeNodeFromPath());
1055     }
1056
1057     public ModuleBuilder getModuleBuilder() {
1058         return moduleBuilder;
1059     }
1060
1061     private static void enterLog(final String p1, final String p2, final int line) {
1062         LOG.trace("entering {} {} ({})", p1, p2, line);
1063     }
1064
1065     private static void exitLog(final String p1) {
1066         LOG.trace("exiting {}", p1);
1067     }
1068
1069     private static void exitLog(final String p1, final QName p2) {
1070         LOG.trace("exiting {} {}", p1, p2.getLocalName());
1071     }
1072
1073     private static void setLog(final String p1, final String p2) {
1074         LOG.trace("setting {} {}", p1, p2);
1075     }
1076
1077     private void handleUnknownNode(final int line, final ParseTree ctx) {
1078         final String nodeParameter = stringFromNode(ctx);
1079         enterLog("unknown-node", nodeParameter, line);
1080
1081         final String nodeTypeStr = ctx.getChild(0).getText();
1082         QName nodeType = parseQName(nodeTypeStr, line);
1083
1084         QName qname = null;
1085         try {
1086             if (Strings.isNullOrEmpty(nodeParameter)) {
1087                 qname = nodeType;
1088             } else {
1089                 final Iterable<String> splittedName = COLON_SPLITTER.split(nodeParameter);
1090                 final Iterator<String> it = splittedName.iterator();
1091                 if (Iterables.size(splittedName) == 2) {
1092                     qname = parseQName(nodeParameter, line);
1093                 } else {
1094                     qname = QName.create(moduleQName, it.next());
1095                 }
1096             }
1097         } catch (IllegalArgumentException e) {
1098             qname = nodeType;
1099         }
1100
1101         SchemaPath path = stack.addNodeToPath(qname);
1102
1103         UnknownSchemaNodeBuilderImpl builder = moduleBuilder.addUnknownSchemaNode(line, qname, path);
1104         builder.setNodeType(nodeType);
1105         builder.setNodeParameter(nodeParameter);
1106
1107         parseSchemaNodeArgs(ctx, builder);
1108         moduleBuilder.enterNode(builder);
1109     }
1110
1111 }