macroexpand

macroexpand(x)

Takes the expression x and returns an equivalent expression with all macros removed (expanded).

Examples

  1. Expand macros in an expression:

    julia> macroexpand(:(@time sum(rand(100))))
    quote
       local #stats#550 = Base.gc_num()
       local #elapsed#551 = Base.time_ns()
       local #val#552 = sum(rand(100))
       local #elapsed#553 = Base.time_ns() - #elapsed#551
       local #diff#554 = Base.gc_num() - #stats#550
       (Base.time_println)("#elapsed#553 seconds (",Base.time_format_elf(0.001 * #elapsed#553)," CPU)",(Base.gc_num)()," collections, ",(Base.gc_alloc_count)()," allocations, ",Base.gc_alloc_bytes()," bytes allocated")
       #val#552
    end

    The macroexpand function expands the macro @time and returns the equivalent expression with the macro removed.

  2. Expand nested macros:
    julia> macroexpand(:(@time begin
           @show 2 + 2
           @time 3 * 3
       end))
    quote
       local #stats#555 = Base.gc_num()
       local #elapsed#556 = Base.time_ns()
       begin
           local #val#557 = begin
                   local #stats#558 = Base.gc_num()
                   local #elapsed#559 = Base.time_ns()
                   begin
                       local #val#560 = 2 + 2
                       (Base.time_println)("2 + 2 = ",#val#560)
                       #val#560
                   end
               end
           local #elapsed#561 = Base.time_ns() - #elapsed#559
           local #diff#562 = Base.gc_num() - #stats#558
           (Base.time_println)("#elapsed#561 seconds (",Base.time_format_elf(0.001 * #elapsed#561)," CPU)",(Base.gc_num)()," collections, ",(Base.gc_alloc_count)()," allocations, ",Base.gc_alloc_bytes()," bytes allocated")
           #val#557
       end
    end

    This example demonstrates the expansion of nested macros using macroexpand.

Common mistake example:

julia> macroexpand(@unknown_macro)
ERROR: UndefVarError: @unknown_macro not defined

Here, the @unknown_macro is not a defined macro, resulting in an error. Ensure that the macro used with macroexpand is valid and defined in the Julia environment.

See Also

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: