Explain failed assert to the console by modifying the AST.

This module implements the service AAssertExpr::explain_assert_str, which should be used by the engines.

Example assert:

var x = 0.0
var y = 1.0
assert x.is_approx(y, 0.5)

Produces the following output on failure:

Runtime assert: 0.0.is_approx(1.0, 0.5)

Introduced classes

private class ExplainAssertVisitor

nitc :: ExplainAssertVisitor

Visitor to find and explain asserts

Redefined classes

redef class AAssertExpr

nitc :: explain_assert $ AAssertExpr

An assert statement
redef abstract class ABinBoolExpr

nitc :: explain_assert $ ABinBoolExpr

Something that is binary boolean expression
redef abstract class ABinopExpr

nitc :: explain_assert $ ABinopExpr

A binary operation on a method
redef class ABraExpr

nitc :: explain_assert $ ABraExpr

A call of the brackets operator. eg x[y,z]
redef class ACallExpr

nitc :: explain_assert $ 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 AExpr

nitc :: explain_assert $ AExpr

Expression and statements
redef class AIsaExpr

nitc :: explain_assert $ AIsaExpr

A type-ckeck expression. eg x isa T
redef class ANotExpr

nitc :: explain_assert $ ANotExpr

A not expression
redef class ToolContext

nitc :: explain_assert $ ToolContext

Global context for tools

All class definitions

redef class AAssertExpr

nitc :: explain_assert $ AAssertExpr

An assert statement
redef abstract class ABinBoolExpr

nitc :: explain_assert $ ABinBoolExpr

Something that is binary boolean expression
redef abstract class ABinopExpr

nitc :: explain_assert $ ABinopExpr

A binary operation on a method
redef class ABraExpr

nitc :: explain_assert $ ABraExpr

A call of the brackets operator. eg x[y,z]
redef class ACallExpr

nitc :: explain_assert $ 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 AExpr

nitc :: explain_assert $ AExpr

Expression and statements
redef class AIsaExpr

nitc :: explain_assert $ AIsaExpr

A type-ckeck expression. eg x isa T
redef class ANotExpr

nitc :: explain_assert $ ANotExpr

A not expression
private class ExplainAssertVisitor

nitc $ ExplainAssertVisitor

Visitor to find and explain asserts
redef class ToolContext

nitc :: explain_assert $ ToolContext

Global context for tools
package_diagram nitc::explain_assert explain_assert nitc::astbuilder astbuilder nitc::explain_assert->nitc::astbuilder nitc::explain_assert_api explain_assert_api nitc::explain_assert->nitc::explain_assert_api nitc::typing typing nitc::astbuilder->nitc::typing nitc\>parser\> parser nitc::explain_assert_api->nitc\>parser\> ...nitc::typing ... ...nitc::typing->nitc::typing ...nitc\>parser\> ... ...nitc\>parser\>->nitc\>parser\> nitc::code_gen code_gen nitc::code_gen->nitc::explain_assert nitc::nit nit nitc::nit->nitc::code_gen nitc::nitc nitc nitc::nitc->nitc::code_gen nitc::nitmetrics nitmetrics nitc::nitmetrics->nitc::code_gen nitc::nitvm nitvm nitc::nitvm->nitc::code_gen nitc::nit... ... nitc::nit...->nitc::nit nitc::nitc... ... nitc::nitc...->nitc::nitc nitc::nitmetrics... ... nitc::nitmetrics...->nitc::nitmetrics nitc::nitvm... ... nitc::nitvm...->nitc::nitvm

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 annotation

nitc :: annotation

Management and utilities on annotations
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 flow

nitc :: flow

Intraprocedural static flow.
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 literal

nitc :: literal

Parsing of literal values in the abstract syntax tree.
module loader

nitc :: loader

Loading of Nit source files
module local_var_init

nitc :: local_var_init

Verify that local variables are initialized before their usage
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 mmodule_data

nitc :: mmodule_data

Define and retrieve data in modules
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 modelize

nitc :: modelize

Create a model from nit source files
module modelize_class

nitc :: modelize_class

Analysis and verification of class definitions to instantiate model element
module modelize_property

nitc :: modelize_property

Analysis and verification of property definitions to instantiate model element
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 scope

nitc :: scope

Identification and scoping of local variables and labels.
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 typing

nitc :: typing

Intraprocedural resolution of static types and OO-services
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

module astbuilder

nitc :: astbuilder

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

nitc :: explain_assert_api

Explain failed assert to the console (service declaration only)

Children

module code_gen

nitc :: code_gen

Main frontend phases plus code generation phases

Descendants

module a_star-m

a_star-m

module nit

nitc :: nit

A naive Nit interpreter
module nitc

nitc :: nitc

A Nit compiler
module nitmetrics

nitc :: nitmetrics

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

nitc :: nitvm

The Nit virtual machine launcher
module test_astbuilder

nitc :: test_astbuilder

Program used to test the clone method of the astbuilder tool
# Explain failed assert to the console by modifying the AST.
#
# This module implements the service `AAssertExpr::explain_assert_str`,
# which should be used by the engines.
#
# Example assert:
#
# ~~~nitish
# var x = 0.0
# var y = 1.0
# assert x.is_approx(y, 0.5)
# ~~~
#
# Produces the following output on failure:
#
# ~~~raw
# Runtime assert: 0.0.is_approx(1.0, 0.5)
# ~~~
module explain_assert

import astbuilder
intrude import literal # for value=
intrude import typing # for mtype=

