Understanding the macro API
The examples in the previous section utilized various variables of different types within the macro context, such as the numbers we iterate over, the strings we use to create identifiers, and the Booleans we compare to conditionally generate code. It would be easy to assume that this maps directly to the standard Number
, String
, and Bool
types. However, that is not the case. As we mentioned in the Defining macros section of this chapter, macros operate on AST nodes and, as such, have their own set of types that are similar to their related normal Crystal types, but with a subset of the API. For example, the types we have worked with so far include NumberLiteral
, StringLiteral
, and BoolLiteral
.
All macro types live under the Crystal::Macros
namespace within the API documentation, which is located at https://crystal-lang.org/api/Crystal/Macros.html. The most common/useful types include the following:
Def
: Describes a method definitionTypeNode...