The main method of a program.

In a module, the instructions defined outside any classes or methods (usually called the main of the module) is an implicit definition of this main method. Basically it means that the following program

print "Hello World"

is equivalent with

redef class Sys
   redef fun main do
      print "Hello World"
   end
end

Property definitions

core $ Sys :: main
	# The main method of a program.
	#
	# In a module, the instructions defined outside any classes or methods
	# (usually called the *main* of the module) is
	# an implicit definition of this `main` method.
	# Basically it means that the following program
	#
	# ~~~nit
	# print "Hello World"
	# ~~~
	#
	# is equivalent with
	#
	# ~~~nit
	# redef class Sys
	#    redef fun main do
	#       print "Hello World"
	#    end
	# end
	# ~~~
	fun main do end
lib/core/kernel.nit:261,2--281,16

app :: app_base $ Sys :: main
if "NIT_TESTING".environ == "true" then exit 0

test_bound_platform

app.setup
app.run
lib/app/app_base.nit:132,1--137,7

functional :: functional_gen $ Sys :: main
var fw = new FileWriter.open("functional_types.nit")
generate_functypes(20, fw)
lib/functional/functional_gen.nit:147,1--148,26

ai :: queens $ Sys :: main
var quiet = false

# The board size
var size = 8

# Basic argument parsing
if args.length > 0 and args.first == "-q" then
	args.shift
	quiet = true
end
if args.length > 0 then
	size = args.first.to_i
	if size <= 0 then
		print "usage: queens [-q] [size]\n -q for quiet"
		exit 1
	end
end

print "The {size}-queens problem"
var pb = new QueenProblem(size)
var s = pb.solve
var sols = 0
while s.is_running do
	if s.run != null then
		if not quiet then pb.print_state(s.state)
		sols += 1
	end
end
print "Found {sols} solutions"
lib/ai/examples/queens.nit:125,1--153,30

cocoa :: hello_cocoa $ Sys :: main
hello_world
lib/cocoa/examples/hello_cocoa.nit:29,1--11

dot :: clusters $ Sys :: main
var graph = new DotGraph("G", "digraph")

var cl0 = new DotGraph("cluster_0", "subgraph")
cl0["label"] = "process #1"
cl0["style"] = "filled"
cl0["color"] = "lightgrey"
cl0.nodes_attrs["style"] = "filled"
cl0.nodes_attrs["color"] = "white"

var a0 = cl0.add_node("a0")
var a1 = cl0.add_node("a1")
var a2 = cl0.add_node("a2")
var a3 = cl0.add_node("a3")
cl0.add_edge(a0, a1)
cl0.add_edge(a1, a2)
cl0.add_edge(a2, a3)

graph.add cl0

var cl1 = new DotGraph("cluster_1", "subgraph")
cl1["label"] = "process #2"
cl1["color"] = "blue"
cl1.nodes_attrs["style"] = "filled"

var b0 = cl1.add_node("b0")
var b1 = cl1.add_node("b1")
var b2 = cl1.add_node("b2")
var b3 = cl1.add_node("b3")
cl1.add_edge(b0, b1)
cl1.add_edge(b1, b2)
cl1.add_edge(b2, b3)

graph.add cl1

var start = graph.add_node("start")
start["shape"] = "Mdiamond"

var nend = graph.add_node("end")
nend["shape"] = "Msquare"

graph.add_edge(start, a0)
graph.add_edge(start, b0)
graph.add_edge(a1, b3)
graph.add_edge(b2, a3)
graph.add_edge(a3, a0)
graph.add_edge(a3, nend)
graph.add_edge(b3, nend)

if args.is_empty then
	print graph.to_dot
	# graph.show
else
	graph.to_dot.write_to_file args.first
end
lib/dot/examples/clusters.nit:20,1--73,3

dot :: hello $ Sys :: main
var graph = new DotGraph("G", "digraph")

var hello = graph.add_node("hello")
var world = graph.add_node("world")
graph.add_edge(hello, world)

if args.is_empty then
	print graph.to_dot
else
	graph.to_dot.write_to_file args.first
end
lib/dot/examples/hello.nit:20,1--30,3

dot :: undirected_clusters $ Sys :: main
var graph = new DotGraph("G", "graph")

var a = new DotNode("a")
var b = new DotNode("b")
var c = new DotNode("c")
var d = new DotNode("d")
var e = new DotNode("e")
var f = new DotNode("f")
var g = new DotNode("g")

var clA = new DotGraph("clusterA", "subgraph")
clA.add_edge(a, b).directed = false
graph.add clA

var clB = new DotGraph("clusterB", "subgraph")
clB.add_edge(c, d).directed = false
clA.add clB

var clC = new DotGraph("clusterC", "subgraph")
clC.add_edge(e, g).directed = false
graph.add clC

graph.add_edge(e, d).directed = false
graph.add_edge(f, g).directed = false

if args.is_empty then
	print graph.to_dot
else
	graph.to_dot.write_to_file args.first
end
lib/dot/examples/undirected_clusters.nit:20,1--49,3

html :: html_page $ Sys :: main
var page = new NitHomepage
page.write_to stdout
page.write_to_file("nit.html")
lib/html/examples/html_page.nit:105,1--107,30

curl :: curl_http $ Sys :: main
if args.length < 2 then
	print_usage
	exit 1
end

var url = args[1]
var request = new CurlHTTPRequest(url)
request.verbose = false # Set to `true` to debug

if args[0] == "GET" then
	# HTTP Get Request
	var response = request.execute

	if response isa CurlResponseSuccess then
		print "Status code: {response.status_code}"
		print "Body: {response.body_str}"
	else if response isa CurlResponseFailed then
		print "Error code: {response.error_code}"
		print "Error msg: {response.error_msg}"
	end

else if args[0] == "POST" then
	# HTTP Post Request
	var my_http_fetcher = new MyHttpFetcher
	request.delegate = my_http_fetcher

	var post_data = new HeaderMap
	post_data["Bugs Bunny"] = "Daffy Duck"
	post_data["Batman"] = "Robin likes special characters @#ùà!è§'(\"é&://,;<>∞~*"
	post_data["Batman"] = "Yes you can set multiple identical keys, but APACHE will consider only one, the last one"
	request.data = post_data
	var response = request.execute

	print "Our body from the callback: {my_http_fetcher.fetched_body}"

	if response isa CurlResponseSuccess then
		print "*** Answer ***"
		print "Status code: {response.status_code}"
		print "Body should be empty, because we decided to manage callbacks: {response.body_str.length}"
	else if response isa CurlResponseFailed then
		print "Error code: {response.error_code}"
		print "Error msg: {response.error_msg}"
	end

else if args[0] == "GET_FILE" then
	# HTTP Get to file Request
	var headers = new HeaderMap
	headers["Accept"] = "Moo"
	request.headers = headers
	var response = request.download_to_file(null)

	if response isa CurlFileResponseSuccess then
		print "*** Answer ***"
		print "Status code: {response.status_code}"
		print "Size downloaded: {response.size_download}"
	else if response isa CurlResponseFailed then
		print "Error code: {response.error_code}"
		print "Error msg: {response.error_msg}"
	end

else
	print_usage
	exit 1
end
lib/curl/examples/curl_http.nit:41,1--104,3

cocoa :: cocoa_message_box $ Sys :: main
if "NIT_TESTING".environ != "true" then dialog
lib/cocoa/examples/cocoa_message_box.nit:32,1--46

markdown :: nitmd $ Sys :: main
var opt_to = new OptionString("Specify output format (html, md, man)", "-t", "--to")

var usage = new Buffer
usage.append "Usage: nitmd [-t format] <file.md>\n"
usage.append "Translate Markdown documents to other formats."

var config = new Config
config.add_option(opt_to)
config.tool_description = usage.write_to_string

config.parse_options(args)
if config.args.length != 1 then
	config.usage
	exit 1
end

var file = config.args.first
if not file.file_exists then
	print "'{file}' not found"
	exit 1
end

var ifs = new FileReader.open(file)
var md = ifs.read_all
ifs.close

var processor = new MarkdownProcessor
var to = opt_to.value
if to == null or to == "html" then
	# Noop
else if to == "md" then
	processor.decorator = new MdDecorator
else if to == "man" then
	processor.decorator = new ManDecorator
else
	print "Unknown output format: {to}"
	exit 1
end
print processor.process(md)
lib/markdown/nitmd.nit:24,1--62,27

bcm2835 :: input $ Sys :: main
assert bcm2835_init else print "Failed to init"

var out = new RPiPin.p1_11
out.fsel = new FunctionSelect.outp
out.write(false)

var inp = new RPiPin.p1_22
inp.fsel = new FunctionSelect.inpt
inp.pud = new PUDControl.down

var last_in = false
loop
	var lev = inp.lev
	if lev != last_in then
		last_in = lev
		if lev then print "button pressed"
	end

	out.write(true)
	100.bcm2835_delay
	out.write(false)
	100.bcm2835_delay
end
lib/bcm2835/examples/input.nit:21,1--43,3

gettext :: langannot $ Sys :: main
var t = new X
print t.foo

print "This String is a test"

print """Multiline string

example


of the language annotation capacities
"""

var s = "example"

print "This superstring {s} rocks"

print "This superstring %1 rocks".format(s)
lib/gettext/examples/langannot.nit:28,1--45,43

libevent :: libevent_example $ Sys :: main
if "NIT_TESTING".environ == "true" then exit 0

# Setup libevent system
var event_base = new NativeEventBase
var factory = new MyFactory(event_base)

# Open a TCP socket for listening
factory.bind_tcp("localhost", 8888)

# Open a UNIX domain socket for listening
factory.bind_unix("/tmp/my.sck")

# Launch event loop
event_base.dispatch

event_base.free
lib/libevent/libevent_example.nit:42,1--57,15

pthreads :: threaded_example $ Sys :: main
print "main"
foo
bar(10, "parameterized and threaded")
sys.nanosleep(5,0)
var x  = baz(2, 3)
print "main, waiting for baz"
var y = x.join
print("baz result : " + y.to_s)
lib/pthreads/examples/threaded_example.nit:41,1--48,31

pthreads :: concurrent_array_and_barrier $ Sys :: main
var n_threads = 20

# This `ConcurrentArray` has its own `Mutex`
var array = new ConcurrentArray[String]

# Use an explicit `Barrier`
var barrier = new Barrier(n_threads)

# Create all our threads
var threads = new Array[Thread]
for t in n_threads.times do
	var thread = new MyThread(array, barrier, t)
	threads.add thread
	thread.start
end

# Wait for the threads to complete
for thread in threads do
	print "Thread {thread.join or else "null"} is done"
end

print "{array.length} strings inserted"
lib/pthreads/examples/concurrent_array_and_barrier.nit:51,1--72,39

socket :: socket_client $ Sys :: main
if args.length < 2 then
	print "Usage : socket_client <host> <port>"
	exit 1
end

var address = args[0]
var port = args[1].to_i

# Open a conection with the server
var s = new TCPStream.connect(address, port)
printn "Connecting to {s.host}:{s.port} at {s.address}... "
print if s.connected then "Connected" else "Connection failed"

if s.connected then
	# Communicate
	s.write "Hello server!\n"
	print s.read_line
	s.write "Bye server!\n"
	print s.read_line

	s.close
end
lib/socket/examples/socket_client.nit:22,1--43,3

socket :: socket_simple_server $ Sys :: main
if args.is_empty then
	print "Usage : socket_simple_server <port>"
	exit 1
end

var port = args[0].to_i

# Open the listening socket
var socket = new TCPServer(port)
socket.listen 4
socket.blocking = false

print "Listening on port {socket.port}"

# Loop until a single client connects
var client: nullable TCPStream = null
while client == null do
	printn "."
	sys.nanosleep(0, 200000)

	client = socket.accept
end
print " Connected"

# Communicate
print client.read_line
client.write "Hello client!\n"
print client.read_line
client.write "Bye client!\n"

client.close
lib/socket/examples/socket_simple_server.nit:20,1--50,12

privileges :: drop_privileges $ Sys :: main
var opts = new OptionContext
var opt_ug = new OptionUserAndGroup.for_dropping_privileges
opt_ug.mandatory = true
opts.add_option(opt_ug)

