Identification and scoping of local variables and labels.

Introduced classes

class EscapeMark

nitc :: EscapeMark

Mark where break and continue will branch.
private class Scope

nitc :: Scope

private class ScopePhase

nitc :: ScopePhase

private class ScopeVisitor

nitc :: ScopeVisitor

Visit a npropdef and:
class Variable

nitc :: Variable

A local variable (including parameters, automatic variables and self)

Redefined classes

redef class AAssertExpr

nitc :: scope $ AAssertExpr

An assert statement
redef class ABreakExpr

nitc :: scope $ ABreakExpr

A break statement.
redef class ACallAssignExpr

nitc :: scope $ ACallAssignExpr

A setter call with a standard method-name and any number of arguments. eg x.m(y)=z. OR just a simple assignment.
redef class ACallExpr

nitc :: scope $ ACallExpr

A call with a standard method-name and any number of arguments. eg x.m(y). OR just a simple id
redef abstract class ACallFormExpr

nitc :: scope $ ACallFormExpr

Whatever looks-like a call with a standard method and any number of arguments.
redef class ACallReassignExpr

nitc :: scope $ ACallReassignExpr

A complex setter call with a standard method-name and any number of arguments. eg x.m(y)+=z. OR just a simple complex assignment.
redef class AContinueExpr

nitc :: scope $ AContinueExpr

A continue statement
redef class ADoExpr

nitc :: scope $ ADoExpr

A do statement
redef abstract class AEscapeExpr

nitc :: scope $ AEscapeExpr

A break or a continue
redef class AForExpr

nitc :: scope $ AForExpr

A for statement
redef class AForGroup

nitc :: scope $ AForGroup

A collection iterated by a for, its automatic variables and its implicit iterator.
redef class AIfExpr

nitc :: scope $ AIfExpr

A if statement
redef class ALambdaExpr

nitc :: scope $ ALambdaExpr

redef class ALoopExpr

nitc :: scope $ ALoopExpr

A loop statement
redef abstract class ANode

nitc :: scope $ ANode

Root of the AST class-hierarchy
redef class AParam

nitc :: scope $ AParam

A parameter definition in a signature. eg x:X
redef abstract class APropdef

nitc :: scope $ APropdef

The definition of a property
redef class AReturnExpr

nitc :: scope $ AReturnExpr

A return statement. eg return x
redef class ASelfExpr

nitc :: scope $ ASelfExpr

A read of self
redef abstract class AVarFormExpr

nitc :: scope $ AVarFormExpr

Whatever is an access to a local variable
redef class AVardeclExpr

nitc :: scope $ AVardeclExpr

A declaration of a local variable. eg var x: X = y
redef class AWhileExpr

nitc :: scope $ AWhileExpr

A while statement
redef class AWithExpr

nitc :: scope $ AWithExpr

A with statement
redef class ToolContext

nitc :: scope $ ToolContext

Global context for tools

All class definitions

redef class AAssertExpr

nitc :: scope $ AAssertExpr

An assert statement
redef class ABreakExpr

nitc :: scope $ ABreakExpr

A break statement.
redef class ACallAssignExpr

nitc :: scope $ ACallAssignExpr

A setter call with a standard method-name and any number of arguments. eg x.m(y)=z. OR just a simple assignment.
redef class ACallExpr

nitc :: scope $ ACallExpr

A call with a standard method-name and any number of arguments. eg x.m(y). OR just a simple id
redef abstract class ACallFormExpr

nitc :: scope $ ACallFormExpr

Whatever looks-like a call with a standard method and any number of arguments.
redef class ACallReassignExpr

nitc :: scope $ ACallReassignExpr

A complex setter call with a standard method-name and any number of arguments. eg x.m(y)+=z. OR just a simple complex assignment.
redef class AContinueExpr

nitc :: scope $ AContinueExpr

A continue statement
redef class ADoExpr

nitc :: scope $ ADoExpr

A do statement
redef abstract class AEscapeExpr

nitc :: scope $ AEscapeExpr

A break or a continue
redef class AForExpr

nitc :: scope $ AForExpr

A for statement
redef class AForGroup

nitc :: scope $ AForGroup

A collection iterated by a for, its automatic variables and its implicit iterator.
redef class AIfExpr

nitc :: scope $ AIfExpr

A if statement
redef class ALambdaExpr

nitc :: scope $ ALambdaExpr

redef class ALoopExpr

nitc :: scope $ ALoopExpr

A loop statement
redef abstract class ANode

nitc :: scope $ ANode

Root of the AST class-hierarchy
redef class AParam

nitc :: scope $ AParam

A parameter definition in a signature. eg x:X
redef abstract class APropdef

nitc :: scope $ APropdef

The definition of a property
redef class AReturnExpr

nitc :: scope $ AReturnExpr

A return statement. eg return x
redef class ASelfExpr

nitc :: scope $ ASelfExpr

A read of self
redef abstract class AVarFormExpr

nitc :: scope $ AVarFormExpr

Whatever is an access to a local variable
redef class AVardeclExpr

nitc :: scope $ AVardeclExpr

A declaration of a local variable. eg var x: X = y
redef class AWhileExpr

nitc :: scope $ AWhileExpr

A while statement
redef class AWithExpr

nitc :: scope $ AWithExpr

A with statement
class EscapeMark

nitc $ EscapeMark

Mark where break and continue will branch.
private class Scope

nitc $ Scope

private class ScopePhase

nitc $ ScopePhase

private class ScopeVisitor

nitc $ ScopeVisitor

Visit a npropdef and:
redef class ToolContext

nitc :: scope $ ToolContext

Global context for tools
class Variable

nitc $ Variable

A local variable (including parameters, automatic variables and self)
package_diagram nitc::scope scope nitc::modelbuilder modelbuilder nitc::scope->nitc::modelbuilder nitc::loader loader nitc::modelbuilder->nitc::loader nitc::phase phase nitc::modelbuilder->nitc::phase ...nitc::loader ... ...nitc::loader->nitc::loader ...nitc::phase ... ...nitc::phase->nitc::phase nitc::flow flow nitc::flow->nitc::scope nitc::reaching_defs reaching_defs nitc::reaching_defs->nitc::scope nitc::local_var_init local_var_init nitc::local_var_init->nitc::flow nitc::local_var_init... ... nitc::local_var_init...->nitc::local_var_init nitc::saf saf nitc::saf->nitc::reaching_defs nitc::saf... ... nitc::saf...->nitc::saf

Ancestors

module abstract_collection

core :: abstract_collection

Abstract collection classes and services.
module abstract_text

core :: abstract_text

Abstract class for manipulation of sequences of characters
module array

core :: array

This module introduces the standard array structure.
module bitset

core :: bitset

Services to handle BitSet
module bytes

core :: bytes

Services for byte streams and arrays
module caching

serialization :: caching

Services for caching serialization engines
module circular_array

core :: circular_array

Efficient data structure to access both end of the sequence.
module codec_base

core :: codec_base

Base for codecs to use with streams
module codecs

core :: codecs

Group module for all codec-related manipulations
module collection

core :: collection

This module define several collection classes.
module console

console :: console

Defines some ANSI Terminal Control Escape Sequences.
module core

core :: core

Standard classes and methods used by default by Nit programs and libraries.
module digraph

graph :: digraph

Implementation of directed graphs, also called digraphs.
module engine_tools

serialization :: engine_tools

Advanced services for serialization engines
module environ

core :: environ

Access to the environment variables of the process
module error

core :: error

Standard error-management infrastructure.
module exec

core :: exec

Invocation and management of operating system sub-processes.
module file

core :: file

File manipulations (create, read, write, etc.)
module fixed_ints

core :: fixed_ints

Basic integers of fixed-precision
module fixed_ints_text

core :: fixed_ints_text

Text services to complement fixed_ints
module flat

core :: flat

All the array-based text representations
module gc

core :: gc

Access to the Nit internal garbage collection mechanism
module hash_collection

core :: hash_collection

Introduce HashMap and HashSet.
module ini

ini :: ini

Read and write INI configuration files
module inspect

serialization :: inspect

Refine Serializable::inspect to show more useful information
module iso8859_1

core :: iso8859_1

Codec for ISO8859-1 I/O
module kernel

core :: kernel

Most basic classes and methods.
module lexer

nitc :: lexer

Lexer and its tokens.
module lexer_work

nitc :: lexer_work

Internal algorithm and data structures for the Nit lexer
module list

core :: list

This module handle double linked lists
module loader

nitc :: loader

Loading of Nit source files
module location

nitc :: location

Nit source-file and locations in source-file
module math

core :: math

Mathematical operations
module mdoc

nitc :: mdoc

Documentation of model entities
module meta

meta :: meta

Simple user-defined meta-level to manipulate types of instances as object.
module mmodule

nitc :: mmodule

modules and module hierarchies in the metamodel
module model

nitc :: model

Classes, types and properties
module model_base

nitc :: model_base

The abstract concept of model and related common things
module modelbuilder_base

nitc :: modelbuilder_base

Load nit source files and build the associated model
module more_collections

more_collections :: more_collections

Highly specific, but useful, collections-related classes.
module mpackage

nitc :: mpackage

Modelisation of a Nit package
module native

core :: native

Native structures for text and bytes
module nitpm_shared

nitc :: nitpm_shared

Services related to the Nit package manager
module numeric

core :: numeric

Advanced services for Numeric types
module opts

opts :: opts

Management of options on the command line
module ordered_tree

ordered_tree :: ordered_tree

Manipulation and presentation of ordered trees.
module parser

nitc :: parser

Parser.
module parser_nodes

nitc :: parser_nodes

AST nodes of the Nit language
module parser_prod

nitc :: parser_prod

Production AST nodes full definition.
module parser_work

nitc :: parser_work

Internal algorithm and data structures for the Nit parser
module phase

nitc :: phase

Phases of the processing of nit programs
module poset

poset :: poset

Pre order sets and partial order set (ie hierarchies)
module protocol

core :: protocol

module queue

core :: queue

Queuing data structures and wrappers
module range

core :: range

Module for range of discrete objects.
module re

core :: re

Regular expression support for all services based on Pattern
module ropes

core :: ropes

Tree-based representation of a String.
module serialization

serialization :: serialization

General serialization services
module serialization_core

serialization :: serialization_core

Abstract services to serialize Nit objects to different formats
module sorter

core :: sorter

This module contains classes used to compare things and sorts arrays.
module stream

core :: stream

Input and output streams of characters
module tables

nitc :: tables

Module that interfaces the parsing tables.
module template

template :: template

Basic template system
module text

core :: text

All the classes and methods related to the manipulation of text entities
module time

core :: time

Management of time and dates
module toolcontext

nitc :: toolcontext

Common command-line tool infrastructure than handle options and error messages
module union_find

core :: union_find

union–find algorithm using an efficient disjoint-set data structure
module utf8

core :: utf8

Codec for UTF-8 I/O
module version

nitc :: version

This file was generated by git-gen-version.sh

Parents

Children

module flow

nitc :: flow

Intraprocedural static flow.

Descendants

module a_star-m

a_star-m

module abstract_compiler

nitc :: abstract_compiler

Abstract compiler
module android

nitc :: android

Compile program for the Android platform
module android_annotations

nitc :: android_annotations

Additionnal annotations to gather metadata on Android projects
module api

nitc :: api

Components required to build a web server about the nit model.
module api_auth

nitc :: api_auth

module api_base

nitc :: api_base

Base classes used by nitweb.
module api_docdown

nitc :: api_docdown

Nitdoc specific Markdown format handling for Nitweb
module api_feedback

nitc :: api_feedback

Feedback related features
module api_light

nitc :: api_light

Highlight and collect messages from a piece of code
module api_model

nitc :: api_model

module app_annotations

nitc :: app_annotations

Annotations to gather metadata on app.nit projects
module astbuilder

nitc :: astbuilder

Instantiation and transformation of semantic nodes in the AST of expressions and statements
module auto_super_init

nitc :: auto_super_init

Computing of super-constructors that must be implicitly called at the begin of constructors.
module c

nitc :: c

Support for nesting C code within a Nit program using its FFI
module c_compiler_options

nitc :: c_compiler_options

Offers the annotations cflags and ldflags to specify
module code_gen

nitc :: code_gen

Main frontend phases plus code generation phases
module commands_docdown

nitc :: commands_docdown

Doc down related queries
module commands_http

nitc :: commands_http

Initialize commands from HTTP requests
module commands_parser

nitc :: commands_parser

A parser that create DocCommand from a string
module commands_usage

nitc :: commands_usage

Commands about how mentities are used
module compilation

nitc :: compilation

The compilation module of the VirtualMachine
module compiler

nitc :: compiler

Compilation to C
module compiler_ffi

nitc :: compiler_ffi

Full FFI support for the compiler
module compiler_serialization

nitc :: compiler_serialization

Serialization support for the compiler
module contracts

nitc :: contracts

Module to build contract
module cpp

nitc :: cpp

Supports the use of the C++ language through the FFI
module detect_covariance

nitc :: detect_covariance

Detect the static usage of covariance in the code.
module div_by_zero

nitc :: div_by_zero

Detection of divisions by zero in obvious cases
module dynamic_loading_ffi

nitc :: dynamic_loading_ffi

Execute FFI code by creating and loading shared libraries
module emscripten

nitc :: emscripten

Compile to JavaScript using the Emscripten SDK
module explain_assert

nitc :: explain_assert

Explain failed assert to the console by modifying the AST.
module extra_java_files

nitc :: extra_java_files

Intro the annotation extra_java_files to compile extra java files
module ffi

nitc :: ffi

Full FFI support, independent of the compiler
module ffi_base

nitc :: ffi_base

Tools and utilities for implement FFI with different languages
module frontend

nitc :: frontend

Collect and orchestration of main frontend phases
module global_compiler

nitc :: global_compiler

Global compilation of a Nit program
module header_dependency

nitc :: header_dependency

Tracks which modules has public header code that must be imported
module highlight

nitc :: highlight

Highlighting of Nit AST
module html_commands

nitc :: html_commands

Render commands results as HTML
module html_model

nitc :: html_model

Translate mentities to html blocks.
module htmlight

nitc :: htmlight

Highlighting of Nit AST with HTML
module i18n_phase

nitc :: i18n_phase

Basic support of internationalization through the generation of id-to-string tables
module interpreter

nitc :: interpreter

Interpretation of Nit programs
module ios

nitc :: ios

Compile programs for the iOS platform
module java

nitc :: java

FFI support for the Java language
module java_compiler

nitc :: java_compiler

Compile Nit code to Java code
module json_commands

nitc :: json_commands

Translate command results to json
module json_model

nitc :: json_model

Make model entities Serializable.
module light

nitc :: light

Light FFI support for the compiler
module light_only

nitc :: light_only

Compiler support for the light FFI only, detects unsupported usage of callbacks
module local_var_init

nitc :: local_var_init

Verify that local variables are initialized before their usage
module md_commands

nitc :: md_commands

Render commands results as Markdown
module memory_logger

nitc :: memory_logger

Extension to inject memory-tracing instrumentation in code generated by nitc.
module metrics

nitc :: metrics

Various statistics about Nit models and programs
module naive_interpreter

nitc :: naive_interpreter

Interpretation of a Nit program directly on the AST
module nit

nitc :: nit

A naive Nit interpreter
module nitc

nitc :: nitc

A Nit compiler
module nitcatalog

nitc :: nitcatalog

Basic catalog generator for Nit packages
module nitdoc

nitc :: nitdoc

Generator of static API documentation for the Nit language
module nith

nitc :: nith

A ligHt Nit compiler
module nitj

nitc :: nitj

Compile Nit into Java code runnable on the Java Virtual Machine.
module nitlight

nitc :: nitlight

Tool that produces highlighting for Nit programs
module nitmetrics

nitc :: nitmetrics

A program that collects various metrics on nit programs and libraries
module nitni

nitc :: nitni

Native interface related services (used underneath the FFI)
module nitni_callbacks

nitc :: nitni_callbacks

nitni services related to callbacks (used underneath the FFI)
module nitpackage

nitc :: nitpackage

Helpful features about packages
module nitpick

nitc :: nitpick

A program that collect potential style and code issues
module nitrestful

nitc :: nitrestful

Tool generating boilerplate code linking RESTful actions to Nit methods
module nitsaf

nitc :: nitsaf

Nit Static Analysis Framework client example.
module nitserial

nitc :: nitserial

Serialization support compiler, a tool to support deserialization of live generic types
module nitsmells

nitc :: nitsmells

module nituml

nitc :: nituml

UML generator in dot format.
module nitunit

nitc :: nitunit

Testing tool.
module nitvm

nitc :: nitvm

The Nit virtual machine launcher
module nitweb

nitc :: nitweb

Runs a webserver based on nitcorn that render things from model.
module nitx

nitc :: nitx

nitx, a command tool that displays useful data about Nit code
module nullables_metrics

nitc :: nullables_metrics

Statistics about the usage of nullables
module objc

nitc :: objc

FFI support for Objective-C
module on_demand_compiler

nitc :: on_demand_compiler

Compiles extern code within a module to a static library, as needed
module parallelization_phase

nitc :: parallelization_phase

Phase generating threads for functions annotated with threaded annotation
module pkgconfig

nitc :: pkgconfig

Offers the PkgconfigPhase to use the external program "pkg-config" in order
module rapid_type_analysis

nitc :: rapid_type_analysis

Rapid type analysis on the AST
module rta_metrics

nitc :: rta_metrics

Metrics from RTA
module saf

nitc :: saf

Nit Static Analysis Framework.
module semantize

nitc :: semantize

Process bodies of methods in regard with the model.
module separate_compiler

nitc :: separate_compiler

Separate compilation of a Nit program
module separate_erasure_compiler

nitc :: separate_erasure_compiler

Separate compilation of a Nit program with generic type erasure
module ssa

nitc :: ssa

Single-Static Assignment algorithm from an AST
module static

nitc :: static

Nitdoc generation framework
module static_base

nitc :: static_base

Base entities shared by all the nitdoc code
module static_cards

nitc :: static_cards

Cards templates for the static documentation
module static_html

nitc :: static_html

Render documentation pages as HTML
module static_index

nitc :: static_index

Manage indexing of Nit model for Nitdoc QuickSearch.
module static_structure

nitc :: static_structure

Composes the pages of the static documentation
module term

nitc :: term

module test_astbuilder

nitc :: test_astbuilder

Program used to test the clone method of the astbuilder tool
module test_highlight

nitc :: test_highlight

Program used to test the Nit highlighter
module test_model_visitor

nitc :: test_model_visitor

Example of model_visitor
module test_neo

nitc :: test_neo

Test for neo model saving and loading.
module test_test_phase

nitc :: test_test_phase

Example of simple module that aims to do some specific work on nit programs.
module transform

nitc :: transform

Thansformations that simplify the AST of expressions
module typing

nitc :: typing

Intraprocedural resolution of static types and OO-services
module variables_numbering

nitc :: variables_numbering

Handle all numbering operations related to local variables in the Nit virtual machine
module virtual_machine

nitc :: virtual_machine

Implementation of the Nit virtual machine
module vm

nitc :: vm

Entry point of all vm components
module vm_optimizations

nitc :: vm_optimizations

Optimization of the nitvm
module xcode_templates

nitc :: xcode_templates

Templates and other services to create XCode projects
# Identification and scoping of local variables and labels.
module scope

import phase
import modelbuilder

redef class ToolContext
	# Run `APropdef::do_scope` on each propdef.
	var scope_phase: Phase = new ScopePhase(self, null)
end

private class ScopePhase
	super Phase
	redef fun process_npropdef(npropdef) do npropdef.do_scope(toolcontext)
end


# A local variable (including parameters, automatic variables and self)
class Variable
	# The name of the variable (as used in the program)
	var name: String is writable

	# Alias of `name`
	redef fun to_s do return self.name

	# The declaration of the variable, if any
	var location: nullable Location = null is writable

	# Is the local variable not read and need a warning?
	var warn_unread = false is writable
end

# Mark where break and continue will branch.
# Marks are either associated with a label of with a for_loop structure
class EscapeMark
	# The name of the label (unless the mark is an anonymous loop mark)
	var name: nullable String

	# The associated `continue` mark, if any.
	# If the mark attached to a loop (loop, while, for), a distinct mark is used.
	private var continue_mark: nullable EscapeMark = null

	# Each break/continue attached to the mark
	var escapes = new Array[AEscapeExpr]
end

# Visit a npropdef and:
#  * Identify variables and labels
#  * Associate each break and continue to its escapemark
#  * Transform `ACallFormExpr` that access a variable into `AVarFormExpr`
# FIXME: Should the class be private?
private class ScopeVisitor
	super Visitor

	# The tool context used to display errors
	var toolcontext: ToolContext

	# The analysed property
	var propdef: APropdef

	var selfvariable = new Variable("self")

	init
	do
		scopes.add(new Scope)
	end

	# All stacked scope. `scopes.first` is the current scope
	var scopes = new List[Scope]

	# Shift and check the last scope
	fun shift_scope
	do
		assert not scopes.is_empty
		var scope = scopes.shift
		for v in scope.variables.values do
			if v.warn_unread then
				toolcontext.advice(v.location, "unread-variable", "Warning: local variable {v.name} is never read.")
			end
		end
	end

	# Register a local variable.
	# Display an error on toolcontext if a variable with the same name is masked.
	fun register_variable(node: ANode, variable: Variable): Bool
	do
		var name = variable.name
		var found = search_variable(name)
		if found != null then
			self.error(node, "Error: a variable named `{name}` already exists.")
			return false
		end
		scopes.first.variables[name] = variable
		variable.location = node.location
		return true
	end

	# Look for a variable named `name`.
	# Return null if no such a variable is found.
	fun search_variable(name: String): nullable Variable
	do
		for scope in scopes do
			var res = scope.get_variable(name)
			if res != null then
				return res
			end
		end
		return null
	end

	redef fun visit(n)
	do
		n.accept_scope_visitor(self)
	end

	# Enter in a statement block `node` as inside a new scope.
	# The block can be optionally attached to an `escapemark`.
	fun enter_visit_block(node: nullable AExpr, escapemark: nullable EscapeMark)
	do
		if node == null then return
		var scope = new Scope
		scope.escapemark = escapemark
		scopes.unshift(scope)
		enter_visit(node)
		shift_scope
	end

	# Look for a label `name`.
	# Return null if no such a label is found.
	fun search_label(name: String): nullable EscapeMark
	do
		for scope in scopes do
			var res = scope.escapemark
			if res != null and res.name == name then
				return res
			end
		end
		return null
	end

	# Create a new escape mark (possibly with a label)
	# Display an error on toolcontext if a label with the same name is masked.
	fun make_escape_mark(nlabel: nullable ALabel, for_loop: Bool): EscapeMark
	do
		var name: nullable String
		if nlabel != null then
			var nid = nlabel.n_id
			if nid == null then
				var res = search_label("")
				if res != null then
					self.error(nlabel, "Syntax Error: anonymous label already defined.")
				end
				name = ""
			else
				name = nid.text
				var found = self.search_label(name)
				if found != null then
					self.error(nlabel, "Syntax Error: label `{name}` already defined.")
				end
			end
		else
			name = null
		end
		var res = new EscapeMark(name)
		if for_loop then res.continue_mark = new EscapeMark(name)
		return res
	end

	# Look for an escape mark optionally associated with a label.
	# If a label is given, the escapemark of this label is returned.
	# If there is no label, the nearest escapemark that is `for loop` is returned.
	# If there is no valid escapemark, then an error is displayed ans null is returned.
	# Return null if no such a label is found.
	fun get_escapemark(node: ANode, nlabel: nullable ALabel): nullable EscapeMark
	do
		if nlabel != null then
			var nid = nlabel.n_id
			if nid == null then
				var res = search_label("")
				if res == null then
					self.error(nlabel, "Syntax Error: invalid anonymous label.")
					node.is_broken = true
					return null
				end
				return res
			end
			var name = nid.text
			var res = search_label(name)
			if res == null then
				self.error(nlabel, "Syntax Error: invalid label `{name}`.")
				node.is_broken = true
				return null
			end
			return res
		else
			for scope in scopes do
				var res = scope.escapemark
				if res != null then
					return res
				end
			end
			self.error(node, "Syntax Error: `break` statement outside block.")
			return null
		end
	end

	# Display an error
	fun error(node: ANode, message: String)
	do
		self.toolcontext.error(node.hot_location, message)
		node.is_broken = true
	end
