1b9ecfe93f21f069bd5e9f0632adcc933a5d479c
[nit.git] / src / ni.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2008 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 module ni
18
19 import model_utils
20
21 private class Pager
22 var content: String = ""
23 fun add(text: String) do addn("{text}\n")
24 fun addn(text: String) do content += text.escape
25 fun add_rule do add("\n---\n")
26 fun render do sys.system("echo \"{content}\" | pager -r")
27 end
28
29 class NitIndex
30 private var toolcontext: ToolContext
31 private var model: Model
32 private var mbuilder: ModelBuilder
33 private var mainmodule: MModule
34 private var arguments: Array[String]
35
36 init(toolcontext: ToolContext) do
37 # We need a model to collect stufs
38 self.toolcontext = toolcontext
39 self.arguments = toolcontext.option_context.rest
40
41 if arguments.length > 2 then
42 print "usage: ni path/to/module.nit [expression]"
43 toolcontext.option_context.usage
44 exit(1)
45 end
46
47 model = new Model
48 mbuilder = new ModelBuilder(model, toolcontext)
49
50 # Here we load an process std modules
51 #var dir = "NIT_DIR".environ
52 #var mmodules = modelbuilder.parse_and_build(["{dir}/lib/standard/standard.nit"])
53 var mmodules = mbuilder.parse_and_build([arguments.first])
54 if mmodules.is_empty then return
55 mbuilder.full_propdef_semantic_analysis
56 assert mmodules.length == 1
57 self.mainmodule = mmodules.first
58 end
59
60 fun start do
61 if arguments.length == 1 then
62 welcome
63 prompt
64 else
65 seek(arguments[1])
66 end
67 end
68
69 fun welcome do
70 print "Welcome in Nit Index.\n"
71 print "Loaded modules"
72 for m in mbuilder.nmodules do
73 print " - {m.mmodule.name}"
74 end
75 print "\nEnter the module, class or property name you want to look up."
76 print "Enter a blank line to exit.\n"
77 end
78
79 fun prompt do
80 printn ">> "
81 seek(stdin.read_line)
82 end
83
84 fun seek(entry: String) do
85 if entry.is_empty then exit(0)
86 var flag = false
87 # seek for modules
88 var mmatches = new List[MModule]
89 for m in model.mmodules do
90 if m.name == entry then
91 flag = true
92 mmatches.add(m)
93 end
94 end
95 if not mmatches.is_empty then modules_fulldoc(mmatches)
96 # seek for classes
97 var cmatches = new List[MClass]
98 for c in model.mclasses do
99 if c.name == entry then
100 flag = true
101 cmatches.add(c)
102 end
103 end
104 if not cmatches.is_empty then classes_fulldoc(cmatches)
105 # seek for properties
106 var matches = new List[MProperty]
107 for p in model.mproperties do
108 if p.name == entry then
109 flag = true
110 matches.add(p)
111 end
112 end
113 if not matches.is_empty then props_fulldoc(matches)
114 # no matches
115 if not flag then print "Nothing known about '{entry}'"
116 if arguments.length == 1 then prompt
117 end
118
119 private fun modules_fulldoc(mmodules: List[MModule]) do
120 var pager = new Pager
121 for mmodule in mmodules do
122 var nmodule = mbuilder.mmodule2nmodule[mmodule]
123 pager.add("# module {mmodule.namespace}\n".bold)
124 if not mmodule.in_importation.direct_greaters.is_empty then
125 pager.add("import ".bold + "{mmodule.in_importation.direct_greaters.join(", ")}\n")
126 end
127 if not mmodule.in_importation.direct_smallers.is_empty then
128 pager.add("known clients: ".bold + "{mmodule.in_importation.direct_smallers.join(", ")}\n")
129 end
130 pager.add_rule
131 pager.addn(nmodule.comment.green)
132 pager.add_rule
133
134 var cats = new HashMap[String, Collection[MClass]]
135 cats["introduced classes"] = mmodule.intro_mclasses
136 cats["refined classes"] = mmodule.redef_mclasses
137 cats["inherited classes"] = mmodule.imported_mclasses
138
139 for cat, list in cats do
140 if not list.is_empty then
141 pager.add("# {cat}".bold)
142 for mclass in list do
143 var nclass = mbuilder.mclassdef2nclassdef[mclass.intro].as(AStdClassdef)
144 pager.add("")
145 if not nclass.short_comment.is_empty then
146 pager.add("\t# {nclass.short_comment}")
147 end
148 if cat == "refined classes" then
149 pager.add("\tredef {mclass.short_doc}")
150 else
151 pager.add("\t{mclass.short_doc}")
152 end
153 if not mclass.intro_mmodule == mmodule then
154 pager.add("\t\t" + "introduced in {mmodule.full_name}::{mclass}".gray)
155 end
156 for mclassdef in mclass.mclassdefs do
157 if mclassdef != mclass.intro then
158 pager.add("\t\t" + "refined in {mclassdef.namespace}".gray)
159 end
160 end
161 end
162 end
163 end
164 pager.add_rule
165 end
166 pager.render
167 end
168
169 private fun classes_fulldoc(mclasses: List[MClass]) do
170 var pager = new Pager
171 for mclass in mclasses do
172 var nclass = mbuilder.mclassdef2nclassdef[mclass.intro].as(AStdClassdef)
173
174 pager.add("# {mclass.namespace}\n".bold)
175 pager.add("{mclass.short_doc}")
176 pager.add_rule
177 pager.addn(nclass.comment.green)
178 pager.add_rule
179 if not mclass.parameter_types.is_empty then
180 pager.add("# formal types".bold)
181 for ft, bound in mclass.parameter_types do
182 pager.add("")
183 pager.add("\t{ft.to_s.green}: {bound}")
184 end
185 end
186 if not mclass.virtual_types.is_empty then
187 pager.add("# virtual types".bold)
188 for vt in mclass.virtual_types do
189 pager.add("")
190 vt_fulldoc(pager, vt)
191 end
192 end
193 pager.add_rule
194
195 var cats = new HashMap[String, Collection[MMethod]]
196 cats["constructors"] = mclass.constructors
197 cats["introduced methods"] = mclass.intro_methods
198 cats["refined methods"] = mclass.redef_methods
199 cats["inherited methods"] = mclass.inherited_methods
200
201 for cat, list in cats do
202 if not list.is_empty then
203 pager.add("\n# {cat}".bold)
204 for mprop in list do
205 pager.add("")
206 method_fulldoc(pager, mprop)
207 end
208 end
209 end
210 pager.add_rule
211 end
212 pager.render
213 end
214
215 private fun props_fulldoc(mprops: List[MProperty]) do
216 var pager = new Pager
217 # TODO group by module
218 for mprop in mprops do
219 if mprop isa MMethod and mbuilder.mpropdef2npropdef.has_key(mprop.intro) then
220 method_fulldoc(pager, mprop)
221 pager.add_rule
222 else if mprop isa MVirtualTypeProp then
223 vt_fulldoc(pager, mprop)
224 pager.add_rule
225 end
226 end
227 pager.render
228 end
229
230 private fun method_fulldoc(pager: Pager, mmethod: MMethod) do
231 if mbuilder.mpropdef2npropdef.has_key(mmethod.intro) then
232 var nmethod = mbuilder.mpropdef2npropdef[mmethod.intro]
233 if nmethod isa AMethPropdef then
234 if not nmethod.short_comment.is_empty then
235 pager.add("\t# {nmethod.short_comment}")
236 end
237 pager.add("\t{nmethod}")
238 pager.add("\t\t" + "introduced in {mmethod.intro_mclassdef.namespace}".gray)
239 for mpropdef in mmethod.mpropdefs do
240 if mpropdef != mmethod.intro then
241 pager.add("\t\t" + "refined in {mpropdef.mclassdef.namespace}".gray)
242 end
243 end
244 end
245 end
246 end
247
248 private fun vt_fulldoc(pager: Pager, vt: MVirtualTypeProp) do
249 pager.add("\t{vt.short_doc}")
250 pager.add("\t\t" + "introduced in {vt.intro_mclassdef.namespace}::{vt}".gray)
251 for mpropdef in vt.mpropdefs do
252 if mpropdef != vt.intro then
253 pager.add("\t\t" + "refined in {mpropdef.mclassdef.namespace}".gray)
254 end
255 end
256 end
257 end
258
259 # Printing facilities
260
261 redef class MModule
262 private fun namespace: String do
263 return full_name
264 end
265 end
266
267 redef class MClass
268
269 redef fun to_s: String do
270 if arity > 0 then
271 return "{name}[{intro.parameter_names.join(", ")}]"
272 else
273 return name
274 end
275 end
276
277 private fun short_doc: String do
278 var ret = ""
279 if is_interface then ret = "interface {ret}"
280 if is_enum then ret = "enum {ret}"
281 if is_class then ret = "class {ret}"
282 if is_abstract then ret = "abstract {ret}"
283 if visibility.to_s == "public" then ret = "{ret}{to_s.green}"
284 if visibility.to_s == "private" then ret = "{ret}{to_s.red}"
285 if visibility.to_s == "protected" then ret = "{ret}{to_s.yellow}"
286 if not parents.is_empty then
287 ret = "{ret} super {parents.join(", ")}"
288 end
289 return ret
290 end
291
292 private fun namespace: String do
293 return "{intro_mmodule.public_owner.name}::{name}"
294 end
295 end
296
297 redef class MClassDef
298 private fun namespace: String do
299 return "{mmodule.full_name}::{mclass.name}"
300 end
301 end
302
303 redef class MVirtualTypeProp
304 private fun short_doc: String do
305 var ret = ""
306 if visibility.to_s == "public" then ret = "{to_s.green}: {intro.bound.to_s}"
307 if visibility.to_s == "private" then ret = "\t{to_s.red}: {intro.bound.to_s}"
308 if visibility.to_s == "protected" then ret = "\t{to_s.yellow}: {intro.bound.to_s}"
309 return ret
310 end
311 end
312
313 redef class AModule
314 private fun comment: String do
315 var ret = ""
316 for t in n_moduledecl.n_doc.n_comment do
317 ret += "{t.text.replace("# ", "")}"
318 end
319 return ret
320 end
321 end
322
323 redef class AStdClassdef
324 private fun comment: String do
325 var ret = ""
326 if n_doc != null then
327 for t in n_doc.n_comment do
328 var txt = t.text.replace("# ", "")
329 txt = txt.replace("#", "")
330 ret += "{txt}"
331 end
332 end
333 return ret
334 end
335
336 private fun short_comment: String do
337 var ret = ""
338 if n_doc != null then
339 var txt = n_doc.n_comment.first.text
340 txt = txt.replace("# ", "")
341 txt = txt.replace("\n", "")
342 ret += txt
343 end
344 return ret
345 end
346 end
347
348 redef class AMethPropdef
349 private fun short_comment: String do
350 var ret = ""
351 if n_doc != null then
352 var txt = n_doc.n_comment.first.text
353 txt = txt.replace("# ", "")
354 txt = txt.replace("\n", "")
355 ret += txt
356 end
357 return ret
358 end
359
360 redef fun to_s do
361 var ret = ""
362 if not mpropdef.mproperty.is_init then
363 ret = "fun "
364 end
365 if mpropdef.mproperty.visibility.to_s == "public" then ret = "{ret}{mpropdef.mproperty.name.green}"
366 if mpropdef.mproperty.visibility.to_s == "private" then ret = "{ret}{mpropdef.mproperty.name.red}"
367 if mpropdef.mproperty.visibility.to_s == "protected" then ret = "{ret}{mpropdef.mproperty.name.yellow}"
368 if n_signature != null then ret = "{ret}{n_signature.to_s}"
369 if n_kwredef != null then ret = "redef {ret}"
370 if self isa ADeferredMethPropdef then ret = "{ret} is abstract"
371 if self isa AInternMethPropdef then ret = "{ret} is intern"
372 if self isa AExternMethPropdef then ret = "{ret} is extern"
373 return ret
374 end
375 end
376
377 redef class ASignature
378 redef fun to_s do
379 #TODO closures
380 var ret = ""
381 if not n_params.is_empty then
382 ret = "{ret}({n_params.join(", ")})"
383 end
384 if n_type != null then ret += ": {n_type.to_s}"
385 return ret
386 end
387 end
388
389 redef class AParam
390 redef fun to_s do
391 var ret = "{n_id.text}"
392 if n_type != null then
393 ret = "{ret}: {n_type.to_s}"
394 if n_dotdotdot != null then ret = "{ret}..."
395 end
396 return ret
397 end
398 end
399
400 redef class AType
401 redef fun to_s do
402 var ret = n_id.text
403 if n_kwnullable != null then ret = "nullable {ret}"
404 if not n_types.is_empty then ret = "{ret}[{n_types.join(", ")}]"
405 return ret
406 end
407 end
408
409 # Redef String class to add a function to color the string
410 redef class String
411
412 private fun add_escape_char(escapechar: String): String do
413 return "{escapechar}{self}\\033[0m"
414 end
415
416 private fun esc: Char do return 27.ascii
417 private fun red: String do return add_escape_char("{esc}[1;31m")
418 private fun yellow: String do return add_escape_char("{esc}[1;33m")
419 private fun green: String do return add_escape_char("{esc}[1;32m")
420 private fun blue: String do return add_escape_char("{esc}[1;34m")
421 private fun cyan: String do return add_escape_char("{esc}[1;36m")
422 private fun gray: String do return add_escape_char("{esc}[30;1m")
423 private fun bold: String do return add_escape_char("{esc}[1m")
424 private fun underline: String do return add_escape_char("{esc}[4m")
425
426 private fun escape: String
427 do
428 var b = new Buffer
429 for c in self do
430 if c == '\n' then
431 b.append("\\n")
432 else if c == '\0' then
433 b.append("\\0")
434 else if c == '"' then
435 b.append("\\\"")
436 else if c == '\\' then
437 b.append("\\\\")
438 else if c == '`' then
439 b.append("'")
440 else if c.ascii < 32 then
441 b.append("\\{c.ascii.to_base(8, false)}")
442 else
443 b.add(c)
444 end
445 end
446 return b.to_s
447 end
448 end
449
450 # Create a tool context to handle options and paths
451 var toolcontext = new ToolContext
452 toolcontext.process_options
453
454 # Here we launch the nit index
455 var ni = new NitIndex(toolcontext)
456 ni.start
457
458 # TODO seek methods by return type :<type>
459 # TODO seek methods by param type: (<type>)
460 # TODO seek subclasses and super classes <.<class> >.<class>
461 # TODO seek subclasses and super types <:<type> >:<type>
462 # TODO sort by alphabetic order
463 # TODO seek with regexp
464 # TODO standardize namespaces with private option