import explain_assert_api

redef class ToolContext

	# Phase modifying the AST to explain assets when they fail
	var explain_assert_phase: Phase = new ExplainAssertPhase(self, [modelize_class_phase, typing_phase, literal_phase])
end

private class ExplainAssertPhase
	super Phase

	redef fun process_nmodule(nmodule)
	do
		var mmodule = nmodule.mmodule
		if mmodule == null then return

		# Skip if `mmodule` doesn't have access to `String`
		var string_class = toolcontext.modelbuilder.try_get_mclass_by_name(nmodule, mmodule, "String")
		if string_class == null then return

		# Launch a visitor on all elements of the AST
		var visitor = new ExplainAssertVisitor(toolcontext, mmodule, string_class.mclass_type)
		visitor.enter_visit nmodule
	end
end

# Visitor to find and explain asserts
private class ExplainAssertVisitor
	super Visitor

	# The toolcontext is our entry point to most services
	var toolcontext: ToolContext

	# The visited module
	var mmodule: MModule

	# Type of `String` (the generated code does not work without a `String`)
	var string_mtype: MType

	# Tool to modify the AST
	var builder = new ASTBuilder(mmodule) is lazy

	redef fun visit(node)
	do
		# Recursively visit all sub-nodes
		node.visit_all(self)

		# Only work on asserts
		if not node isa AAssertExpr then return
		var expr = node.n_expr

		# Skip assert on a single boolean var and asserts on false:
		# ~~~
		# assert false
		# # or
		# var x = false # Or any boolean expression
		# assert x
		# ~~~
		if expr isa AVarExpr or expr isa AFalseExpr then return

		# Build the superstring to explain the assert
		var explain_str = new ASuperstringExpr

		# Prepare attribute used by visited nodes
		self.assert_node = node
		self.explain_str = explain_str
		expr.accept_explain_assert self

		# Done! Store the superstring in the assert's node
		if explain_str.n_exprs.not_empty then
			node.explain_assert_str = explain_str
		end
	end

	# Visited assert node
	var assert_node: AAssertExpr is noinit

	# Superstring in construction to explain the `assert_node`
	var explain_str: ASuperstringExpr is noinit

	# Build an `AStringExpr` containing `value`
	#
	# Add it to `explain_str` if `auto_add == true`, the default.
	fun explain_string(value: String, auto_add: nullable Bool): AStringExpr
	do
		auto_add = auto_add or else true

		var tk = new TString
		tk.text = "\"{value}\""
		var op = new AStringExpr
		op.n_string = tk
		op.mtype = string_mtype
		op.value = value
		op.location = assert_node.location

		if auto_add then explain_str.n_exprs.add op
		return op
	end

	# Add the value of `v_expr` to `explain_str` and protect null values
	fun explain_expr(v_expr: AExpr)
	do
		var mtype = v_expr.mtype
		if mtype == null then
			explain_string "<unexpected error>"
			return
		end

		# Set the expression value aside
		var old_parent = v_expr.parent
		var expr = v_expr.make_var_read
		if old_parent != null then old_parent.validate

		# Protect nullable types
		if mtype isa MNullType then
			explain_string "null"
			return
		else if mtype isa MNullableType then
			var e = new AOrElseExpr
			e.n_expr = expr
			e.n_expr2 = explain_string("null", false)
			e.location = assert_node.location
			e.mtype = mmodule.object_type

			explain_str.n_exprs.add e
			return
		end

		explain_str.n_exprs.add expr
	end

	# Add all the arguments in `AExprs` to `explain_str`
	fun explain_args(n_args: AExprs)
	do
		var first = true
		for n_arg in n_args.to_a do
			if not first then
				explain_string ", "
			else first = false

			explain_expr n_arg
		end
	end
end

redef class AAssertExpr
	redef var explain_assert_str = null
end

redef class AExpr
	# Fill `v` to explain this node if the parent assert fails
	private fun accept_explain_assert(v: ExplainAssertVisitor)
	do if mtype != null then v.explain_expr self
end

redef class ABinopExpr
	redef fun accept_explain_assert(v)
	do
		if n_expr.mtype == null or n_expr2.mtype == null then return

		v.explain_expr n_expr
		v.explain_string " {n_op.text} "
		v.explain_expr n_expr2
	end
end

redef class ACallExpr
	redef fun accept_explain_assert(v)
	do
		if n_expr.mtype == null then return

		v.explain_expr n_expr
		v.explain_string ".{n_qid.n_id.text}"

		if n_args.to_a.not_empty then
			v.explain_string "("
			v.explain_args n_args
			v.explain_string ")"
		end
	end
end

redef class ABraExpr
	redef fun accept_explain_assert(v)
	do
		if n_expr.mtype == null then return

		v.explain_expr n_expr
		v.explain_string "["
		v.explain_args n_args
		v.explain_string "]"
	end
end

redef class AIsaExpr
	redef fun accept_explain_assert(v)
	do
		if n_expr.mtype == null then return

		v.explain_expr n_expr
		v.explain_string " {n_kwisa.text} "
		v.explain_string n_type.collect_text
	end
end

redef class ANotExpr
	redef fun accept_explain_assert(v)
	do
		v.explain_string "{n_kwnot.text} "
		n_expr.accept_explain_assert v
	end
end

redef class ABinBoolExpr
	# Don't explain the conditions using `and`, `or`, etc.
	redef fun accept_explain_assert(v) do end
end
src/frontend/explain_assert.nit:15,1--255,3