module Crystal::Macros
Overview
The Macros module is a fictitious module used to document macros and macro methods.
You can invoke a fixed subset of methods on AST nodes at compile-time. These methods
are documented on the classes in this module. Additionally, methods of the
Macros
module are top-level methods that you can invoke, like #puts
and #run
.
Defined in:
compiler/crystal/macros.crInstance Method Summary
-
#`(command) : MacroId
Executes a system command and returns the output as a
MacroId
. -
#debug(format = true) : Nop
Outputs the current macro's buffer to the standard output.
-
#env(name) : StringLiteral | NilLiteral
Gets the value of an environment variable at compile-time, or
nil
if it doesn't exist. -
#p(expression) : Nop
Same as
#puts
. -
#puts(expression) : Nop
Prints an AST node at compile-time.
-
#raise(message) : NoReturn
Gives a compile-time error with the given message.
-
#run(filename, *args) : MacroId
Compiles and execute a Crystal program and returns its output as a
MacroId
. -
#system(command) : MacroId
Executes a system command and returns the output as a
MacroId
.
Instance Method Detail
Executes a system command and returns the output as a MacroId
.
Gives a compile-time error if the command failed to execute.
Outputs the current macro's buffer to the standard output. Useful for debugging
a macro to see what's being generated. Use it like {{debug()}}
, the parenthesis
are mandatory.
By default, the output is tried to be formatted using Crystal's
formatter, but you can disable this by passing false
to this method.
Gets the value of an environment variable at compile-time, or nil
if it doesn't exist.
Prints an AST node at compile-time. Useful for debugging macros.
Compiles and execute a Crystal program and returns its output
as a MacroId
.
The file denote by filename must be a valid Crystal program.
This macro invocation passes args to the program as regular
program arguments. The program must output a valid Crystal expression.
This output is the result of this macro invocation, as a MacroId
.
The #run
macro is useful when the subset of available macro methods
are not enough for your purposes and you need something more powerful.
With #run
you can read files at compile time, connect to the internet
or to a database.
A simple example:
# fetch.cr
require "http/client"
puts HTTP::Client.get(ARGV[0]).body
# main.cr
macro invoke_fetch
{{ run("./fetch", "http://example.com").stringify }}
end
puts invoke_fetch
The above generates a program that will have the contents of http://example.com
.
A connection to http://example.com
is never made at runtime.
Executes a system command and returns the output as a MacroId
.
Gives a compile-time error if the command failed to execute.