end

private class Scope
	var variables = new HashMap[String, Variable]

	var escapemark: nullable EscapeMark = null

	fun get_variable(name: String): nullable Variable
	do
		if self.variables.has_key(name) then
			return self.variables[name]
		else
			return null
		end
	end
end

redef class ANode
	private fun accept_scope_visitor(v: ScopeVisitor)
	do
		visit_all(v)
	end
end

redef class APropdef
	# The break escape mark associated with the return
	var return_mark: nullable EscapeMark

	# Entry point of the scope analysis
	fun do_scope(toolcontext: ToolContext)
	do
		var v = new ScopeVisitor(toolcontext, self)
		v.enter_visit(self)
		v.shift_scope
	end
end

redef class AParam
	# The variable associated with the parameter
	var variable: nullable Variable
	redef fun accept_scope_visitor(v)
	do
		if variable != null then
			v.register_variable(self.n_id, variable.as(not null))
			return
		end

		super
		var nid = self.n_id
		var variable = new Variable(nid.text)
		v.register_variable(nid, variable)
		self.variable = variable
	end
end

redef class AVardeclExpr
	# The variable associated with the variable declaration
	var variable: nullable Variable
	redef fun accept_scope_visitor(v)
	do
		super
		var nid = self.n_id
		var variable = new Variable(nid.text)
		v.register_variable(nid, variable)
		variable.warn_unread = true # wait for some read mark.
		self.variable = variable
	end
end

redef class ASelfExpr
	# The variable associated with the self receiver
	var variable: nullable Variable
	redef fun accept_scope_visitor(v)
	do
		super
		self.variable = v.selfvariable
	end
end

redef class AEscapeExpr
	# The escape mark associated with the break/continue
	var escapemark: nullable EscapeMark
end

redef class AContinueExpr
	redef fun accept_scope_visitor(v)
	do
		super
		var escapemark = v.get_escapemark(self, self.n_label)
		if escapemark == null then return # Skip error
		escapemark = escapemark.continue_mark
		if escapemark == null then
			v.error(self, "Error: cannot 'continue', only 'break'.")
			return
		end
		escapemark.escapes.add(self)
		self.escapemark = escapemark
	end
end

redef class ABreakExpr
	redef fun accept_scope_visitor(v)
	do
		super
		var escapemark = v.get_escapemark(self, self.n_label)
		if escapemark == null then return # Skip error
		escapemark.escapes.add(self)
		self.escapemark = escapemark
	end
end

redef class AReturnExpr
	redef fun accept_scope_visitor(v)
	do
		super

		var escapemark = v.propdef.return_mark
		if escapemark == null then
			escapemark = new EscapeMark
			v.propdef.return_mark = escapemark
		end

		escapemark.escapes.add(self)
		self.escapemark = escapemark
	end
end

redef class ADoExpr
	# The break escape mark associated with the 'do' block
	var break_mark: nullable EscapeMark

	redef fun accept_scope_visitor(v)
	do
		self.break_mark = v.make_escape_mark(n_label, false)
		v.enter_visit_block(n_block, self.break_mark)
		v.enter_visit_block(n_catch)
	end
end

redef class AIfExpr
	redef fun accept_scope_visitor(v)
	do
		v.enter_visit(n_expr)
		v.enter_visit_block(n_then, null)
		v.enter_visit_block(n_else, null)
	end
end