# parse and check command line options
opts.parse(args)
if not opts.errors.is_empty then
	print opts.errors.join("\n")
	print "Usage: drop_privileges [options]"
	opts.usage
	exit 1
end

# original user
print "before {sys.uid}:{sys.gid}"

# make the switch
var user_group = opt_ug.value
assert user_group != null
user_group.drop_privileges

# final user
print "after {sys.uid}:{sys.egid}"
lib/privileges/examples/drop_privileges.nit:23,1--46,34

pthreads :: jointask_example $ Sys :: main
var tp = new ThreadPool
var t0 = new StringTask(10, "First, long task", 0)
var tasks = new Array[StringTask]
for i in 5.times do
	tasks.add(new StringTask(1, "Small task", i + 1))
end
tp.execute(t0)
for t in tasks do tp.execute(t)
for t in tasks do
	t.join
	print t.value
end
t0.join
print t0.value
lib/pthreads/examples/jointask_example.nit:39,1--52,14

pthreads :: threadpool_example $ Sys :: main
var tp = new ThreadPool
for i in 100.times do
	var t = new HWTask(2.rand, i)
	tp.execute(t)
end

nanosleep(20,10)
lib/pthreads/examples/threadpool_example.nit:36,1--42,16

sdl2 :: minimal $ Sys :: main
sys.sdl.initialize((new SDLInitFlags).video)
check_error "init"

# Init `sdl2::image`
sdl.img.initialize((new SDLImgInitFlags).png)
check_error "img_init"

# Create a window
var window = new SDLWindow("Window title!".to_cstring, 800, 600, (new SDLWindowFlags).opengl)
check_error "window"

# Create a render, the suffested one
var renderer = new SDLRenderer(window, -1, (new SDLRendererFlags).accelerated)
check_error "renderer"

# Load an image
var surface = new SDLSurface.load("assets/fighter.png".to_cstring)
check_error "surface"
assert not surface.address_is_null

# Alternative code to load a BMP image without `sdl2::image`
#
# var surface = new SDLSurface.load_bmp("assets/fighter.bmp".to_cstring)

# Set the window icon
window.icon = surface
check_error "icon"

# Get a texture out of that surface
var texture = new SDLTexture.from_surface(renderer, surface)
check_error "texture"

# Allocate memory for reusable objects
var event = new SDLEventBuffer.malloc
var src = new SDLRect.nil
var dst = new SDLRect(0, 0, 128, 128)

# Set the colors we will be using
var white = new SDLColor(255, 255, 255, 255)
var green = new SDLColor(  0, 255,   0, 255)
var spacy = new SDLColor( 25,  25,  50, 255)

loop
	# Loop over events until we get a quit event
	while event.poll_event do
		var higher_event = event.to_event
		if higher_event isa SDLQuitEvent then
			break label out
		else if higher_event isa SDLMouseButtonDownEvent then
			# Update `dst` to be centered on the latest click
			dst.x = higher_event.x - dst.w/2
			dst.y = higher_event.y - dst.h/2
		end
	end

	# Clear the screen with a spacy color
	renderer.draw_color = spacy
	renderer.clear

	# Draw the target box for the following `copy`
	renderer.draw_color = green
	renderer.draw_rect dst

	# Copy a texture to the screen
	renderer.draw_color = white
	renderer.copy(texture, src, dst)

	# Copy the back buffer to the screen
	renderer.present

	check_error "present"

	33.delay
end label out

# Free all resources
event.free
src.free
dst.free

texture.free
surface.free

window.destroy
sdl.img.quit
sys.sdl.quit
lib/sdl2/examples/minimal/src/minimal.nit:35,1--120,12

crapto :: repeating_key_xor_solve $ Sys :: main
if args.length != 1 then
	print "Usage: repeating_key_xor_solve <cipher_file>"
	exit 1
end

# Read the cipher from the file
var cipher_bytes = args[0].to_path.read_all_bytes.decode_base64

# Create a RepeatingKeyXorCipher object to manipulate your ciphertext
var xorcipher = new RepeatingKeyXorCipher
xorcipher.ciphertext = cipher_bytes

# Try to find the best candidate key
xorcipher.find_key

# Decrypt the cipher according to the found key
xorcipher.decrypt

# Check the resulting plaintext out...
print xorcipher.plaintext
lib/crapto/examples/repeating_key_xor_solve.nit:21,1--40,25

websocket :: websocket_server $ Sys :: main
var sock = new WebsocketServer.with_infos(8088, 1)

var msg: String

if sock.listener.closed then
	print sys.errno.strerror
end

var cli: WebsocketConnection

while not sock.closed do
	cli = sock.accept
	while cli.connected do
		if sys.stdin.poll_in then
			msg = gets
			printn "Sending message : {msg}"
			if msg == "disconnect" then cli.close
			cli.write(msg)
		end
		if cli.can_read(10) then
			msg = ""
			while cli.can_read(0) do msg += cli.read(100)
			if msg != "" then print msg
		end
	end
end
lib/websocket/examples/websocket_server.nit:22,1--47,3

nitc :: nitpm $ Sys :: main
opts.add_option(opt_help, opt_verbose)
opts.parse
var rest = opts.rest

if opt_help.value then
	print_help
	exit 0
end

if opts.errors.not_empty then
	for error in opts.errors do print error
	print ""
	print_help
	exit 1
end

if rest.is_empty then
	print_help
	exit 1
end

# Find and apply action
var action_name = rest.shift
var action = commands.get_or_null(action_name)
if action != null then
	action.apply rest
else
	print_help
	exit 1
end
src/nitpm.nit:426,1--455,3

vsm :: example_vsm $ Sys :: main
var config = new Config
config.tool_description = "usage: example_vsm <files>"
config.parse_options(args)

if args.length < 1 then
	config.usage
	exit 1
end

var index = new FileIndex
index.whitelist_exts = config.opt_white_exts.value
index.blacklist_exts = config.opt_black_exts.value

print "Building index..."
index.index_files(args, true)
print "Indexed {index.documents.length} documents"

loop
	print "\nEnter query:"
	printn "> "
	var input = sys.stdin.read_line
	var matches = index.match_string(input)
	printn ""
	for match in matches do
		print match
	end
end
lib/vsm/examples/example_vsm.nit:39,1--65,3

markdown2 :: nitmd $ Sys :: main
var opt_to = new OptionString("Specify output format (html, md, man, latex)", "-t", "--to")

var usage = new Buffer
usage.append "Usage: nitmd [-t format] [file.md]\n"
usage.append "Translate Markdown documents to other formats.\n\n"
usage.append "If no argument, read the Markdown input from `stdin`."

var config = new Config
config.add_option(opt_to)
config.tool_description = usage.write_to_string

config.parse_options(args)
if config.args.length > 1 then
	config.usage
	exit 1
end

var md
if config.args.is_empty then
	md = sys.stdin.read_all
else
	var file = config.args.first
	if not file.file_exists then
		print "'{file}' not found"
		exit 1
	end
	md = file.to_path.read_all
end

# Parse the input
var parser = new MdParser
var node = parser.parse(md)

var renderer: MdRenderer
var to = opt_to.value
if to == null or to == "html" then
	renderer = new HtmlRenderer
else if to == "md" then
	renderer = new MarkdownRenderer
else if to == "man" then
	renderer = new ManRenderer
else if to == "latex" then
	renderer = new LatexRenderer
else
	print "Unknown output format: {to}"
	exit 1
	return
end
printn renderer.render(node)
lib/markdown2/nitmd.nit:25,1--73,28

actors :: chameneosredux $ Sys :: main
var n = if args.is_empty then 600 else args[0].to_i

print_all_colors
print ""

work(n, 3)
work(n, 10)
lib/actors/examples/chameneos-redux/chameneosredux.nit:148,1--154,11

actors :: fannkuchredux $ Sys :: main
n = if args.is_empty then 7 else args[0].to_i

fact = new Array[Int].with_capacity(n+1)
fact[0] = 1
for i in [1..n] do fact.add(fact[i-1] * i)

chunk_sz = (fact[n] + n_chunks - 1) / n_chunks
n_tasks = (fact[n] + chunk_sz - 1) / chunk_sz
max_flips = new Array[Int].with_capacity(n_tasks)
for i in [0..n_tasks[ do max_flips.add(0)
chk_sums = new Array[Int].with_capacity(n_tasks)
for i in [0..n_tasks[ do chk_sums.add(0)

var actors = new Array[FannkuchRedux].with_capacity(nb_actors)
for i in [0..nb_actors[ do
	var a = new FannkuchRedux
	actors.add(a)
	a.async.run
end

for i in [0..nb_actors[ do
	actors[i].async.terminate
	actors[i].async.wait_termination
end

var res = 0
for i in max_flips do res = res.max(i)

var chk = 0
for i in chk_sums do
	chk += i
end

print_result(n, res, chk)
lib/actors/examples/fannkuchredux/fannkuchredux.nit:151,1--184,25

actors :: mandelbrot $ Sys :: main
n = if args.is_empty then 200 else args[0].to_i

sys.crb = new Array[Float].with_capacity(n)
sys.cib = new Array[Float].with_capacity(n)
sys.inv_n = 2.0 / n.to_f
for i in [0..n[ do
	sys.cib[i] = i.to_f * inv_n - 1.0
	sys.crb[i] = i.to_f * inv_n - 1.5
end
sys.data = new Array[Array[Int]].with_capacity(n)
for i in [0..n[ do sys.data[i] = new Array[Int].filled_with(0, (n) / 8)

# Parallel Approach
var actors = new Array[Worker]
for i in [0..nb_threads[ do
	var a = new Worker
	actors.add(a)
	a.async.work
end

for a in actors do
	a.async.terminate
	a.async.wait_termination
end

var filename = "WRITE".environ
if filename == "" then filename = "out"
var output = new FileWriter.open(filename)
output.write_bytes("P4\n{n} {n}\n".to_bytes)
for i in [0..n[ do
	var length = data[i].length
	for j in [0..length[ do output.write_byte(data[i][j])
end
output.close
lib/actors/examples/mandelbrot/mandelbrot.nit:83,1--116,12

actors :: simple $ Sys :: main
var a = new A

# Make an asynchronous call
a.async.foo

# Make a synchronous call
a.foo

# Make an asynchronous call
# Which return a `Future[Int]` instead of `Int`
var r = a.async.bar(5)

# Retrieve the value of the future
print r.join

# Make a Synchronous call
print a.bar(5)
lib/actors/examples/simple/simple.nit:34,1--50,14

actors :: thread_ring $ Sys :: main
var first = new ThreadRing(1)
var current = new ThreadRing(2)
first.next = current
for i in [3..nb_actors] do
	var t = new ThreadRing(i)
	current.next = t
	current = t
end
current.next = first
var n = if args.is_empty then 1000 else args[0].to_i
first.send_token(n)
lib/actors/examples/thread-ring/thread_ring.nit:46,1--56,19

serialization :: custom_serialization $ Sys :: main
var a = new A("a", 1)
var b = new B("b", a)

a.ser_json
a.ser_json2
b.ser_json
b.ser_json2
lib/serialization/examples/custom_serialization.nit:149,1--155,11

glesv2 :: opengles2_hello_triangle $ Sys :: main
if "NIT_TESTING".environ == "true" then exit(0)

var window_width = 800
var window_height = 600

#
## SDL2
#
assert sdl.initialize((new SDLInitFlags).video) else
	print sdl.error
end

var sdl_window = new SDLWindow("Title".to_cstring, window_width, window_height, (new SDLWindowFlags).opengl)
assert not sdl_window.address_is_null else print sdl.error

var sdl_wm_info = sdl_window.wm_info
var native_window = sdl_wm_info.window_handle
var native_display = sdl_wm_info.display_handle
assert not native_display.address_is_null else print "Failed to get handle to native display"

#
## EGL
#
var egl_display = new EGLDisplay(native_display)
assert egl_display.is_valid else print "EGL display is not valid"

egl_display.initialize
assert egl_display.is_valid else print egl_display.error

print "EGL version: {egl_display.version}"
print "EGL vendor: {egl_display.vendor}"
print "EGL extensions: \n* {egl_display.extensions.join("\n* ")}"
print "EGL client APIs: {egl_display.client_apis.join(", ")}"

var config_chooser = new EGLConfigChooser
#config_chooser.surface_type_egl
config_chooser.blue_size = 8
config_chooser.green_size = 8
config_chooser.red_size = 8
#config_chooser.alpha_size = 8
#config_chooser.depth_size = 8
#config_chooser.stencil_size = 8
#config_chooser.sample_buffers = 1
config_chooser.close

var configs = config_chooser.choose(egl_display)
assert configs != null else print "choosing config failed: {egl_display.error}"
assert not configs.is_empty else print "no EGL config"

print "{configs.length} EGL configs available"
for config in configs do
	var attribs = config.attribs(egl_display)
	print "* caveats: {attribs.caveat}"
	print "  conformant to: {attribs.conformant}"
	print "  size of RGBA: {attribs.red_size} {attribs.green_size} {attribs.blue_size} {attribs.alpha_size}"
	print "  buffer, depth, stencil: {attribs.buffer_size} {attribs.depth_size} {attribs.stencil_size}"
end

var config = configs.first

var surface = egl_display.create_window_surface(config, native_window, [0])
assert surface.is_ok else print egl_display.error

var context = egl_display.create_context(config)
assert context.is_ok else print egl_display.error

var make_current_res = egl_display.make_current(surface, surface, context)
assert make_current_res else print egl_display.error

var width = surface.attribs(egl_display).width
var height = surface.attribs(egl_display).height
print "Width: {width}"
print "Height: {height}"

assert egl_bind_opengl_es_api else print "eglBingAPI failed: {egl_display.error}"

#
## GLESv2
#

print "Can compile shaders? {gl.shader_compiler}"
assert_no_gl_error

assert gl.shader_compiler else print "Cannot compile shaders"

# gl program
print glGetError.to_s
var program = new GLProgram
if not glIsProgram(program) then
	print "Program is not ok: {glGetError.to_s}\nLog:"
	print glGetProgramInfoLog(program)
	abort
end
assert_no_gl_error

# vertex shader
var vertex_shader = new GLVertexShader
assert glIsShader(vertex_shader) else print "Vertex shader is not ok: {glGetError}"
glShaderSource(vertex_shader, """
attribute vec4 vPosition;
void main()
{
  gl_Position = vPosition;
}
""".to_cstring)
glCompileShader vertex_shader
assert vertex_shader.is_compiled else print "Vertex shader compilation failed with: {glGetShaderInfoLog(vertex_shader)} {glGetProgramInfoLog(program)}"
assert_no_gl_error

# fragment shader
var fragment_shader = new GLFragmentShader
assert glIsShader(fragment_shader) else print "Fragment shader is not ok: {glGetError}"
glShaderSource(fragment_shader, """
precision mediump float;
void main()
{
	gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
""".to_cstring)
glCompileShader(fragment_shader)
assert fragment_shader.is_compiled else print "Fragment shader compilation failed with: {glGetShaderInfoLog(fragment_shader)}"
assert_no_gl_error

glAttachShader(program, vertex_shader)
glAttachShader(program, fragment_shader)
program.bind_attrib_location(0, "vPosition")
glLinkProgram program
assert program.is_linked else print "Linking failed: {glGetProgramInfoLog(program)}"
assert_no_gl_error

# prepare
glViewport(0, 0, width, height)
glClearColor(0.5, 0.0, 0.5, 1.0)

# draw!
var vertices = [0.0, 0.5, 0.0, -0.5, -0.5, 0.0, 0.5, -0.5, 0.0]
var vertex_array = new VertexArray(0, 3, vertices)
vertex_array.attrib_pointer

var clock = new Clock

var n_frames = 1000
for i in [0..n_frames[ do
	printn "."
	assert_no_gl_error

	glClear gl_COLOR_BUFFER_BIT
	glUseProgram program
	vertex_array.enable
	glDrawArrays(gl_TRIANGLES, 0, 3)
	egl_display.swap_buffers(surface)
end

print "FPS: {n_frames.to_f/clock.lapse.to_f}"

# delete
glDeleteProgram program
glDeleteShader vertex_shader
glDeleteShader fragment_shader

#
## EGL
#
# close
egl_display.make_current(new EGLSurface.none, new EGLSurface.none, new EGLContext.none)
egl_display.destroy_context context
egl_display.destroy_surface surface

#
## SDL2
#
# close
sdl.quit
lib/glesv2/examples/opengles2_hello_triangle.nit:29,1--201,8

dom :: checker $ Sys :: main
if args.length != 1 then
	print_error "Usage: checker xml_file"
	exit 2
end

var path = args.first
if not path.file_exists then
	print_error "Path '{path}' does not exist"
	exit 3
end

# Read file
var content = path.to_path.read_all

# Parse XML
var xml = content.to_xml

# Check for errors
if xml isa XMLError then
	print_error "XML file at '{path}' is invalid:"
	print_error xml.message
	var loc = xml.location
	if loc != null then print_error loc
	exit 1
else
	print "XML file at '{path}' is valid"
end
lib/dom/examples/checker.nit:17,1--43,3

actors :: simple_simulation $ Sys :: main
var nb_steps = 0
var nb_agents = 0
if args.is_empty or args.length != 2 then
	nb_steps = 10
	nb_agents = 10
else
	nb_steps = args[0].to_i
	nb_agents = args[1].to_i
end

var agents = new Array[Agent]
for i in [0..nb_agents[ do agents.add(new Agent)
for a in agents do for b in agents do if a != b then a.others.add(b)
clock_agent = new ClockAgent(nb_steps, agents)
clock_agent.async.do_step
lib/actors/examples/agent_simulation/simple_simulation.nit:43,1--57,25

gamnit :: texture_atlas_parser $ Sys :: main
var opts = new OptionContext
var opt_name = new OptionString("Name of the module to generate", "--name", "-n")
var opt_dir = new OptionString("Folder where to write the generated module", "--dir")
opts.add_option(opt_name, opt_dir)
opts.parse
var rest = opts.rest

if opts.errors.not_empty then
	print_error opts.errors
	exit 1
end

if rest.is_empty then
	print_error "Error: Expected the path to the XML file as argument"
	exit 2
end

# Prepare to read XML file and gather the attributes
var xml_file = rest.first
var attributes = new Array[String]

# Insert the first attribute, to load the root texture
var png_file = "images" / xml_file.basename("xml") + "png"
attributes.add """
	var root_texture = new TextureAsset("{{{png_file}}}")"""

# Read XML file
var content = xml_file.to_path.read_all
var xml = content.to_xml
if xml isa XMLError then
	print_error "RSS Parse Error: {xml.message}:{xml.location or else "null"}"
	exit 3
end

var items = xml["TextureAtlas"].first.children
for item in items do if item isa XMLOnelinerTag then
	var x = null
	var y = null
	var width = null
	var height = null
	var name = null
	for attr in item.attributes do if attr isa XMLStringAttr then
		if attr.name == "x" then
			x = attr.value.to_i
		else if attr.name == "y" then
			y = attr.value.to_i
		else if attr.name == "width" then
			width = attr.value.to_i
		else if attr.name == "height" then
			height = attr.value.to_i
		else if attr.name == "name" then
			name = attr.value
		end
	end

	if x != null and y != null and width != null and height != null and name != null then
		name = name.strip_extension(".png").to_snake_case

			var coords = "{x}, {y}, {width}, {height}"
			attributes.add """
	var {{{name}}}: Texture = root_texture.subtexture({{{coords}}})"""
	else
		print_error "Error on {item}"
	end
end

var module_name = opt_name.value
if module_name == null then module_name = "spritesheet"
var class_name = module_name.capitalized.to_camel_case

# Generate Nit code
var nit_module = new NitModule(module_name)
nit_module.header = """
# This file is generated by texture_atlas_parser
"""

nit_module.content.add """
import gamnit::display
import gamnit::textures

class {{{class_name}}}
"""

for a in attributes do nit_module.content.add a

nit_module.content.add """
end"""

var dir = opt_dir.value
if dir != null then
	var out_path = dir / module_name + ".nit"
	nit_module.write_to_file out_path
else
	printn nit_module.write_to_string
end
lib/gamnit/texture_atlas_parser.nit:23,1--117,3

markdown2 :: commonmark_gen $ Sys :: main
if args.length != 2 then
	print "Usage: commonmark_gen <tests.json> <output_dir>"
	exit 1
end

var gen = new TestGenerator(args.first, args.last)
gen.gen_tests
lib/markdown2/tests/commonmark_gen.nit:245,1--251,13

curl :: curl_rest $ Sys :: main
var url = "http://example.com"

# POST REQUEST
var my_request = new CurlHTTPRequest(url, method="POST")
var person = new Person("Jean",12)
my_request.body = person.serialize_to_json
my_request.execute
lib/curl/examples/curl_rest.nit:31,1--37,18

nlp :: nlp_index $ Sys :: main
var config = new Config
config.tool_description = "usage: example_index <files>"
config.parse_options(args)

if args.length < 1 then
	config.usage
	exit 1
end

var host = config.opt_server.value
if host == null then host = "http://localhost:9000"
var lang = config.opt_lang.value
if lang == null then lang = "en"

var cli = new NLPClient(host)
cli.language = lang

var bl = config.opt_black_exts.value
if bl.is_empty then bl = ["CD", "SYM", "-RRB-", "-LRB-", "''", "``", ".", "#", ":", ",", "$", ""]

var index = new NLPFileIndex(cli)
index.whitelist_exts = config.opt_white_exts.value
index.blacklist_exts = bl

print "Building index..."
index.index_files(args, true)

print "Indexed {index.documents.length} documents"

loop
	print "\nEnter query:"
	printn "> "
	var input = sys.stdin.read_line
	var matches = index.match_string(input)

	for match in matches do
		print match
	end
end
lib/nlp/examples/nlp_index.nit:43,1--81,3

nlp :: nlp_server $ Sys :: main
var config = new Config
config.parse_options(args)

var cp = config.opt_java_cp.value
if cp == null then cp = "stanfordnlp/*"

var srv = new NLPServer(cp, config.opt_port.value)
srv.start
lib/nlp/examples/nlp_server.nit:30,1--37,9

nitc :: test_parser $ Sys :: main
var no_print = false
var only_lexer = false
var need_help = false
var no_file = false
var interactive = false
var xml = false

while not args.is_empty and args.first.chars.first == '-' do
	if args.first == "-n" then
		no_print = true
	else if args.first == "-l" then
		only_lexer = true
	else if args.first == "-p" then
		only_lexer = false
	else if args.first == "-x" then
		xml = true
	else if args.first == "-e" then
		no_file = true
	else if args.first == "-i" then
		interactive = true
	else if args.first == "-h" or args.first == "-?" then
		need_help = true
	else
		stderr.write("Unknown option {args.first}.\n")
		exit(0)
	end
	args.shift
end

if (args.is_empty and not interactive) or need_help then
	print("usage:")
	print("  test_parser [options]... <filename.nit>...")
	print("  test_parser -e [options]... <text>...")
	print("  test_parser -i [options]...")
	print("options:")
	print("  -n	do not print anything")
	print("  -l	only lexer")
	print("  -p	lexer and parser (default)")
	print("  -x	instead of a ascii tree, output a XML document")
	print("  -e	instead on files, each argument is a content to parse")
	print("  -i	tree to parse are read interactively")
	print("  -h	print this help")
else if interactive then
	if only_lexer then
		print "Error: -l and -i are incompatible"
		exit 1
	else if no_file then
		print "Error: -e and -i are incompatible"
		exit 1
	else if not args.is_empty then
		print "Error: -i works without arguments"
		exit 1
	end

	var tc = new ToolContext

	loop
		var n = tc.interactive_parse("-->")
		if n isa TString then
			var s = n.text
			if s == ":q" then
				break
			else
				print "`:q` to quit"
			end
			continue
		end

		if n isa AError then
			print "{n.location.colored_line("0;31")}: {n.message}"
			continue
		end

		if not no_print then
			n.dump_tree
		end
	end
else
	for a in args do
		var source
		if no_file then
			source = new SourceFile.from_string("", a)
		else
			var f = new FileReader.open(a)
			source = new SourceFile(a, f)
			f.close
		end
		var lexer = new Lexer(source)
		if only_lexer then
			var token = lexer.next
			while not token isa EOF do
				if not no_print then
					print("Read token at {token.location} text='{token.text}'")
				end
				token = lexer.next
			end
		else
			var parser = new Parser(lexer)
			var tree = parser.parse

			var error = tree.n_eof
			if error isa AError then
				print("Error at {error.location}:\n\t{error.message}")
				return
			end

			if xml then
				tree.parentize_tokens
				tree.to_xml.write_to(stdout)
			else if not no_print then
				tree.dump_tree
			end
		end
	end
end
src/test_parser.nit:24,1--138,3

mpi :: mpi_simple $ Sys :: main
var mpi = new MPI

var data = new CIntArray(2)
if comm_world.size == 1 then
	print "not enough nodes, got only 1"
	mpi.finalize
	exit 1
end

print "stdout: processor '{mpi.processor_name}' {comm_world.rank}/{comm_world.size}"

if comm_world.rank == 0.rank then
	# send - ints
	data[0] = 123
	data[1] = 456
	mpi.send_from(data, 0, 2, 1.rank, 0.tag, comm_world)

	# send - simple string
	mpi.send_all("Hello", 1.rank, 0.tag, comm_world)
	mpi.send_from(" World", 0, 6, 1.rank, 0.tag, comm_world)
	mpi.send_from("+-!0?", 2, 2, 1.rank, 0.tag, comm_world)
else if comm_world.rank == 1.rank then

	# recv - ints
	mpi.recv_into(data, 0, 2, 0.rank, 0.tag, comm_world)
	print "received data: {data[0]} {data[1]}"

	# recv - simple string
	var buf = new FlatBuffer.with_capacity(5)
	mpi.recv_fill(buf, 0.rank, 0.tag, comm_world)
	print "received string: {buf}"

	mpi.recv_into(buf, 5, 6, 0.rank, 0.tag, comm_world)
	print "received string: {buf}"

	mpi.recv_into(buf, 3, 2, 0.rank, 0.tag, comm_world)
	print "received string: {buf}"
end

# Passing complex objects and inverse sender/receiver
if comm_world.rank == 0.rank then
	var errors = 0
	var processors_per_host = new HashMap[String, Int]

	# recv - serializable
	for p in [1 .. comm_world.size[ do
		var a = mpi.recv(new Rank.any, 0.tag, comm_world)
		print "received serialized: {a or else "<null>"}"

		if a != null and a isa ProcessorInfo then
			if not processors_per_host.keys.has(a.name) then
				processors_per_host[a.name] = 1
			else processors_per_host[a.name] += 1
		else errors += 1
	end

	print "errors: {errors}"
	print "processors: {processors_per_host.join(", ", ": ")}"
else
	# send - serializable
	srand_from comm_world.rank.to_i
	var a = new ProcessorInfo(mpi)
	mpi.send(a, 0.rank, 0.tag, comm_world)
end

mpi.finalize
lib/mpi/examples/src/mpi_simple.nit:41,1--106,12

nitcorn :: nitcorn_reverse_proxy $ Sys :: main
var vh = new VirtualHost("localhost:8080")

# Create the interface to represent your proxy target
var proxy_interface = new Interface("localhost", 31337)

# Add your action as usual
vh.routes.add new Route("/", new ProxyAction(proxy_interface))

# Let it be (serve)
var factory = new HttpFactory.and_libevent
factory.config.virtual_hosts.add vh
factory.run
lib/nitcorn/examples/src/nitcorn_reverse_proxy.nit:23,1--34,11

nitc :: nitls $ Sys :: main
var tc = new ToolContext

var opt_keep = new OptionBool("Ignore errors and files that are not a Nit source file", "-k", "--keep")
var opt_recursive = new OptionBool("Process directories recursively", "-r", "--recursive")
var opt_tree = new OptionBool("List source files in their groups and packages", "-t", "--tree")
var opt_source = new OptionBool("List source files in a flat list", "-s", "--source")
var opt_package = new OptionBool("List packages in a flat list (default)", "-P", "--package")
var opt_depends = new OptionBool("List dependencies of given modules", "-d", "--depends")
var opt_make = new OptionBool("List dependencies suitable for a rule in a Makefile (alias for -d, -p and -s)", "-M")
var opt_paths = new OptionBool("List only path (instead of name + path)", "-p", "--path-only")

tc.option_context.add_option(opt_keep, opt_recursive, opt_tree, opt_source, opt_package, opt_depends, opt_paths, opt_make)
tc.tooldescription = "Usage: nitls [OPTION]... <file.nit|directory>...\nLists the packages and/or paths of Nit sources files."
tc.accept_no_arguments = true
tc.process_options(args)

if opt_make.value then
	opt_depends.value = true
	opt_paths.value = true
	opt_source.value = true
end

var sum = opt_tree.value.to_i + opt_source.value.to_i + opt_package.value.to_i
if sum > 1 then
	print "Error: options --tree, --source, and --package are exclusive."
	print tc.tooldescription
	exit 1
end
if sum == 0 then opt_package.value = true
tc.keep_going = opt_keep.value

var model = new Model
var mb = new ModelBuilder(model, tc)

if tc.option_context.rest.is_empty then tc.option_context.rest.add "."
var files
if opt_recursive.value then
	files = new Array[String]
	for d in tc.option_context.rest do
		var pipe = new ProcessReader("find", d, "-name", "*.nit")
		while not pipe.eof do
			var l = pipe.read_line
			if l == "" then break # last line
			files.add l
		end
		pipe.close
		pipe.wait
		if pipe.status != 0 and not opt_keep.value then exit 1
	end
else
	files = tc.option_context.rest
end

if sum == 0 then
	# If one of the file is a group, default is `opt_tree` instead of `opt_package`
	for a in files do
		var g = mb.identify_group(a)
		if g != null then
			opt_tree.value = true
			opt_package.value = false
			break
		end
	end
end

var mmodules = mb.scan_full(files)

# Load modules to get more informations
for mmodule in mmodules do
	if not opt_paths.value or opt_depends.value then
		var ast = mmodule.parse(mb)
		if ast != null and opt_depends.value then
			mb.build_module_importation(ast)
		end
	end
end
#tc.check_errors

if opt_depends.value then
	# Extends the list of module with the loaded ones
	mmodules = mb.parsed_modules.to_a
end

var ot = new ProjTree(tc)
if opt_tree.value then
	ot.opt_paths = opt_paths.value
	var mgroups = new HashSet[MGroup]
	for mp in mmodules do
		var pa = mp.mgroup
		while pa != null and not pa.is_interesting do pa = pa.parent
		ot.add(pa, mp)
		while pa != null do
			mgroups.add pa
			pa = pa.parent
		end
	end
	for g in mgroups do
		var pa = g.parent
		if g.is_interesting then
			ot.add(pa, g)
		end
	end
	ot.sort_with(alpha_comparator)
	ot.write_to(stdout)
end

if opt_source.value then
	alpha_comparator.sort(mmodules)
	for mp in mmodules do
		if opt_make.value then
			print mp.filepath.escape_to_mk
		else if opt_paths.value then
			print mp.filepath.as(not null)
		else
			print "{mp.mgroup.full_name}{ot.display(mp)}"
		end
	end
end

if opt_package.value then
	var mpackages = new Array[MPackage]
	for m in mmodules do
		var p = m.mgroup.mpackage
		if mpackages.has(p) then continue
		mpackages.add p
	end

	alpha_comparator.sort(mpackages)
	for p in mpackages do
		var g = p.root.as(not null)
		var path = g.filepath.as(not null)
		if opt_paths.value then
			print path
		else
			var d = ""
			var md = g.mdoc_or_fallback
			if md != null then
				if tc.opt_no_color.value then
					d = ": {md.content.first}"
				else
					d = ": {md.content.first.green}"
				end
			end
			if tc.opt_no_color.value then
				print "{g.name}{d} ({path})"
			else
				print "{g.name}{d} ({path.yellow})"
			end
		end
	end
end
src/nitls.nit:90,1--240,3

nitc :: test_phase $ Sys :: main
var toolcontext = new ToolContext
toolcontext.tooldescription = "Usage: [OPTION]... <file.nit>..."

# We do not add other options, so process them now!
toolcontext.process_options(args)

# Get arguments
var arguments = toolcontext.option_context.rest

# We need a model to collect stufs
var model = new Model
# An a model builder to parse files
var modelbuilder = new ModelBuilder(model, toolcontext)

# Here we load an process all modules passed on the command line
var mmodules = modelbuilder.parse_full(arguments)
modelbuilder.run_phases
toolcontext.run_global_phases(mmodules)
src/test_phase.nit:50,1--67,39

nitc :: nitpretty $ Sys :: main
var toolcontext = new ToolContext

var opts = toolcontext.option_context
opts.add_option(toolcontext.opt_dir, toolcontext.opt_output)
opts.add_option(toolcontext.opt_diff, toolcontext.opt_meld, toolcontext.opt_check)
opts.add_option(toolcontext.opt_line_width, toolcontext.opt_break_str, toolcontext.opt_inline_do)
opts.add_option(toolcontext.opt_no_inline)
opts.add_option(toolcontext.opt_skip_empty)

toolcontext.tooldescription = "Usage: nitpretty [OPTION]... <file.nit>\n" +
	"Pretty print Nit code from Nit source files."

toolcontext.process_options args
var arguments = toolcontext.option_context.rest
# build model
var model = new Model
var mbuilder = new ModelBuilder(model, toolcontext)
var mmodules = mbuilder.parse_full(arguments)
mbuilder.run_phases

if mmodules.is_empty then
	print "Error: no module to pretty print"
	return
end

if not toolcontext.opt_check.value and mmodules.length > 1 then
	print "Error: only --check option allow multiple modules"
	return
end

var dir = toolcontext.opt_dir.value or else ".nitpretty"
if not dir.file_exists then dir.mkdir
var v = new PrettyPrinterVisitor

v.max_size = toolcontext.opt_line_width.value
if toolcontext.opt_break_str.value then
	v.break_strings = true
end
if toolcontext.opt_inline_do.value then
	v.inline_do = true
end
if toolcontext.opt_skip_empty.value then
	v.skip_empty = true
end
if toolcontext.opt_no_inline.value then
	v.no_inline = true
end

for mmodule in mmodules do
	var nmodule = mbuilder.mmodule2node(mmodule)
	if nmodule == null then
		print " Error: no source file for module {mmodule}"
		return
	end
	var file = "{dir}/{mmodule.name}.nit"
	var tpl = v.pretty_nmodule(nmodule)
	tpl.write_to_file file

	if toolcontext.opt_check.value then
		var res = diff(nmodule.location.file.filename, file)

		if not res.is_empty then
			print "Wrong formating for module {nmodule.location.file.filename}"
			toolcontext.info(res, 1)

			if toolcontext.opt_meld.value then
				sys.system "meld {nmodule.location.file.filename} {file}"
			end
		else
			toolcontext.info("[OK] {nmodule.location.file.filename}", 1)
		end
	else
		# write to file
		var out = toolcontext.opt_output.value
		if out != null then sys.system "cp {file} {out}"

		# open in meld
		if toolcontext.opt_meld.value then
			sys.system "meld {arguments.first} {file}"
			return
		end

		# show diff
		if toolcontext.opt_diff.value then
			var res = diff(arguments.first, file)
			if not res.is_empty then print res
			return
		end

		# show pretty
		if not toolcontext.opt_quiet.value then tpl.write_to sys.stdout
	end
end
src/nitpretty.nit:73,1--165,3

nitc :: nitpick $ Sys :: main
var toolcontext = new ToolContext
toolcontext.tooldescription = "Usage: nitpick [OPTION]... <file.nit>...\nCollect potential style and code issues."

# We do not add other options, so process them now!
toolcontext.process_options(args)

# Do not stop phases on errors
toolcontext.keep_going = true

# Get arguments
var arguments = toolcontext.option_context.rest

# We need a model to collect stuffs
var model = new Model
# A model builder to parse files
var modelbuilder = new ModelBuilder(model, toolcontext)

# Here we load and process all modules passed on the command line
var mmodules = modelbuilder.parse_full(arguments)
toolcontext.mmodules_to_check.add_all mmodules

# Blacklist warnings of not explicitly required modules
for mm in model.mmodules do
	if mmodules.has(mm) then continue
	toolcontext.warning_blacklist[mm.location.file].add("all")
end

modelbuilder.run_phases
toolcontext.run_global_phases(mmodules)
if toolcontext.error_count > 0 then exit(1)
src/nitpick.nit:35,1--64,43

nitc :: nitj $ Sys :: main
var toolcontext = new ToolContext
toolcontext.process_options(args)

# We need a model to collect stufs
var model = new Model
# And a model builder to parse files
var modelbuilder = new ModelBuilder(model, toolcontext)

# Collect arguments
var arguments = toolcontext.option_context.rest
if arguments.is_empty then
	toolcontext.option_context.usage
	return
end
if arguments.length > 1 then
	print "Too much arguments: {arguments.join(" ")}"
	toolcontext.option_context.usage
	return
end
var progname = arguments.first

# Here we load an process all modules passed on the command line
var mmodules = modelbuilder.parse([progname])

if mmodules.is_empty then return
modelbuilder.run_phases

var mainmodule
if mmodules.length == 1 then
	mainmodule = mmodules.first
else
	mainmodule = new MModule(model, null, mmodules.first.name, mmodules.first.location)
	mainmodule.set_imported_mmodules(mmodules)
end

var analysis = modelbuilder.do_rapid_type_analysis(mainmodule)

# Do compilation
modelbuilder.run_java_compiler(mainmodule, analysis)
src/nitj.nit:21,1--59,52

nitc :: nituml $ Sys :: main
var toolcontext = new ToolContext
toolcontext.process_options(args)
var arguments = toolcontext.option_context.rest

# build model
var model = new Model
var mbuilder = new ModelBuilder(model, toolcontext)
var mmodules = mbuilder.parse_full(arguments)

if mmodules.is_empty then return
mbuilder.run_phases
toolcontext.run_global_phases(mmodules)
src/nituml.nit:59,1--70,39

nitc :: test_model_index $ Sys :: main
var toolcontext = new ToolContext
toolcontext.process_options(args)
var args = toolcontext.option_context.rest

if args.is_empty then
	print "usage: test_model_index nitfiles..."
	exit 1
	return
end

# build model
var model = new Model
var mbuilder = new ModelBuilder(model, toolcontext)
var mmodules = mbuilder.parse_full(args)

# process
if mmodules.is_empty then return
mbuilder.run_phases
toolcontext.run_global_phases(mmodules)

# Build index
var filters = new ModelFilter(
	private_visibility,
	accept_fictive = false,
	accept_test = false)
var index = new ModelIndex
for mentity in model.collect_mentities(filters) do
	if mentity isa MClassDef or mentity isa MPropDef then continue
	index.index(mentity)
end

var query = toolcontext.opt_query.value
if query == null then
	print "# Interactive mode, type `:q` to quit\n\n"
	printn "> "
	var line = stdin.read_line
	while line != ":q" do
		print ""
		var time = search(index, toolcontext, line.trim)
		print ""
		print "Query executed in {time} seconds."
		print ""
		printn "> "
		line = stdin.read_line
	end
	return
end

search(index, toolcontext, query)
src/test_model_index.nit:86,1--134,33

nitc :: nitpackage $ Sys :: main
var toolcontext = new ToolContext
var tpl = new Template
tpl.add "Usage: nitpackage [OPTION]... <file.nit>...\n"
tpl.add "Helpful features about packages."
toolcontext.tooldescription = tpl.write_to_string

# process options
toolcontext.process_options(args)
var arguments = toolcontext.option_context.rest

# build model
var model = new Model
var mbuilder = new ModelBuilder(model, toolcontext)
var mmodules = mbuilder.parse_full(arguments)

# process
if mmodules.is_empty then return
mbuilder.run_phases
toolcontext.run_global_phases(mmodules)
src/nitpackage.nit:773,1--791,39

nitcorn :: htcpcp_server $ Sys :: main
var server = new HTCPCServer(1227)

server.run
lib/nitcorn/examples/src/htcpcp_server.nit:101,1--103,10

nitcorn :: nitcorn_hello_world $ Sys :: main
var vh = new VirtualHost("localhost:8080")

# Serve index.html with our custom handler
vh.routes.add new Route("/index.html", new StaticAction)
vh.routes.add new Route("/hello/:name", new ParamAction)

# Serve everything else with a standard `FileServer` with a root at "www/hello_world/"
vh.routes.add new Route(null, new FileServer("www/hello_world/"))

var factory = new HttpFactory.and_libevent
factory.config.virtual_hosts.add vh
factory.run
lib/nitcorn/examples/src/nitcorn_hello_world.nit:71,1--82,11

nitc :: nitrestful $ Sys :: main
var toolcontext = new ToolContext
toolcontext.tooldescription = """
Usage: nitrestful [OPTION] module.nit [other_module.nit [...]]
Generates the boilerplate code to link RESTful request to static Nit methods."""

toolcontext.process_options args
var arguments = toolcontext.option_context.rest

# Check options
if toolcontext.opt_output.value != null and toolcontext.opt_dir.value != null then
	print "Error: cannot use both --dir and --output"
	exit 1
end
if arguments.length > 1 and toolcontext.opt_output.value != null then
	print "Error: --output needs a single source file. Do you prefer --dir?"
	exit 1
end

var model = new Model
var modelbuilder = new ModelBuilder(model, toolcontext)

var mmodules = modelbuilder.parse(arguments)
modelbuilder.run_phases
var first_mmodule = mmodules.first

# Name of the support module
var module_name

# Path to the support module
var module_path = toolcontext.opt_output.value
if module_path == null then
	module_name = "{first_mmodule.name}_rest"
	module_path = "{module_name}.nit"

	var dir = toolcontext.opt_dir.value
	if dir != null then module_path = dir.join_path(module_path)
else if module_path == "stdout" then
	module_name = "{first_mmodule.name}_rest"
	module_path = null
else if module_path.has_suffix(".nit") then
	module_name = module_path.basename(".nit")
else
	module_name = module_path.basename
	module_path += ".nit"
end

var nit_module = new NitModule(module_name)
nit_module.annotations.add """generated"""
nit_module.annotations.add """no_warning("parentheses")"""
nit_module.header = """
# This file is generated by nitrestful
# Do not modify, instead refine the generated services.
"""

for mmod in mmodules do
	nit_module.imports.add mmod.name
end

var phase = toolcontext.restful_phase
assert phase isa RestfulPhase

for mclassdef in phase.restful_classes do
	var mclass = mclassdef.mclass

	var t = new Template
	nit_module.content.add t

	var classes = new Template
	nit_module.content.add classes

	t.add """
redef class {{{mclass}}}
	redef fun prepare_respond_and_close(request, truncated_uri, http_server)
	do
		var resources = truncated_uri.split("/")
		if resources.not_empty and resources.first.is_empty then resources.shift

		if resources.length != 1 then
			super
			return
		end
		var resource = resources.first

"""
	var methods = mclassdef.restful_methods
	for i in methods.length.times, method in methods do
		var msig = method.intro.msignature
		if msig == null then continue

		# Condition to select this method from a request
		var conds = new Array[String]

		# Name of the resource from the method or as renamed
		var resource_conds = new Array[String]
		for resource in method.restful_resources do resource_conds.add "resource == \"{resource}\""
		conds.add "(" + resource_conds.join(" or ") + ")"

		# HTTP methods/verbs
		if method.restful_verbs.not_empty then
			var method_conds = new Array[String]
			for meth in method.restful_verbs do method_conds.add "request.method == \"{meth}\""
			conds.add "(" + method_conds.join(" or ") + ")"
		end

		t.add """
		if {{{conds.join(" and ")}}} then
"""

		# Extract the arguments from the request for the method call
		var args = new Array[String]
		var isas = new Array[String]
		for param in msig.mparameters do

			t.add """
			var in_{{{param.name}}} = request.string_arg("{{{param.name}}}")
"""

			var mtype = param.mtype
			var bound_mtype = mclassdef.bound_mtype
			var resolved_mtype = mtype.resolve_for(bound_mtype, bound_mtype, mclassdef.mmodule, true)
			var resolved_type_name = resolved_mtype.name

			resolved_mtype.gen_arg_convert(t, param.name)

			var arg = "out_{param.name}"
			args.add arg

			if mtype.needs_type_check then
				isas.add "{arg} isa {mtype.name}"
			end

			t.add "\n"
		end

		if isas.not_empty then t.add """
			if {{{isas.join(" and ")}}} then
"""

		var sig = ""
		if args.not_empty then sig = "({args.join(", ")})"

		if not method.restful_async then
			# Synchronous method
			t.add """
				var response = {{{method.name}}}{{{sig}}}
				http_server.respond response
				http_server.close
				return
"""
		else
			# Asynchronous method
			var task_name = "Task_{mclass}_{method.name}"
			args.unshift "http_server"
			args.unshift "request"
			args.unshift "self"

			t.add """
				var task = new {{{task_name}}}({{{args.join(", ")}}})
				self.thread_pool.execute task
				return
"""

			var thread_attribs = new Array[String]
			for param in msig.mparameters do
				thread_attribs.add """
	private var out_{{{param.name}}}: {{{param.mtype}}}"""
			end

			classes.add """

# Generated task to execute {{{mclass}}}::{{{method.name}}}
class {{{task_name}}}
	super RestfulTask

	redef type A: {{{mclass}}}

{{{thread_attribs.join("\n")}}}

	redef fun indirect_restful_method
	do
		return action.{{{method.name}}}{{{sig}}}
	end
end
"""
		end

		if isas.not_empty then t.add """
			end
"""
		t.add """
		end
"""
	end

	t.add """
		super
	end
end"""
end

# Write support module
if module_path != null then
	# To file
	nit_module.write_to_file module_path
else
	# To stdout
	nit_module.write_to stdout
end
src/nitrestful.nit:149,1--356,3

nitc :: nitserial $ Sys :: main
var toolcontext = new ToolContext
toolcontext.tooldescription = """
Usage: nitserial [OPTION] program.nit [other_program.nit [...]]
Generates a serialization support module"""

toolcontext.process_options(args)
var arguments = toolcontext.option_context.rest

# Check options
if toolcontext.opt_output.value != null and toolcontext.opt_dir.value != null then
	print "Error: cannot use both --dir and --output"
	exit 1
end
if arguments.length > 1 and toolcontext.opt_output.value != null then
	print "Error: --output needs a single source file. Do you prefer --dir?"
	exit 1
end

var model = new Model
var modelbuilder = new ModelBuilder(model, toolcontext)

var mmodules = modelbuilder.parse_full(arguments)
modelbuilder.run_phases

# Create a distinct support module per target modules
for mmodule in mmodules do
	# Name of the support module
	var module_name

	# Path to the support module
	var module_path = toolcontext.opt_output.value
	if module_path == null then
		module_name = "{mmodule.name}_serial"
		module_path = "{module_name}.nit"

		var dir = toolcontext.opt_dir.value
		if dir != null then module_path = dir.join_path(module_path)
	else if module_path == "stdout" then
		module_name = "{mmodule.name}_serial"
		module_path = null
	else if module_path.has_suffix(".nit") then
		module_name = module_path.basename(".nit")
	else
		module_name = module_path.basename
		module_path += ".nit"
	end

	var target_modules = null
	var importations = null
	var mgroup = mmodule.mgroup
	if toolcontext.opt_depth.value == 1 and mgroup != null then
		modelbuilder.scan_group mgroup
		target_modules = mgroup.mmodules
	else if toolcontext.opt_depth.value == 2 then
		# package
		target_modules = new Array[MModule]
		importations = new Array[MModule]
		if mgroup != null then
			for g in mgroup.mpackage.mgroups do
				target_modules.add_all g.mmodules
			end

			for g in mgroup.in_nesting.direct_smallers do
				var dm = g.default_mmodule
				if dm != null then
					importations.add dm
				end
			end

			for m in mgroup.mmodules do
				importations.add m
			end
		end
	end

	if target_modules == null then target_modules = [mmodule]
	if importations == null then importations = target_modules

	var nit_module = new NitModule(module_name)
	nit_module.annotations.add """generated"""
	nit_module.annotations.add """no_warning("property-conflict")"""
	nit_module.header = """
# This file is generated by nitserial
# Do not modify, but you can redef
"""

	for importation in importations do
		nit_module.imports.add importation.name
	end

	nit_module.imports.add "serialization"

	nit_module.content.add """
redef class Deserializer
	redef fun deserialize_class(name)
	do"""

	var serializable_type = mmodule.serializable_type
	var compiled_types = new Array[MType]
	for m in target_modules do
		nit_module.content.add """
		# Module: {{{m.to_s}}}"""

		var rta = modelbuilder.do_rapid_type_analysis(m)

		for mtype in rta.live_types do
			# We are only interested in instanciated generics, subtypes of Serializable
			# and which are visible.
			if mtype isa MGenericType and
			   mtype.is_subtype(m, null, serializable_type) and
			   mtype.mclass.kind == concrete_kind and
			   not compiled_types.has(mtype) then

				# Intrude import the modules declaring private classes
				var related_mclasses = mtype.related_mclasses(mmodule)
				for mclass in related_mclasses do
					if not mmodule.is_visible(mclass.intro_mmodule, mclass.visibility) then
						var intro_mmodule = mclass.intro_mmodule
						var intro_mgroup = intro_mmodule.mgroup

						var to_import = intro_mmodule.full_name
						if intro_mgroup == null or intro_mgroup.default_mmodule == intro_mmodule then
							to_import = intro_mmodule.name
						end

						nit_module.imports.add "intrude import {to_import}"
					end
				end

				compiled_types.add mtype
				nit_module.content.add """
		if name == \"{{{mtype}}}\" then return new {{{mtype}}}.from_deserializer(self)"""
			end
		end
	end

	nit_module.content.add """
		return super
	end
end"""

	# Compile support module
	if module_path != null then
		# To file
		nit_module.write_to_file module_path
	else
		# To stdout
		nit_module.write_to stdout
	end
end
src/nitserial.nit:81,1--230,3

nitc :: nitlight $ Sys :: main
var toolcontext = new ToolContext

# Try to colorize, even if programs are non valid
toolcontext.keep_going = true

var opt_fragment = new OptionBool("Omit document header and footer", "-f", "--fragment")
var opt_line_id_prefix = new OptionString("Prefix of the id of each line `<span>` element", "--line-id-prefix")
var opt_first_line = new OptionInt("Start the source file at this line (default: 1)", 0, "--first-line")
var opt_last_line = new OptionInt("End the source file at this line (default: to the end)", 0, "--last-line")
var opt_dir = new OptionString("Output html files in a specific directory (required if more than one module)", "-d", "--dir")
var opt_full = new OptionBool("Process also imported modules", "--full")
var opt_ast = new OptionBool("Generate specific HTML elements for each Node of the AST", "--ast")
var opt_noinfobox = new OptionBool("Disable the generation of infoboxes", "--no-infobox")
var opt_txt = new OptionBool("Generate text with ANSI coloring escape sequences", "--txt")
toolcontext.option_context.add_option(opt_fragment, opt_line_id_prefix, opt_first_line, opt_last_line, opt_dir, opt_full, opt_ast, opt_txt, opt_noinfobox)
toolcontext.tooldescription = "Usage: nitlight [OPTION]... <file.nit>...\nGenerates HTML of highlited code from Nit source files."
toolcontext.process_options(args)

var model = new Model
var modelbuilder = new ModelBuilder(model, toolcontext)

var args = toolcontext.option_context.rest

var mmodules = modelbuilder.parse_full(args)
modelbuilder.run_phases

if opt_full.value then mmodules = modelbuilder.parsed_modules

var dir = opt_dir.value
if dir != null then
	dir.mkdir
else if mmodules.length > 1 then
	print "More than one module to render, use option -d"
	return
end

if opt_txt.value then
	for mm in mmodules do
		var v = new AnsiHighlightVisitor
		v.include_loose_tokens = true
		v.include_whole_lines = true

		if opt_first_line.value != 0 then v.first_line = opt_first_line.value
		if opt_last_line.value != 0 then v.last_line = opt_last_line.value
		var m = modelbuilder.mmodule2node(mm)
		assert m != null

		v.highlight_node(m)
		var page = v.result

		if dir != null then
			page.write_to_file("{dir}/{mm.c_name}.txt")
		else
			page.write_to(stdout)
		end
	end
	return
end

for mm in mmodules do
	if dir != null then toolcontext.info("write {dir}/{mm.c_name}.html", 1)

	var v = new NitlightVisitor(mm, mmodules)
	var prefix = opt_line_id_prefix.value
	if prefix != null then
		v.line_id_prefix = prefix.trim
	end
	v.include_loose_tokens = true
	v.include_whole_lines = true

	if opt_first_line.value != 0 then v.first_line = opt_first_line.value
	if opt_last_line.value != 0 then v.last_line = opt_last_line.value
	if opt_ast.value then v.with_ast = true
	if opt_noinfobox.value then v.show_infobox = false
	var page = null
	var m = modelbuilder.mmodule2node(mm)
	assert m != null
	if not opt_fragment.value then
		page = new HTMLTag("html")
		page.add_raw_html """<head>
		<meta charset="utf-8">
		<title>file {{{m.location.file.filename}}}</title>"""
		if dir == null then
			page.add_raw_html """
			<style type="text/css">
			{{{v.css_content}}}
			</style>
			"""
		else
			page.add_raw_html """<link rel="stylesheet" type="text/css" href="style.css" />"""
		end
		page.add_raw_html v.head_content
		page.add_raw_html "</head><body><pre class='nit_code'>"
	end
	v.highlight_node(m)
	if not opt_fragment.value then
		page.add(v.html)
		page.add_raw_html "</pre>"
		page.add_raw_html v.foot_content
		page.add_raw_html "</body>"
	else
		page = v.html
	end

	if dir != null then
		page.write_to_file("{dir}/{mm.c_name}.html")
	else
		page.write_to(stdout)
	end
end

if dir != null then
	toolcontext.info("write {dir}/index.html", 1)

	var page = new HTMLTag("html")
	page.add_raw_html """<head>
	<meta charset="utf-8">
	</head><body><ul>
	"""
	for mm in mmodules do
		var n = new HTMLTag("li")
		var n2 = new HTMLTag("a")
		page.add n
		n.add n2
		n2.attr("href", "{mm.c_name}.html")
		n2.text(mm.full_name)
	end
	page.add_raw_html "</li></body>"
	page.write_to_file("{dir}/index.html")

	var v = new HtmlightVisitor
	toolcontext.info("write {dir}/style.css", 1)
	var f = new FileWriter.open("{dir}/style.css")
	f.write v.css_content
	f.close
end
src/nitlight.nit:85,1--220,3

nitc :: nitvm $ Sys :: main
var toolcontext = new ToolContext
toolcontext.tooldescription = "Usage: nitvm [OPTION]... <file.nit>...\nExecutes Nit programs with a virtual machine."
# Add an option "-o" to enable compatibility with the tests.sh script
var opt = new OptionString("compatibility (does nothing)", "-o")
toolcontext.option_context.add_option(opt)
var opt_mixins = new OptionArray("Additional modules to min-in", "-m")
toolcontext.option_context.add_option(opt_mixins)
# We do not add other options, so process them now!
toolcontext.process_options(args)

# We need a model to collect stufs
var model = new Model

# Add a model builder to parse files
var modelbuilder = new ModelBuilder(model, toolcontext)

var arguments = toolcontext.option_context.rest
var progname = arguments.first

# Here we load and process all modules passed on the command line
var mmodules = modelbuilder.parse([progname])
mmodules.add_all modelbuilder.parse(opt_mixins.value)
modelbuilder.run_phases

if toolcontext.opt_only_metamodel.value then toolcontext.quit

var mainmodule: nullable MModule

# Here we launch the interpreter on the main module
if mmodules.length == 1 then
	mainmodule = mmodules.first
else
	mainmodule = new MModule(model, null, mmodules.first.name, mmodules.first.location)
	mainmodule.set_imported_mmodules(mmodules)
end

var self_mm = mainmodule
var self_args = arguments

modelbuilder.run_virtual_machine(self_mm, self_args)
src/nitvm.nit:24,1--63,52

nitcorn :: simple_file_server $ Sys :: main
var opts = new OptionContext
var opt_drop = new OptionUserAndGroup.for_dropping_privileges
var opt_port = new OptionInt("Server port", 80, "--port", "-p")
var opt_help = new OptionBool("Print this message", "--help", "-h")
opts.add_option(opt_drop, opt_port, opt_help)
opts.parse args

# Check options errors and help
if not opts.errors.is_empty or opt_help.value then
	print opts.errors.join("\n")
	print "Usage: file_server [Options]"
	opts.usage
	exit 1
end

# Serve everything with a standard FilesHandler
var vh = new VirtualHost("localhost:{opt_port.value}")
vh.routes.add new Route(null, new FileServer("www/hello_world/"))
var factory = new HttpFactory.and_libevent
factory.config.virtual_hosts.add vh

# Drop to a low-privileged user
var user_group = opt_drop.value
if user_group != null then user_group.drop_privileges

factory.run
lib/nitcorn/examples/src/simple_file_server.nit:27,1--52,11

nitc :: nitsmells $ Sys :: main
var toolcontext = new ToolContext
toolcontext.tooldescription = "Usage: nitsmells [OPTION]... <file.nit>...\n Computes code smells on Nit programs."
# We do not add other options, so process them now!
toolcontext.process_options(args)
# Get arguments
var arguments = toolcontext.option_context.rest
# We need a model to collect stufs
var model = new Model
# An a model builder to parse files
var modelbuilder = new ModelBuilder(model, toolcontext)
# Here we load an process all modules passed on the command line
var mmodules = modelbuilder.parse_full(arguments)
modelbuilder.run_phases
print "*** CODE SMELLS METRICS ***"
toolcontext.run_global_phases(mmodules)
src/nitsmells.nit:25,1--39,39

nitc :: nitunit $ Sys :: main
var toolcontext = new ToolContext
toolcontext.keep_going = true

toolcontext.option_context.add_option(toolcontext.opt_full, toolcontext.opt_output, toolcontext.opt_dir, toolcontext.opt_noact, toolcontext.opt_pattern, toolcontext.opt_autosav, toolcontext.opt_gen_unit, toolcontext.opt_gen_force, toolcontext.opt_gen_private, toolcontext.opt_gen_show, toolcontext.opt_nitc)
toolcontext.tooldescription = "Usage: nitunit [OPTION]... <file.nit>...\nExecutes the unit tests from Nit source files."

toolcontext.process_options(args)
var args = toolcontext.option_context.rest

if toolcontext.opt_gen_unit.value then
	if toolcontext.opt_pattern.value != null then
		print "Option --pattern cannot be used with --gen-suite"
		exit(0)
	end
else
	if toolcontext.opt_gen_force.value then
		print "Option --force must be used with --gen-suite"
		exit(0)
	end
	if toolcontext.opt_gen_private.value then
		print "Option --private must be used with --gen-suite"
		exit(0)
	end
	if toolcontext.opt_gen_show.value then
		print "Option --only-show must be used with --gen-suite"
		exit(0)
	end
end

var model = new Model
var modelbuilder = new ModelBuilder(model, toolcontext)

var module_files = modelbuilder.filter_nit_source(args)

var mmodules = modelbuilder.parse_full(module_files)
modelbuilder.run_phases

if toolcontext.opt_gen_unit.value then
	modelbuilder.gen_test_unit(mmodules.first)
	exit(0)
end

# When testing `nitunit`, disable time.
if "NIT_TESTING".environ != "" then
	toolcontext.opt_no_time.value = true
end

"NIT_TESTING".setenv("true")
"NIT_TESTING_ID".setenv(pid.to_s)
"SRAND".setenv("0")

var test_dir = toolcontext.test_dir
test_dir.mkdir
"# This file prevents the Nit modules of the directory to be part of the package".write_to_file(test_dir / "packages.ini")

var page = new HTMLTag("testsuites")

if toolcontext.opt_full.value then mmodules = model.mmodules

for a in args do
	if not a.file_exists then
		toolcontext.fatal_error(null, "Error: cannot load file or module `{a}`.")
	end
	# Try to load the file as a markdown document
	var mdoc = modelbuilder.load_markdown(a)
	var ts = modelbuilder.test_mdoc(mdoc)
	if not ts.children.is_empty then page.add ts
end

for a in module_files do
	var g = modelbuilder.identify_group(a)
	if g == null then continue
	var ts = modelbuilder.test_group(g)
	if not ts.children.is_empty then page.add ts
end

for m in mmodules do
	var ts
	ts = modelbuilder.test_markdown(m)
	if not ts.children.is_empty then page.add ts
	ts = modelbuilder.test_unit(m)
	if ts != null and not ts.children.is_empty then page.add ts
end

var file = toolcontext.opt_output.value
if file == null then file = "nitunit.xml"
page.write_to_file(file)

# Print results
printn "Docunits: Entities: {modelbuilder.total_entities}; Documented ones: {modelbuilder.doc_entities}; With nitunits: {modelbuilder.unit_entities}"
if modelbuilder.unit_entities == 0 or toolcontext.opt_noact.value then
	print ""
else
	printn "; Failures: "
	var cpt = modelbuilder.failed_entities
	if toolcontext.opt_no_color.value then
		print cpt
	else if cpt == 0 then
		print "0".green.bold
	else
		print cpt.to_s.red.bold
	end
end
printn "Test suites: Classes: {modelbuilder.total_classes}; Test Cases: {modelbuilder.total_tests}"
if modelbuilder.total_tests == 0 or toolcontext.opt_noact.value then
	print ""
else
	printn "; Failures: "
	var cpt = modelbuilder.failed_tests
	if toolcontext.opt_no_color.value then
		print cpt
	else if cpt == 0 then
		print "0".green.bold
	else
		print cpt.to_s.red.bold
	end
end

var total = modelbuilder.unit_entities + modelbuilder.total_tests
var fail = modelbuilder.failed_entities + modelbuilder.failed_tests
if toolcontext.opt_noact.value then
	# nothing
else if total == 0 then
	var head = "[NOTHING]"
	if not toolcontext.opt_no_color.value then
		head = head.yellow
	end
	print "{head} No unit tests to execute."
else if fail == 0 then
	var head = "[SUCCESS]"
	if not toolcontext.opt_no_color.value then
		head = head.green.bold
	end
	print "{head} All {total} tests passed."
else
	var head = "[FAILURE]"
	if not toolcontext.opt_no_color.value then
		head = head.red.bold
	end
	print "{head} {fail}/{total} tests failed."

	print "`{test_dir}` is not removed for investigation."
	exit 1
end

test_dir.rmdir
src/nitunit.nit:22,1--167,14

nitc :: abstract_compiler $ Sys :: main
var toolcontext = new ToolContext

toolcontext.tooldescription = "Usage: nitc [OPTION]... file.nit...\nCompiles Nit programs."

# We do not add other options, so process them now!
toolcontext.process_options(args)

# We need a model to collect stufs
var model = new Model
# An a model builder to parse files
var modelbuilder = new ModelBuilder(model, toolcontext)

var arguments = toolcontext.option_context.rest
if toolcontext.opt_run.value then
	# When --run, only the first is the program, the rest is the run arguments
	arguments = [toolcontext.option_context.rest.shift]
end
if arguments.length > 1 and toolcontext.opt_output.value != null then
	print "Option Error: --output needs a single source file. Do you prefer --dir?"
	exit 1
end

# Here we load an process all modules passed on the command line
var mmodules = modelbuilder.parse(arguments)

if mmodules.is_empty then toolcontext.quit

modelbuilder.run_phases

for mmodule in mmodules do
	toolcontext.info("*** PROCESS {mmodule} ***", 1)
	var ms = [mmodule]
	toolcontext.run_global_phases(ms)
end
src/compiler/abstract_compiler.nit:4661,1--4694,3

nitc :: nitcatalog $ Sys :: main
var model = new Model
var tc = new ToolContext

var opt_dir = new OptionString("Directory where the HTML files are generated", "-d", "--dir")
var opt_no_git = new OptionBool("Do not gather git information from the working directory", "--no-git")
var opt_no_parse = new OptionBool("Do not parse nit files (no importation information)", "--no-parse")
var opt_no_model = new OptionBool("Do not analyse nit files (no class/method information)", "--no-model")

# Piwik tracker URL.
# If you want to monitor your visitors.
var opt_piwik_tracker = new OptionString("Piwik tracker URL (ex: `nitlanguage.org/piwik/`)", "--piwik-tracker")
# Piwik tracker site id.
var opt_piwik_site_id = new OptionString("Piwik site ID", "--piwik-site-id")

tc.option_context.add_option(opt_dir, opt_no_git, opt_no_parse, opt_no_model, opt_piwik_tracker, opt_piwik_site_id)

tc.process_options(sys.args)
tc.keep_going = true

var modelbuilder = new ModelBuilder(model, tc)
var catalog = new Catalog(modelbuilder)

catalog.piwik_tracker = opt_piwik_tracker.value
var piwik_site_id = opt_piwik_site_id.value
if piwik_site_id != null then
	if catalog.piwik_tracker == null then
		print_error "Warning: ignored `{opt_piwik_site_id}` because `{opt_piwik_tracker}` is not set."
	else if piwik_site_id.is_int then
		print_error "Warning: ignored `{opt_piwik_site_id}`, an integer is required."
	else
		catalog.piwik_site_id = piwik_site_id.to_i
	end
end


# Get files or groups
var args = tc.option_context.rest
var mmodules
if opt_no_parse.value then
	mmodules = modelbuilder.scan_full(args)
else
	mmodules = modelbuilder.parse_full(args)
end
var mpackages = modelbuilder.model.mpackage_importation_graph.vertices

# Scan packages and compute information
for p in mpackages do
	var g = p.root
	assert g != null
	modelbuilder.scan_group(g)
end

if not opt_no_git.value then for p in mpackages do
	catalog.git_info(p)
end

# Run phases to modelize classes and properties (so we can count them)
if not opt_no_model.value then
	modelbuilder.run_phases
end

var out = opt_dir.value or else "catalog.out"
(out/"p").mkdir
(out/"res").mkdir

catalog.outdir = out

# Generate the css (hard coded)
var css = """
body {
margin-top:			15px;
background-color:		#f8f8f8;
}

a {
color:				#0D8921;
text-decoration:		none;
}

a:hover {
color:				#333;
text-decoration:		none;
}

h1 {
font-weight:			bold;
color:                          #0D8921;
font-size:			22px;
}

h2 {
color:                          #6C6C6C;
font-size:			18px;
border-bottom:			solid 3px #CCC;
}

h3 {
color:                          #6C6C6C;
font-size:			15px;
border-bottom:			solid 1px #CCC;
}

ul {
list-style-type:		square;
}

dd {
color:				#6C6C6C;
margin-top:			1em;
margin-bottom:			1em;
}

pre {
border:				1px solid #CCC;
font-family:			Monospace;
color:				#2d5003;
background-color:		rgb(250, 250, 250);
}

code {
font-family:			Monospace;
color:				#2d5003;
}

footer {
margin-top:			20px;
}

.container {
margin:				0 auto;
padding:			0 20px;
}

.content {
float:				left;
margin-top:			40px;
width:				65%;
}

.sidebar {
float:				right;
margin-top:			40px;
width:				30%
}

.sidebar h3 {
color:                          #0D8921;
font-size:			18px;
border-bottom:			0px;
}

.box {
margin:				0;
padding:			0;
}

.box li {
line-height:			2.5;
white-space:			nowrap;
overflow:			hidden;
text-overflow:			ellipsis;
padding-right:			10px;
border-bottom:			1px solid rgba(0,0,0,0.2);
}
"""
css.write_to_file(out/"style.css")

# PAGES

for p in mpackages do
	# print p
	var f = "p/{p.name}.html"
	catalog.package_page(p)
	catalog.generate_page(p).write_to_file(out/f)
	# copy ini
	var ini = p.ini
	if ini != null then ini.write_to_file(out/"p/{p.name}.ini")
end

# INDEX

var index = catalog.new_page("")
index.more_head.add "<title>Packages in Nit</title>"

index.add """
<div class="content">
<h1>Packages in Nit</h1>
"""

index.add "<h2>Highlighted Packages</h2>\n"
index.add catalog.list_best(catalog.score)

if catalog.deps.vertices.not_empty then
	index.add "<h2>Most Required</h2>\n"
	var reqs = new Counter[MPackage]
	for p in mpackages do
		reqs[p] = catalog.deps.get_all_successors(p).length - 1
	end
	index.add catalog.list_best(reqs)
end

index.add "<h2>By First Tag</h2>\n"
index.add catalog.list_by(catalog.cat2proj, "cat_")

index.add "<h2>By Any Tag</h2>\n"
index.add catalog.list_by(catalog.tag2proj, "tag_")

index.add """
</div>
<div class="sidebar">
<h3>Stats</h3>
<ul class="box">
<li>{{{mpackages.length}}} packages</li>
<li>{{{catalog.maint2proj.length}}} maintainers</li>
<li>{{{catalog.contrib2proj.length}}} contributors</li>
<li>{{{catalog.tag2proj.length}}} tags</li>
<li>{{{catalog.mmodules.sum}}} modules</li>
<li>{{{catalog.mclasses.sum}}} classes</li>
<li>{{{catalog.mmethods.sum}}} methods</li>
<li>{{{catalog.loc.sum}}} lines of code</li>
</ul>
</div>
"""

index.write_to_file(out/"index.html")

# PEOPLE

var page = catalog.new_page("")
page.more_head.add "<title>People of Nit</title>"
page.add """<div class="content">\n<h1>People of Nit</h1>\n"""
page.add "<h2>By Maintainer</h2>\n"
page.add catalog.list_by(catalog.maint2proj, "maint_")
page.add "<h2>By Contributor</h2>\n"
page.add catalog.list_by(catalog.contrib2proj, "contrib_")
page.add "</div>\n"
page.write_to_file(out/"people.html")

# TABLE

page = catalog.new_page("")
page.more_head.add "<title>Projets of Nit</title>"
page.add """<div class="content">\n<h1>People of Nit</h1>\n"""
page.add "<h2>Table of Projets</h2>\n"
page.add catalog.table_packages(mpackages.to_a)
page.add "</div>\n"
page.write_to_file(out/"table.html")
src/nitcatalog.nit:553,1--799,36

nitc :: test_neo $ Sys :: main
var test_id = "NIT_TESTING_ID".environ
var test_name = "test_{test_id}"

# init tool
var toolcontext = new ToolContext
toolcontext.tooldescription = "Usage: neo_saver host port files..."
toolcontext.process_options(args)
var arguments = toolcontext.option_context.rest

if arguments.length < 3 then
	toolcontext.usage
	exit 0
end

var host = arguments.shift
var port = arguments.shift
var url = "http://{host}:{port}"

# parse model
toolcontext.info("Parse files...", 1)
var org_model = new Model
var modelbuilder = new ModelBuilder(org_model, toolcontext)
modelbuilder.parse(arguments)
modelbuilder.run_phases

toolcontext.info("Open connection to neo4j on {url} for saving...", 1)
var save_client = new Neo4jClient(url)
var save_model = new NeoModel(test_name, toolcontext, save_client)
save_model.save(org_model)

toolcontext.info("Open connection to neo4j on {url} for reading...", 1)
var read_client = new Neo4jClient(url)
var neo_model = new Model
var read_model = new NeoModel(test_name, toolcontext, read_client)
read_model.load(neo_model)

# Compare model
var sorter = new MEntityNameSorter

print "# mpackages:"
var org_mpackages = org_model.mpackages.to_a
sorter.sort org_mpackages
print org_mpackages.join(" ")
print "------------------------------------"
var neo_mpackages = neo_model.mpackages.to_a
sorter.sort neo_mpackages
print neo_mpackages.join(" ")

print "\n# mmodules:"
var org_mmodules = org_model.mmodules.to_a
sorter.sort org_mmodules
print org_mmodules.join(" ")
print "------------------------------------"
var neo_mmodules = neo_model.mmodules.to_a
sorter.sort neo_mmodules
print neo_mmodules.join(" ")

print "\n# mclasses:"
var org_mclasses = org_model.mclasses.to_a
sorter.sort org_mclasses
print org_mclasses.join(" ")
print "------------------------------------"
var neo_mclasses = neo_model.mclasses.to_a
sorter.sort neo_mclasses
print neo_mclasses.join(" ")

print "\n# mproperties:"
var org_mproperties = org_model.mproperties.to_a
sorter.sort org_mproperties
print org_mproperties.join(" ")
print "------------------------------------"
var neo_mproperties = neo_model.mproperties.to_a
sorter.sort neo_mproperties
print neo_mproperties.join(" ")

print "\n# msignatures:"
for org_mprop in org_mproperties do
	if not org_mprop isa MMethod then continue
	print "{org_mprop.name}{org_mprop.intro.msignature or else ""}"
end
print "------------------------------------"
for neo_mprop in neo_mproperties do
	if not neo_mprop isa MMethod then continue
	print "{neo_mprop.name}{neo_mprop.intro.msignature or else ""}"
end
src/test_neo.nit:22,1--106,3

nitc :: nitx $ Sys :: main
var toolcontext = new ToolContext
var tpl = new Template
tpl.add "Usage: nitx [OPTION]... <file.nit>... [query]\n"
tpl.add "Displays pieces of API information from Nit source files."
toolcontext.tooldescription = tpl.write_to_string

# process options
toolcontext.process_options(args)
var arguments = toolcontext.option_context.rest

# build model
var model = new Model
var mbuilder = new ModelBuilder(model, toolcontext)
var mmodules = mbuilder.parse_full(arguments)

# process
if mmodules.is_empty then return
mbuilder.run_phases
toolcontext.run_global_phases(mmodules)
var mainmodule = toolcontext.make_main_module(mmodules)

# build views
var catalog = null
if toolcontext.opt_catalog.value then
	catalog = new Catalog(mbuilder)
	catalog.build_catalog(model)
end

# start nitx
var nitx = new Nitx(model, mainmodule, mbuilder, catalog, toolcontext.opt_no_color.value)
var q = toolcontext.opt_command.value
if q != null then # shortcut prompt
	print ""
	nitx.do_command(q)
	return
end
nitx.start
src/nitx.nit:140,1--176,10

android :: nit_activity $ Sys :: main
app.setup
lib/android/nit_activity.nit:325,1--9

popcorn :: example_post_handler $ Sys :: main
var app = new App
app.use("/", new PostHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/handlers/example_post_handler.nit:36,1--38,29

popcorn :: example_query_string $ Sys :: main
var app = new App
app.use("/", new QueryStringHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/handlers/example_query_string.nit:36,1--38,29

popcorn :: example_hello $ Sys :: main
var app = new App
app.use("/", new HelloHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/hello_world/example_hello.nit:27,1--29,29

popcorn :: example_advanced_logger $ Sys :: main
var app = new App
app.use_before("/*", new RequestTimeHandler)
app.use("/", new AnotherHandler)
app.use_after("/*", new AdvancedLoggerHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/middlewares/example_advanced_logger.nit:52,1--56,29

popcorn :: example_html_error_handler $ Sys :: main
var app = new App
app.use("/*", new HtmlErrorHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/middlewares/example_html_error_handler.nit:51,1--53,29

popcorn :: example_simple_error_handler $ Sys :: main
var app = new App
app.use("/", new SomeHandler)
app.use("/*", new SimpleErrorHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/middlewares/example_simple_error_handler.nit:36,1--39,29

popcorn :: example_simple_logger $ Sys :: main
var app = new App
app.use_before("/*", new SimpleLoggerHandler)
app.use("/", new MyOtherHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/middlewares/example_simple_logger.nit:34,1--37,29

popcorn :: example_glob_route $ Sys :: main
var app = new App
app.use("/user/:user/item/:item/*", new UserItem)
app.listen("localhost", 3000)
lib/popcorn/examples/routing/example_glob_route.nit:35,1--37,29

popcorn :: example_param_route $ Sys :: main
var app = new App
app.use("/:user", new UserHome)
app.listen("localhost", 3000)
lib/popcorn/examples/routing/example_param_route.nit:34,1--36,29

popcorn :: example_router $ Sys :: main
var user_router = new Router
user_router.use("/*", new UserLogger)
user_router.use("/", new UserHomepage)
user_router.use("/profile", new UserProfile)

var app = new App
app.use("/", new AppHome)
app.use("/user", user_router)
app.listen("localhost", 3000)
lib/popcorn/examples/routing/example_router.nit:45,1--53,29

popcorn :: example_session $ Sys :: main
var app = new App
app.use("/*", new SessionInit)
app.use("/", new AppLogin)
app.listen("localhost", 3000)
lib/popcorn/examples/sessions/example_session.nit:42,1--45,29

popcorn :: example_static $ Sys :: main
var app = new App
app.use("/", new StaticHandler("public/"))
app.listen("localhost", 3000)
lib/popcorn/examples/static_files/example_static.nit:21,1--23,29

popcorn :: example_static_default $ Sys :: main
var app = new App
app.use("/", new StaticHandler("public/", "default.html"))
app.listen("localhost", 3000)
lib/popcorn/examples/static_files/example_static_default.nit:21,1--23,29

popcorn :: example_static_multiple $ Sys :: main
var app = new App
app.use("/", new StaticHandler("public/"))
app.use("/", new StaticHandler("files/"))
app.use("/static", new StaticHandler("public/"))
app.use("/static", new StaticHandler("files/"))
app.listen("localhost", 3000)
lib/popcorn/examples/static_files/example_static_multiple.nit:21,1--26,29

nitcorn :: restful_annot $ Sys :: main
var vh = new VirtualHost("localhost:8080")

# Set `rest_path` as the root for an instance of `MyAction`, so:
# * `MyClass::foo` is available as `localhost:8080/rest_path/foo?s=s&i=12&b=true`,
# * `MyClass::bar` is available as both `localhost:8080/rest_path/api_name?s=s`
#   and `localhost:8080/rest_path/alt_name?...`.
# * `MyClass::async_service` is available as `localhost:8080/rest_path/async_service?str=str`
# * `MyClass::complex_args` is available as
#   `localhost:8080/rest_path/complex_args?array=["a","b"]&data={"str":"asdf"}`
vh.routes.add new Route("rest_path", new MyAction)

var factory = new HttpFactory.and_libevent
factory.config.virtual_hosts.add vh
factory.run
lib/nitcorn/examples/src/restful_annot.nit:122,1--135,11

nitc :: nitdoc $ Sys :: main
var toolcontext = new ToolContext
var tpl = new Template
tpl.add "Usage: nitdoc [OPTION]... <file.nit>...\n"
tpl.add "Generates HTML pages of API documentation from Nit source files."
toolcontext.tooldescription = tpl.write_to_string

# process options
toolcontext.process_options(args)
var arguments = toolcontext.option_context.rest

# build model
var model = new Model
var mbuilder = new ModelBuilder(model, toolcontext)
var mmodules = mbuilder.parse_full(arguments)

# process
if mmodules.is_empty then return
print "Parsing code..."
mbuilder.run_phases
toolcontext.run_global_phases(mmodules)
src/nitdoc.nit:247,1--266,39

popcorn :: example_angular $ Sys :: main
var app = new App
app.use("/counter", new CounterAPI)
app.use("/*", new StaticHandler("www/", "index.html"))
app.listen("localhost", 3000)
lib/popcorn/examples/angular/example_angular.nit:45,1--48,29

popcorn :: example_mongodb $ Sys :: main
var mongo = new MongoClient("mongodb://mongo:27017/")
var db = mongo.database("mongo_example")

var app = new App
app.use("/", new UserList(db))
app.listen("localhost", 3000)
lib/popcorn/examples/mongodb/example_mongodb.nit:63,1--68,29

nitc :: nit $ Sys :: main
var toolcontext = new ToolContext
toolcontext.option_context.options_before_rest = true
toolcontext.tooldescription = "Usage: nit [OPTION]... <file.nit>...\nInterprets and debugs Nit programs."
# Add an option "-o" to enable compatibility with the tests.sh script
var opt = new OptionString("Does nothing. Used for compatibility.", "-o")
opt.hidden = true
toolcontext.option_context.add_option(opt)
var opt_eval = new OptionBool("Specifies the program from command-line", "-e")
var opt_loop = new OptionBool("Repeatedly run the program for each line in file-name arguments", "-n")
var opt_vm = new OptionBool("Run the virtual machine instead of the naive interpreter (experimental)", "--vm")
toolcontext.option_context.add_option(opt_eval, opt_loop, opt_vm)
# We do not add other options, so process them now!
toolcontext.process_options(args)

# We need a model to collect stufs
var model = new Model
# An a model builder to parse files
var modelbuilder = new ModelBuilder(model, toolcontext)

var arguments = toolcontext.option_context.rest
var progname = arguments.first

# Here we load an process all modules passed on the command line
var mmodules: Array[MModule]

if opt_eval.value then
	var amodule = toolcontext.parse_module(progname)
	toolcontext.check_errors

	var parent = null
	if opt_loop.value then
		parent = modelbuilder.get_mmodule_by_name(null, null, "niti_runtime")
		if parent == null then
			toolcontext.check_errors
			abort
		end
	end

	modelbuilder.load_rt_module(parent, amodule, "-")

	mmodules = [amodule.mmodule.as(not null)]
else if progname == "-" then
	var content = stdin.read_all
	var amodule = toolcontext.parse_module(content)
	toolcontext.check_errors
	modelbuilder.load_rt_module(null, amodule, "-")
	mmodules = [amodule.mmodule.as(not null)]
else
	mmodules = modelbuilder.parse([progname])
end

modelbuilder.run_phases

if toolcontext.opt_only_metamodel.value then toolcontext.quit

var mainmodule = toolcontext.make_main_module(mmodules)

var self_mm = mainmodule
var self_args = arguments

if opt_vm.value then
	modelbuilder.run_virtual_machine(self_mm, self_args)
else
	modelbuilder.run_naive_interpreter(self_mm, self_args)
end
src/nit.nit:26,1--90,3

nitc :: nitmetrics $ Sys :: main
var toolcontext = new ToolContext
toolcontext.tooldescription = "Usage: nitmetrics [OPTION]... <file.nit>...\nComputes various metrics on Nit programs."

# We do not add other options, so process them now!
toolcontext.process_options(args)

# Get arguments
var arguments = toolcontext.option_context.rest

# We need a model to collect stuff
var model = new Model
# And a model builder to parse files
var modelbuilder = new ModelBuilder(model, toolcontext)

# Here we load an process all modules passed on the command line
var mmodules = modelbuilder.parse_full(arguments)
modelbuilder.run_phases

print "*** METRICS ***"

toolcontext.run_global_phases(mmodules)
src/nitmetrics.nit:24,1--44,39

nitc :: nitweb $ Sys :: main
var toolcontext = new ToolContext
var tpl = new Template
tpl.add "Usage: nitweb [OPTION]... <file.nit>...\n"
tpl.add "Run a webserver based on nitcorn that serves pages about model."
toolcontext.tooldescription = tpl.write_to_string

# process options
toolcontext.process_options(args)
var arguments = toolcontext.option_context.rest

# build model
var model = new Model
var mbuilder = new ModelBuilder(model, toolcontext)
var mmodules = mbuilder.parse_full(arguments)

# process
if mmodules.is_empty then return
mbuilder.run_phases
toolcontext.run_global_phases(mmodules)
src/nitweb.nit:131,1--149,39