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.cr

Instance Method Summary

Instance Method Detail

def `(command) : MacroId #

Executes a system command and returns the output as a MacroId. Gives a compile-time error if the command failed to execute.


[View source]
def debug : Nop #

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.


[View source]
def env(name) : StringLiteral | NilLiteral #

Gets the value of an environment variable at compile-time, or nil if it doesn't exist.


[View source]
def p(expression) : Nop #

Same as #puts.


[View source]
def puts(expression) : Nop #

Prints an AST node at compile-time. Useful for debugging macros.


[View source]
def raise(message) : NoReturn #

Gives a compile-time error with the given message.


[View source]
def run(filename, *args) : MacroId #

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.


[View source]
def system(command) : MacroId #

Executes a system command and returns the output as a MacroId. Gives a compile-time error if the command failed to execute.


[View source]