redef class AWhileExpr
	# The break escape mark associated with the 'while'
	var break_mark: nullable EscapeMark

	# The continue escape mark associated with the 'while'
	var continue_mark: nullable EscapeMark

	redef fun accept_scope_visitor(v)
	do
		var escapemark = v.make_escape_mark(n_label, true)
		self.break_mark = escapemark
		self.continue_mark = escapemark.continue_mark
		v.enter_visit(n_expr)
		v.enter_visit_block(n_block, escapemark)
	end
end

redef class ALoopExpr
	# The break escape mark associated with the 'loop'
	var break_mark: nullable EscapeMark

	# The continue escape mark associated with the 'loop'
	var continue_mark: nullable EscapeMark

	redef fun accept_scope_visitor(v)
	do
		var escapemark = v.make_escape_mark(n_label, true)
		self.break_mark = escapemark
		self.continue_mark = escapemark.continue_mark
		v.enter_visit_block(n_block, escapemark)
	end
end

redef class AForExpr
	# The break escape mark associated with the 'for'
	var break_mark: nullable EscapeMark

	# The continue escape mark associated with the 'for'
	var continue_mark: nullable EscapeMark

	redef fun accept_scope_visitor(v)
	do
		for g in n_groups do
			v.enter_visit(g.n_expr)
		end

		# Protect automatic variables
		v.scopes.unshift(new Scope)

		for g in n_groups do
			# Create the automatic variables
			var variables = new Array[Variable]
			g.variables = variables
			for nid in g.n_ids do
				var va = new Variable(nid.text)
				v.register_variable(nid, va)
				variables.add(va)
			end
		end

		var escapemark = v.make_escape_mark(n_label, true)
		self.break_mark = escapemark
		self.continue_mark = escapemark.continue_mark
		v.enter_visit_block(n_block, escapemark)

		v.shift_scope
	end
end

redef class AForGroup
	# The automatic variables in order
	var variables: nullable Array[Variable]
end

redef class AWithExpr
	# The break escape mark associated with the 'with'
	var break_mark: nullable EscapeMark

	redef fun accept_scope_visitor(v)
	do
		v.scopes.unshift(new Scope)

		var escapemark = v.make_escape_mark(n_label, true)
		self.break_mark = escapemark

		v.enter_visit(n_expr)
		v.enter_visit_block(n_block, escapemark)

		v.shift_scope
	end
end

redef class AAssertExpr
	redef fun accept_scope_visitor(v)
	do
		v.enter_visit(n_expr)
		v.enter_visit_block(n_else, null)
	end
end

redef class AVarFormExpr
	# The associated variable
	var variable: nullable Variable is writable
end

redef class ACallFormExpr
	redef fun accept_scope_visitor(v)
	do
		if n_expr isa AImplicitSelfExpr then
			var name = n_qid.n_id.text
			var variable = v.search_variable(name)
			if variable != null then
				var n: AExpr
				if not n_args.n_exprs.is_empty or n_args isa AParExprs or self isa ACallrefExpr then
					v.error(self, "Error: `{name}` is a variable, not a method.")
					return
				end
				n = variable_create(variable)
				n.variable = variable
				replace_with(n)
				n.accept_scope_visitor(v)
				return
			end
		end

		super
	end

	# Create a variable access corresponding to the call form
	private fun variable_create(variable: Variable): AVarFormExpr is abstract
end

redef class ACallExpr
	redef fun variable_create(variable)
	do
		variable.warn_unread = false
		return new AVarExpr.init_avarexpr(n_qid.n_id)
	end
end

redef class ACallAssignExpr
	redef fun variable_create(variable)
	do
		return new AVarAssignExpr.init_avarassignexpr(n_qid.n_id, n_assign, n_value)
	end
end

redef class ACallReassignExpr
	redef fun variable_create(variable)
	do
		variable.warn_unread = false
		return new AVarReassignExpr.init_avarreassignexpr(n_qid.n_id, n_assign_op, n_value)
	end
end

redef class ALambdaExpr
	redef fun accept_scope_visitor(v)
	do
		# TODO
		return
	end
end
src/semantize/scope.nit:17,1--538,3