Bug 3670 (part 3/5): Use of new statement parser in yang-maven-plugin
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / util / ModuleDependencySort.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.util;
9
10 import static java.util.Arrays.asList;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Function;
14 import com.google.common.base.Optional;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Maps;
17 import com.google.common.collect.Sets;
18 import java.net.URI;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Date;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Set;
27 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
28 import org.opendaylight.yangtools.yang.model.api.Module;
29 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
30 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
31 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
32 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.Node;
33 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.NodeImpl;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * Creates a module dependency graph from provided {@link ModuleBuilder}s and
39  * provides a {@link #sort(ModuleBuilder...)} method. It is topological sort and
40  * returns modules in order in which they should be processed (e.g. if A imports
41  * B, sort returns {B, A}).
42  */
43 public final class ModuleDependencySort {
44
45     private static final Date DEFAULT_REVISION = SimpleDateFormatUtil.DEFAULT_DATE_REV;
46     private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDependencySort.class);
47     private static final Function<Node, Module> TOPOLOGY_FUNCTION = new Function<TopologicalSort.Node, Module>() {
48         @Override
49         public Module apply(final TopologicalSort.Node input) {
50             if (input == null) {
51                 return null;
52             }
53             ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
54             return moduleOrModuleBuilder.getModule();
55         }
56     };
57
58     /**
59      * It is not desirable to instance this class
60      */
61     private ModuleDependencySort() {
62     }
63
64
65     /**
66      * Extracts {@link ModuleBuilder} from a {@link ModuleNodeImpl}.
67      */
68     private static final Function<TopologicalSort.Node, ModuleBuilder> NODE_TO_MODULEBUILDER = new Function<TopologicalSort.Node, ModuleBuilder>() {
69         @Override
70         public ModuleBuilder apply(final TopologicalSort.Node input) {
71             // Cast to ModuleBuilder from Node and return
72             if (input == null) {
73                 return null;
74             }
75             ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
76             return moduleOrModuleBuilder.getModuleBuilder();
77         }
78     };
79
80     /**
81      * Topological sort of module builder dependency graph.
82      *
83      * @param builders builders of Module object
84      * @return Sorted list of Module builders. Modules can be further processed
85      *         in returned order.
86      */
87     public static List<ModuleBuilder> sort(final ModuleBuilder... builders) {
88         return sort(asList(builders));
89     }
90
91     public static List<ModuleBuilder> sort(final Collection<ModuleBuilder> builders) {
92         List<TopologicalSort.Node> sorted = sortInternal(ModuleOrModuleBuilder.fromAll(
93                 Collections.<Module>emptySet(),builders));
94         return Lists.transform(sorted, NODE_TO_MODULEBUILDER);
95     }
96
97     public static List<ModuleBuilder> sortWithContext(final SchemaContext context, final ModuleBuilder... builders) {
98         List<ModuleOrModuleBuilder> all = ModuleOrModuleBuilder.fromAll(context.getModules(), asList(builders));
99
100         List<TopologicalSort.Node> sorted = sortInternal(all);
101         // Cast to ModuleBuilder from Node if possible and return
102         return Lists.transform(sorted, new Function<TopologicalSort.Node, ModuleBuilder>() {
103
104             @Override
105             public ModuleBuilder apply(final TopologicalSort.Node input) {
106                 if (input == null) {
107                     return null;
108                 }
109                 ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
110                 if (moduleOrModuleBuilder.isModuleBuilder()) {
111                     return moduleOrModuleBuilder.getModuleBuilder();
112                 } else {
113                     return null;
114                 }
115             }
116         });
117     }
118
119     /**
120      * Topological sort of module dependency graph.
121      *
122      * @param modules YANG modules
123      * @return Sorted list of Modules. Modules can be further processed in
124      *         returned order.
125      */
126     public static List<Module> sort(final Module... modules) {
127         List<TopologicalSort.Node> sorted = sortInternal(ModuleOrModuleBuilder.fromAll(asList(modules),
128                 Collections.<ModuleBuilder>emptyList()));
129         // Cast to Module from Node and return
130         return Lists.transform(sorted, TOPOLOGY_FUNCTION);
131     }
132
133     private static List<TopologicalSort.Node> sortInternal(final Iterable<ModuleOrModuleBuilder> modules) {
134         Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
135
136         Set<TopologicalSort.Node> nodes = Sets.newHashSet();
137         for (Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
138             for (ModuleNodeImpl node : map.values()) {
139                 nodes.add(node);
140             }
141         }
142
143         return TopologicalSort.sort(nodes);
144     }
145
146     @VisibleForTesting
147     static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final Iterable<ModuleOrModuleBuilder> builders) {
148         Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
149
150         processModules(moduleGraph, builders);
151         processDependencies(moduleGraph, builders);
152
153         return moduleGraph;
154     }
155
156     /**
157      * Extract module:revision from module builders
158      */
159     private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
160             final Iterable<ModuleOrModuleBuilder> mmbs) {
161         Map<URI, ModuleOrModuleBuilder> allNS = new HashMap<>();
162
163         // Create edges in graph
164         for (ModuleOrModuleBuilder mmb : mmbs) {
165             Map<String, Date> imported = Maps.newHashMap();
166
167             String fromName;
168             Date fromRevision;
169             Collection<ModuleImport> imports;
170             URI ns;
171
172             if (mmb.isModule()) {
173                 Module module = mmb.getModule();
174                 fromName = module.getName();
175                 fromRevision = module.getRevision();
176                 imports = module.getImports();
177                 ns = module.getNamespace();
178             } else {
179                 ModuleBuilder moduleBuilder = mmb.getModuleBuilder();
180                 fromName = moduleBuilder.getName();
181                 fromRevision = moduleBuilder.getRevision();
182                 imports = moduleBuilder.getImports().values();
183                 ns = moduleBuilder.getNamespace();
184             }
185
186             // check for existence of module with same namespace
187             if (allNS.containsKey(ns)) {
188                 ModuleOrModuleBuilder mod = allNS.get(ns);
189                 String name = null;
190                 Date revision = null;
191                 if (mod.isModule()) {
192                     name = mod.getModule().getName();
193                     revision = mod.getModule().getRevision();
194                 } else if (mod.isModuleBuilder()) {
195                     name = mod.getModuleBuilder().getName();
196                     revision = mod.getModuleBuilder().getRevision();
197                 }
198                 if (!(fromName.equals(name))) {
199                     LOGGER.warn(
200                             "Error while sorting module [{}, {}]: module with same namespace ({}) already loaded: [{}, {}]",
201                             fromName, fromRevision, ns, name, revision);
202                 }
203             } else {
204                 allNS.put(ns, mmb);
205             }
206
207             // no need to check if other Type of object, check is performed in
208             // process modules
209
210             if (fromRevision == null) {
211                 fromRevision = DEFAULT_REVISION;
212             }
213
214             for (ModuleImport imprt : imports) {
215                 String toName = imprt.getModuleName();
216                 Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
217
218                 ModuleNodeImpl from = moduleGraph.get(fromName).get(fromRevision);
219
220                 ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
221
222                 /*
223                  * Check imports: If module is imported twice with different
224                  * revisions then throw exception
225                  */
226                 if (imported.get(toName) != null && !imported.get(toName).equals(toRevision)
227                         && !imported.get(toName).equals(DEFAULT_REVISION) && !toRevision.equals(DEFAULT_REVISION)) {
228                     ex(String.format("Module:%s imported twice with different revisions:%s, %s", toName,
229                             formatRevDate(imported.get(toName)), formatRevDate(toRevision)));
230                 }
231
232                 imported.put(toName, toRevision);
233
234                 from.addEdge(to);
235             }
236         }
237     }
238
239     /**
240      * Get imported module by its name and revision from moduleGraph
241      */
242     private static ModuleNodeImpl getModuleByNameAndRevision(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
243             final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
244         ModuleNodeImpl to = null;
245
246         if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
247             // If revision is not specified in import, but module exists
248             // with different revisions, take first
249             if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
250                     && toRevision.equals(DEFAULT_REVISION)) {
251                 to = moduleGraph.get(toName).values().iterator().next();
252                 LOGGER.trace(String
253                         .format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
254                                 toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
255                                 formatRevDate(to.getRevision())));
256             } else {
257                 LOGGER.warn(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
258                         formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
259                 LOGGER.warn("Available models: {}", moduleGraph);
260                 ex(String.format("Not existing module imported:%s:%s by:%s:%s", toName, formatRevDate(toRevision),
261                         fromName, formatRevDate(fromRevision)));
262             }
263         } else {
264             to = moduleGraph.get(toName).get(toRevision);
265         }
266         return to;
267     }
268
269     private static void ex(final String message) {
270         throw new YangValidationException(message);
271     }
272
273     /**
274      * Extract dependencies from module builders or modules to fill dependency
275      * graph
276      */
277     private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
278             final Iterable<ModuleOrModuleBuilder> builders) {
279
280         // Process nodes
281         for (ModuleOrModuleBuilder momb : builders) {
282
283             String name;
284             Date rev;
285
286             if (momb.isModule()) {
287                 name = momb.getModule().getName();
288                 rev = momb.getModule().getRevision();
289             } else {
290                 name = momb.getModuleBuilder().getName();
291                 rev = momb.getModuleBuilder().getRevision();
292             }
293
294             if (rev == null) {
295                 rev = DEFAULT_REVISION;
296             }
297
298             if (moduleGraph.get(name) == null) {
299                 moduleGraph.put(name, Maps.<Date, ModuleNodeImpl> newHashMap());
300             }
301
302             if (moduleGraph.get(name).get(rev) != null) {
303                 ex(String.format("Module:%s with revision:%s declared twice", name, formatRevDate(rev)));
304             }
305
306             moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, momb));
307         }
308     }
309
310     private static String formatRevDate(final Date rev) {
311         return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
312     }
313
314     @VisibleForTesting
315     static class ModuleNodeImpl extends NodeImpl {
316         private final String name;
317         private final Date revision;
318         private final ModuleOrModuleBuilder originalObject;
319
320         public ModuleNodeImpl(final String name, final Date revision, final ModuleOrModuleBuilder builder) {
321             this.name = name;
322             this.revision = revision;
323             this.originalObject = builder;
324         }
325
326         public String getName() {
327             return name;
328         }
329
330         public Date getRevision() {
331             return revision;
332         }
333
334         @Override
335         public int hashCode() {
336             final int prime = 31;
337             int result = 1;
338             result = prime * result + ((name == null) ? 0 : name.hashCode());
339             result = prime * result + ((revision == null) ? 0 : revision.hashCode());
340             return result;
341         }
342
343         @Override
344         public boolean equals(final Object obj) {
345             if (this == obj) {
346                 return true;
347             }
348             if (obj == null) {
349                 return false;
350             }
351             if (getClass() != obj.getClass()) {
352                 return false;
353             }
354             ModuleNodeImpl other = (ModuleNodeImpl) obj;
355             if (name == null) {
356                 if (other.name != null) {
357                     return false;
358                 }
359             } else if (!name.equals(other.name)) {
360                 return false;
361             }
362             if (revision == null) {
363                 if (other.revision != null) {
364                     return false;
365                 }
366             } else if (!revision.equals(other.revision)) {
367                 return false;
368             }
369             return true;
370         }
371
372         @Override
373         public String toString() {
374             return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
375         }
376
377         public ModuleOrModuleBuilder getReference() {
378             return originalObject;
379         }
380
381     }
382
383 }
384 class ModuleOrModuleBuilder {
385     private final Optional<Module> maybeModule;
386     private final Optional<ModuleBuilder> maybeModuleBuilder;
387
388     ModuleOrModuleBuilder(final Module module) {
389         maybeModule = Optional.of(module);
390         maybeModuleBuilder = Optional.absent();
391     }
392
393     ModuleOrModuleBuilder(final ModuleBuilder moduleBuilder) {
394         maybeModule = Optional.absent();
395         maybeModuleBuilder = Optional.of(moduleBuilder);
396     }
397     boolean isModule(){
398         return maybeModule.isPresent();
399     }
400     boolean isModuleBuilder(){
401         return maybeModuleBuilder.isPresent();
402     }
403     Module getModule(){
404         return maybeModule.get();
405     }
406     ModuleBuilder getModuleBuilder(){
407         return maybeModuleBuilder.get();
408     }
409
410     static List<ModuleOrModuleBuilder> fromAll(final Collection<Module> modules, final Collection<ModuleBuilder> moduleBuilders) {
411         List<ModuleOrModuleBuilder> result = new ArrayList<>(modules.size() + moduleBuilders.size());
412         for(Module m: modules){
413             result.add(new ModuleOrModuleBuilder(m));
414         }
415         for (ModuleBuilder mb : moduleBuilders) {
416             result.add(new ModuleOrModuleBuilder(mb));
417         }
418         return result;
419     }
420 }