Code review for dump(expr) macro

Looking for a code review of this dump(expr) macro and its supporting code. Also, asking if these things were already in Crystal and I just missed them.

module TermColors
	Black   = "\e[30m"
	Red     = "\e[31m"
	Green   = "\e[32m"
	Yellow  = "\e[33m"
	Blue    = "\e[34m"
	Magenta = "\e[35m"
	Cyan    = "\e[36m"
	White   = "\e[37m"

	BrightBlack   = "\e[90m"
	BrightRed     = "\e[91m"
	BrightGreen   = "\e[92m"
	BrightYellow  = "\e[93m"
	BrightBlue    = "\e[94m"
	BrightMagenta = "\e[95m"
	BrightCyan    = "\e[96m"
	BrightWhite   = "\e[97m"

	Reset   = "\e[0m"
	Bold    = "\e[1m"
	Dim     = "\e[2m"
	Italic  = "\e[3m"
	Underline = "\e[4m"

	def self.colorize(color, string) : String
		STDOUT.tty? ? "#{color}#{string}#{Reset}" : string
	end
end


# Returns a simplified path for the given path by chopping off the leading "/foo/bar" part.
def simplify_path(path : String, chop_before : String = "/src/") : String
	if path.includes?(chop_before)
		return chop_before + path.split(chop_before).last
	end
	path
end


module DumpCounter

	@@next : UInt64 = 999_u64

	def self.next
		@@next += 1
	end

end


# Dumps the expression source code and value, and source location.
# Used for debugging. Temporarily added to the code, and removed when done.
# Usage: dump expr
# Example output: dump 1000:  self.coords = Coords(@x=1, @y=1);  /src/base/Grid.cr:23
macro dump(expr)
	{% begin %}
		%count = DumpCounter.next
		%file = simplify_path(__FILE__)
		%line = __LINE__
		%value = {{expr}}
		%inspect = if %value == nil
			"nil"
		elsif %value == Pointer(Void).null
			"null"
		else
			%value.inspect
		end
		%expr_color = TermColors::BrightCyan
		%value_color = TermColors::BrightMagenta
		%expr_str = TermColors.colorize(%expr_color, {{expr.stringify}})
		%value_str = TermColors.colorize(%value_color, %inspect)
		puts "dump #{%count}:  #{%expr_str} = #{%value_str};  #{%file}:#{%line}"
		%value
	{% end %}
end
1 Like

This code is very similar to the pp! macro, minus like the unique ID and source location. But for colors you could prob just leverage Colorize - Crystal 1.14.0. simplify_path could prob leverage Path - Crystal 1.14.0 with Dir - Crystal 1.14.0 as the base?

If pp! could report the line numbers, that might be helpful.
I never thought of the idea.