2021-01-09 07:12:28 +00:00
|
|
|
require "./label"
|
|
|
|
|
|
|
|
module Spectator
|
|
|
|
# Represents an expression from a test.
|
|
|
|
# This is typically captured by an `expect` macro.
|
|
|
|
# It consists of a label and the value of the expression.
|
|
|
|
# The label should be a string recognizable by the user,
|
|
|
|
# or nil if one isn't available.
|
2021-01-16 05:32:02 +00:00
|
|
|
#
|
2021-01-09 07:12:28 +00:00
|
|
|
# This base class is provided so that all generic sub-classes can be stored as this one type.
|
2021-11-28 22:45:17 +00:00
|
|
|
# The value of the expression can be retrieved by down-casting to the expected type with `#cast`.
|
2021-01-16 05:32:02 +00:00
|
|
|
#
|
|
|
|
# NOTE: This is intentionally a class and not a struct.
|
|
|
|
# If it were a struct, changes made to the value held by an instance may not be kept when passing it around.
|
|
|
|
# See commit ca564619ad2ae45f832a058d514298c868fdf699.
|
2021-01-09 07:12:28 +00:00
|
|
|
abstract class AbstractExpression
|
|
|
|
# User recognizable string for the expression.
|
|
|
|
# This can be something like a variable name or a snippet of Crystal code.
|
|
|
|
getter label : Label
|
|
|
|
|
|
|
|
# Creates the expression.
|
2021-01-16 05:32:02 +00:00
|
|
|
# The *label* is usually the Crystal code evaluating to the `#raw_value`.
|
2021-01-09 07:12:28 +00:00
|
|
|
# It can be nil if it isn't available.
|
|
|
|
def initialize(@label : Label)
|
|
|
|
end
|
|
|
|
|
2021-01-16 05:32:02 +00:00
|
|
|
# Retrieves the evaluated value of the expression.
|
|
|
|
abstract def raw_value
|
2021-01-09 07:12:28 +00:00
|
|
|
|
2021-01-16 05:32:02 +00:00
|
|
|
# Attempts to cast `#raw_value` to the type *T* and return it.
|
2021-01-09 07:12:28 +00:00
|
|
|
def cast(type : T.class) : T forall T
|
2021-01-16 05:32:02 +00:00
|
|
|
raw_value.as(T)
|
2021-01-09 07:12:28 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# Produces a string representation of the expression.
|
|
|
|
# This consists of the label (if one is available) and the value.
|
2022-11-05 02:56:02 +00:00
|
|
|
def to_s(io : IO) : Nil
|
2021-01-09 07:12:28 +00:00
|
|
|
if (label = @label)
|
2021-05-30 20:21:42 +00:00
|
|
|
io << label << ": "
|
2021-01-09 07:12:28 +00:00
|
|
|
end
|
2021-01-16 05:32:02 +00:00
|
|
|
raw_value.to_s(io)
|
2021-01-09 07:12:28 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# Produces a detailed string representation of the expression.
|
|
|
|
# This consists of the label (if one is available) and the value.
|
2022-11-05 02:56:02 +00:00
|
|
|
def inspect(io : IO) : Nil
|
2021-01-09 07:12:28 +00:00
|
|
|
if (label = @label)
|
2021-05-30 20:21:42 +00:00
|
|
|
io << label << ": "
|
2021-01-09 07:12:28 +00:00
|
|
|
end
|
2021-01-16 05:32:02 +00:00
|
|
|
raw_value.inspect(io)
|
2021-01-09 07:12:28 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|