Last active
July 25, 2016 02:43
-
-
Save Sija/62a90dcaabb7f9cbaa804493fb15631e to your computer and use it in GitHub Desktop.
Detailed assert macro for Crystal by @BlaXpirit — http://blaxpirit.com/blog/17/detailed-assert-macro-for-crystal.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AssertionError < Exception | |
end | |
# If `cond` is `false`, raise `exc`. | |
# If `exc` is not provided, `AssertionError` will be raised instead with information about the faulty expression. | |
# If the expression is a comparison, the result of each side of the comparison will also be shown. | |
macro assert(cond, exc = nil) | |
unless {{ cond }} | |
{% if exc %} | |
raise {{ exc }} | |
{% else %} | |
{% if cond.is_a? Call && %w(== != < > <= >=).any? {|s| s == cond.name.stringify} %} | |
{% a = cond.receiver; b = cond.args[0] %} | |
%error = "#{{{ a.stringify }}} => #{{{ a }}} {{ cond.name }} #{{{ b }}} <= #{{{ b.stringify }}}" | |
{% else %} | |
%error = {{ cond.stringify }} | |
{% end %} | |
raise AssertionError.new(%error) | |
{% end %} | |
end | |
end | |
# Assert only in debug mode | |
macro debug_assert(cond, exc = nil) | |
ifdef !release | |
assert({{ cond }}, {{ exc }}) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment