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