72164749feee38e2292ec2b4942c2d9c74cdac9e
[nit.git] / lib / ordered_tree.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Manipulation and presentation of ordered trees.
18 module ordered_tree
19
20 # Generic structure to manage and display an ordered tree
21 #
22 # Ordered tree are tree where the elements of a same parent are in a specific order
23 #
24 # Elements of the trees are added with the `add` method that takes a parent and
25 # a sub-element.
26 # If the parent is `null`, then the element is considered a root.
27 #
28 # ~~~~
29 # var t = new OrderedTree[String]
30 # t.add(null, "root")
31 # t.add("root", "child1")
32 # t.add("root", "child2")
33 # t.add("child1", "grand-child")
34 # assert t.length == 4
35 # ~~~~
36 #
37 # By default, the elements with a same parent
38 # are visited in the order they are added.
39 #
40 # ~~~
41 # assert t.to_a == ["root", "child1", "grand-child", "child2"]
42 # assert t.write_to_string == """
43 # root
44 # |--child1
45 # | `--grand-child
46 # `--child2
47 # """
48 # ~~~
49 #
50 # The `sort_with` method can be used reorder elements
51 #
52 # ~~~
53 # t.add("root", "aaa")
54 # assert t.to_a == ["root", "child1", "grand-child", "child2", "aaa"]
55 # t.sort_with(alpha_comparator)
56 # assert t.to_a == ["root", "aaa", "child1", "grand-child", "child2"]
57 # ~~~
58 #
59 # This class can be used as it to work with generic trees but can also be specialized to provide more specific
60 # behavior or display. It is why the internal attributes are mutable.
61 class OrderedTree[E: Object]
62 super Writable
63 super Collection[E]
64 super Cloneable
65
66 # The roots of the tree (in sequence)
67 var roots = new Array[E]
68
69 # The branches of the trees.
70 # For each element, the ordered array of its direct sub-elements.
71 var sub = new HashMap[E, Array[E]]
72
73 # Add a new element `e` in the tree.
74 # `p` is the parent of `e`.
75 # if `p` is null, then `e` is a root element.
76 fun add(p: nullable E, e: E)
77 do
78 if p == null then
79 roots.add(e)
80 else if sub.has_key(p) then
81 sub[p].add(e)
82 else
83 sub[p] = [e]
84 end
85 end
86
87 # Append all nodes `es` as children of `p`.
88 fun add_all(p: nullable E, es: Collection[E])
89 do
90 for e in es do add(p, e)
91 end
92
93 # print the full tree on `o`
94 # Write a ASCII-style tree and use the `display` method to label elements
95 redef fun write_to(stream: Writer)
96 do
97 for r in roots do
98 stream.write display(r)
99 stream.write "\n"
100 sub_write_to(stream, r, "")
101 end
102 end
103
104 private fun sub_write_to(o: Writer, e: E, prefix: String)
105 do
106 if not sub.has_key(e) then return
107 var subs = sub[e]
108 var last = subs.last
109 for e2 in subs do
110 if e2 != last then
111 o.write "{prefix}|--{display(e2)}\n"
112 sub_write_to(o, e2, prefix+"| ")
113 else
114 o.write "{prefix}`--{display(e2)}\n"
115 sub_write_to(o, e2, prefix+" ")
116 end
117 end
118 end
119
120 # Sort roots and other elements using a comparator method
121 # This method basically sorts roots then each group of children
122 fun sort_with(comparator: Comparator)
123 do
124 comparator.sort(roots)
125 for a in sub.values do
126 comparator.sort(a)
127 end
128 end
129
130 # How to display a specific element of the tree
131 # By defaut, uses `to_s`
132 #
133 # Subclasses should redefine this method to provide a specific output
134 fun display(e: E): String do return e.to_s
135
136 # Get an array of the contained elements
137 # Order is preserved
138 #
139 # var tree = new OrderedTree[Int]
140 # tree.add_all(null, [1, 2])
141 # tree.add_all(1, [11, 12])
142 # tree.add_all(11, [111, 112])
143 # tree.add_all(12, [121, 122])
144 # tree.add_all(2, [21, 22])
145 # assert tree.to_a == [1, 11, 111, 112, 12, 121, 122, 2, 21, 22]
146 redef fun to_a: Array[E] do
147 var res = new Array[E]
148 for r in roots do sub_to_a(r, res)
149 return res
150 end
151
152 private fun sub_to_a(e: E, res: Array[E]) do
153 res.add e
154 if sub.has_key(e) then for e2 in sub[e] do sub_to_a(e2, res)
155 end
156
157 # var tree = new OrderedTree[Int]
158 # assert tree.is_empty
159 # tree.add(null, 1)
160 # assert not tree.is_empty
161 redef fun is_empty: Bool do return roots.is_empty
162
163 # var tree = new OrderedTree[Int]
164 # tree.add(null, 1)
165 # tree.add(1, 11)
166 # assert tree.first == 1
167 redef fun first do return roots.first
168
169 # var tree = new OrderedTree[Int]
170 # tree.add_all(null, [1, 2])
171 # tree.add_all(1, [11, 12])
172 # tree.add_all(11, [111, 112])
173 # tree.add_all(12, [121, 122])
174 # tree.add_all(2, [21, 22])
175 # var order = [1, 11, 111, 112, 12, 121, 122, 2, 21, 22]
176 # assert tree.iterator.to_a == order
177 redef fun iterator do return new OrderedTreeIterator[E](self)
178
179 # Two trees are equal if they have the same nodes in the same order
180 #
181 # ~~~
182 # var t1 = new OrderedTree[Int]
183 # t1.add_all(null, [1, 2])
184 # t1.add_all(1, [11, 12])
185 #
186 # var t2 = new OrderedTree[Int]
187 # t2.add_all(null, [1, 2])
188 #
189 # assert t1 != t2
190 #
191 # t2.add_all(1, [11, 12])
192 #
193 # assert t1 == t2
194 # ~~~
195 redef fun ==(other)
196 do
197 if not other isa OrderedTree[Object] then return false
198 return roots == other.roots and sub == other.sub
199 end
200
201 redef fun hash
202 do
203 return roots.hash + sub.hash
204 end
205
206 # Shallow clone of the tree.
207 #
208 # ~~~
209 # var t = new OrderedTree[Int]
210 # t.add_all(null, [1, 2])
211 # t.add_all(1, [11, 12])
212 #
213 # assert t.clone == t
214 # ~~~
215 redef fun clone
216 do
217 var res = new OrderedTree[E]
218 res.add_all(null, roots)
219 for p, es in sub do
220 res.add_all(p, es)
221 end
222 return res
223 end
224 end
225
226 # An Iterator over an OrderedTree
227 private class OrderedTreeIterator[E: Object]
228 super Iterator[E]
229
230 var tree: OrderedTree[E]
231
232 var iterators = new Array[Iterator[E]]
233
234 init do
235 if not tree.is_empty then
236 iterators.add tree.roots.iterator
237 end
238 end
239
240 redef fun is_ok do return not iterators.is_empty
241
242 redef fun item do
243 assert is_ok
244 return iterators.last.item
245 end
246
247 redef fun next do
248 assert is_ok
249 if tree.sub.has_key(item) then
250 iterators.add tree.sub[item].iterator
251 else
252 iterators.last.next
253 while is_ok and not iterators.last.is_ok do
254 iterators.pop
255 if is_ok and iterators.last.is_ok then
256 iterators.last.next
257 end
258 end
259 end
260 end
261
262 redef fun iterator do return new OrderedTreeIterator[E](tree)
263 end