<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Metaprogramming — Julia Language 0.3.4 documentation</title> <link href='https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="../_static/julia.css" type="text/css" /> <link rel="stylesheet" href="../_static/julia.css" type="text/css" /> <link rel="top" title="Julia Language 0.3.4 documentation" href="../index.html"/> <link rel="next" title="Multi-dimensional Arrays" href="arrays.html"/> <link rel="prev" title="Modules" href="modules.html"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"></script> </head> <body class="wy-body-for-nav" role="document"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-nav-search"> <a href="http://julialang.org/"><img src="../_static/julia-logo.svg" class="logo"></a> <!-- <a href="../index.html" class="fa fa-home"> Julia Language</a> --> <div role="search"> <form id ="rtd-search-form" class="wy-form" action="../search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <ul class="current"> <li class="toctree-l1"><a class="reference internal" href="introduction.html">Introduction</a></li> <li class="toctree-l1"><a class="reference internal" href="getting-started.html">Getting Started</a><ul> <li class="toctree-l2"><a class="reference internal" href="getting-started.html#resources">Resources</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="variables.html">Variables</a><ul> <li class="toctree-l2"><a class="reference internal" href="variables.html#allowed-variable-names">Allowed Variable Names</a></li> <li class="toctree-l2"><a class="reference internal" href="variables.html#stylistic-conventions">Stylistic Conventions</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="integers-and-floating-point-numbers.html">Integers and Floating-Point Numbers</a><ul> <li class="toctree-l2"><a class="reference internal" href="integers-and-floating-point-numbers.html#integers">Integers</a></li> <li class="toctree-l2"><a class="reference internal" href="integers-and-floating-point-numbers.html#floating-point-numbers">Floating-Point Numbers</a></li> <li class="toctree-l2"><a class="reference internal" href="integers-and-floating-point-numbers.html#arbitrary-precision-arithmetic">Arbitrary Precision Arithmetic</a></li> <li class="toctree-l2"><a class="reference internal" href="integers-and-floating-point-numbers.html#numeric-literal-coefficients">Numeric Literal Coefficients</a></li> <li class="toctree-l2"><a class="reference internal" href="integers-and-floating-point-numbers.html#literal-zero-and-one">Literal zero and one</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="mathematical-operations.html">Mathematical Operations and Elementary Functions</a><ul> <li class="toctree-l2"><a class="reference internal" href="mathematical-operations.html#arithmetic-operators">Arithmetic Operators</a></li> <li class="toctree-l2"><a class="reference internal" href="mathematical-operations.html#bitwise-operators">Bitwise Operators</a></li> <li class="toctree-l2"><a class="reference internal" href="mathematical-operations.html#updating-operators">Updating operators</a></li> <li class="toctree-l2"><a class="reference internal" href="mathematical-operations.html#numeric-comparisons">Numeric Comparisons</a></li> <li class="toctree-l2"><a class="reference internal" href="mathematical-operations.html#elementary-functions">Elementary Functions</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="complex-and-rational-numbers.html">Complex and Rational Numbers</a><ul> <li class="toctree-l2"><a class="reference internal" href="complex-and-rational-numbers.html#complex-numbers">Complex Numbers</a></li> <li class="toctree-l2"><a class="reference internal" href="complex-and-rational-numbers.html#rational-numbers">Rational Numbers</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="strings.html">Strings</a><ul> <li class="toctree-l2"><a class="reference internal" href="strings.html#characters">Characters</a></li> <li class="toctree-l2"><a class="reference internal" href="strings.html#string-basics">String Basics</a></li> <li class="toctree-l2"><a class="reference internal" href="strings.html#unicode-and-utf-8">Unicode and UTF-8</a></li> <li class="toctree-l2"><a class="reference internal" href="strings.html#interpolation">Interpolation</a></li> <li class="toctree-l2"><a class="reference internal" href="strings.html#common-operations">Common Operations</a></li> <li class="toctree-l2"><a class="reference internal" href="strings.html#non-standard-string-literals">Non-Standard String Literals</a></li> <li class="toctree-l2"><a class="reference internal" href="strings.html#regular-expressions">Regular Expressions</a></li> <li class="toctree-l2"><a class="reference internal" href="strings.html#id3">Byte Array Literals</a></li> <li class="toctree-l2"><a class="reference internal" href="strings.html#version-number-literals">Version Number Literals</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="functions.html">Functions</a><ul> <li class="toctree-l2"><a class="reference internal" href="functions.html#argument-passing-behavior">Argument Passing Behavior</a></li> <li class="toctree-l2"><a class="reference internal" href="functions.html#the-return-keyword">The <tt class="docutils literal"><span class="pre">return</span></tt> Keyword</a></li> <li class="toctree-l2"><a class="reference internal" href="functions.html#id1">Operators Are Functions</a></li> <li class="toctree-l2"><a class="reference internal" href="functions.html#operators-with-special-names">Operators With Special Names</a></li> <li class="toctree-l2"><a class="reference internal" href="functions.html#anonymous-functions">Anonymous Functions</a></li> <li class="toctree-l2"><a class="reference internal" href="functions.html#multiple-return-values">Multiple Return Values</a></li> <li class="toctree-l2"><a class="reference internal" href="functions.html#varargs-functions">Varargs Functions</a></li> <li class="toctree-l2"><a class="reference internal" href="functions.html#optional-arguments">Optional Arguments</a></li> <li class="toctree-l2"><a class="reference internal" href="functions.html#keyword-arguments">Keyword Arguments</a></li> <li class="toctree-l2"><a class="reference internal" href="functions.html#evaluation-scope-of-default-values">Evaluation Scope of Default Values</a></li> <li class="toctree-l2"><a class="reference internal" href="functions.html#block-syntax-for-function-arguments">Block Syntax for Function Arguments</a></li> <li class="toctree-l2"><a class="reference internal" href="functions.html#further-reading">Further Reading</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="control-flow.html">Control Flow</a><ul> <li class="toctree-l2"><a class="reference internal" href="control-flow.html#compound-expressions">Compound Expressions</a></li> <li class="toctree-l2"><a class="reference internal" href="control-flow.html#conditional-evaluation">Conditional Evaluation</a></li> <li class="toctree-l2"><a class="reference internal" href="control-flow.html#short-circuit-evaluation">Short-Circuit Evaluation</a></li> <li class="toctree-l2"><a class="reference internal" href="control-flow.html#repeated-evaluation-loops">Repeated Evaluation: Loops</a></li> <li class="toctree-l2"><a class="reference internal" href="control-flow.html#exception-handling">Exception Handling</a></li> <li class="toctree-l2"><a class="reference internal" href="control-flow.html#tasks-aka-coroutines">Tasks (aka Coroutines)</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="variables-and-scoping.html">Scope of Variables</a><ul> <li class="toctree-l2"><a class="reference internal" href="variables-and-scoping.html#for-loops-and-comprehensions">For Loops and Comprehensions</a></li> <li class="toctree-l2"><a class="reference internal" href="variables-and-scoping.html#constants">Constants</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="types.html">Types</a><ul> <li class="toctree-l2"><a class="reference internal" href="types.html#type-declarations">Type Declarations</a></li> <li class="toctree-l2"><a class="reference internal" href="types.html#abstract-types">Abstract Types</a></li> <li class="toctree-l2"><a class="reference internal" href="types.html#bits-types">Bits Types</a></li> <li class="toctree-l2"><a class="reference internal" href="types.html#composite-types">Composite Types</a></li> <li class="toctree-l2"><a class="reference internal" href="types.html#immutable-composite-types">Immutable Composite Types</a></li> <li class="toctree-l2"><a class="reference internal" href="types.html#declared-types">Declared Types</a></li> <li class="toctree-l2"><a class="reference internal" href="types.html#tuple-types">Tuple Types</a></li> <li class="toctree-l2"><a class="reference internal" href="types.html#type-unions">Type Unions</a></li> <li class="toctree-l2"><a class="reference internal" href="types.html#man-parametric-types">Parametric Types</a></li> <li class="toctree-l2"><a class="reference internal" href="types.html#type-aliases">Type Aliases</a></li> <li class="toctree-l2"><a class="reference internal" href="types.html#operations-on-types">Operations on Types</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="methods.html">Methods</a><ul> <li class="toctree-l2"><a class="reference internal" href="methods.html#defining-methods">Defining Methods</a></li> <li class="toctree-l2"><a class="reference internal" href="methods.html#method-ambiguities">Method Ambiguities</a></li> <li class="toctree-l2"><a class="reference internal" href="methods.html#parametric-methods">Parametric Methods</a></li> <li class="toctree-l2"><a class="reference internal" href="methods.html#note-on-optional-and-keyword-arguments">Note on Optional and keyword Arguments</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="constructors.html">Constructors</a><ul> <li class="toctree-l2"><a class="reference internal" href="constructors.html#outer-constructor-methods">Outer Constructor Methods</a></li> <li class="toctree-l2"><a class="reference internal" href="constructors.html#inner-constructor-methods">Inner Constructor Methods</a></li> <li class="toctree-l2"><a class="reference internal" href="constructors.html#incomplete-initialization">Incomplete Initialization</a></li> <li class="toctree-l2"><a class="reference internal" href="constructors.html#parametric-constructors">Parametric Constructors</a></li> <li class="toctree-l2"><a class="reference internal" href="constructors.html#case-study-rational">Case Study: Rational</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="conversion-and-promotion.html">Conversion and Promotion</a><ul> <li class="toctree-l2"><a class="reference internal" href="conversion-and-promotion.html#conversion">Conversion</a></li> <li class="toctree-l2"><a class="reference internal" href="conversion-and-promotion.html#promotion">Promotion</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="modules.html">Modules</a><ul> <li class="toctree-l2"><a class="reference internal" href="modules.html#summary-of-module-usage">Summary of module usage</a></li> </ul> </li> <li class="toctree-l1 current"><a class="current reference internal" href="">Metaprogramming</a><ul> <li class="toctree-l2"><a class="reference internal" href="#expressions-and-eval">Expressions and Eval</a></li> <li class="toctree-l2"><a class="reference internal" href="#macros">Macros</a></li> <li class="toctree-l2"><a class="reference internal" href="#reflection">Reflection</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="arrays.html">Multi-dimensional Arrays</a><ul> <li class="toctree-l2"><a class="reference internal" href="arrays.html#arrays">Arrays</a></li> <li class="toctree-l2"><a class="reference internal" href="arrays.html#sparse-matrices">Sparse Matrices</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="linear-algebra.html">Linear algebra</a><ul> <li class="toctree-l2"><a class="reference internal" href="linear-algebra.html#matrix-factorizations">Matrix factorizations</a></li> <li class="toctree-l2"><a class="reference internal" href="linear-algebra.html#special-matrices">Special matrices</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="networking-and-streams.html">Networking and Streams</a><ul> <li class="toctree-l2"><a class="reference internal" href="networking-and-streams.html#basic-stream-i-o">Basic Stream I/O</a></li> <li class="toctree-l2"><a class="reference internal" href="networking-and-streams.html#text-i-o">Text I/O</a></li> <li class="toctree-l2"><a class="reference internal" href="networking-and-streams.html#working-with-files">Working with Files</a></li> <li class="toctree-l2"><a class="reference internal" href="networking-and-streams.html#a-simple-tcp-example">A simple TCP example</a></li> <li class="toctree-l2"><a class="reference internal" href="networking-and-streams.html#resolving-ip-addresses">Resolving IP Addresses</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="parallel-computing.html">Parallel Computing</a><ul> <li class="toctree-l2"><a class="reference internal" href="parallel-computing.html#data-movement">Data Movement</a></li> <li class="toctree-l2"><a class="reference internal" href="parallel-computing.html#parallel-map-and-loops">Parallel Map and Loops</a></li> <li class="toctree-l2"><a class="reference internal" href="parallel-computing.html#synchronization-with-remote-references">Synchronization With Remote References</a></li> <li class="toctree-l2"><a class="reference internal" href="parallel-computing.html#scheduling">Scheduling</a></li> <li class="toctree-l2"><a class="reference internal" href="parallel-computing.html#distributed-arrays">Distributed Arrays</a></li> <li class="toctree-l2"><a class="reference internal" href="parallel-computing.html#constructing-distributed-arrays">Constructing Distributed Arrays</a></li> <li class="toctree-l2"><a class="reference internal" href="parallel-computing.html#distributed-array-operations">Distributed Array Operations</a></li> <li class="toctree-l2"><a class="reference internal" href="parallel-computing.html#shared-arrays-experimental">Shared Arrays (Experimental)</a></li> <li class="toctree-l2"><a class="reference internal" href="parallel-computing.html#clustermanagers">ClusterManagers</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="running-external-programs.html">Running External Programs</a><ul> <li class="toctree-l2"><a class="reference internal" href="running-external-programs.html#interpolation">Interpolation</a></li> <li class="toctree-l2"><a class="reference internal" href="running-external-programs.html#quoting">Quoting</a></li> <li class="toctree-l2"><a class="reference internal" href="running-external-programs.html#pipelines">Pipelines</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="calling-c-and-fortran-code.html">Calling C and Fortran Code</a><ul> <li class="toctree-l2"><a class="reference internal" href="calling-c-and-fortran-code.html#mapping-c-types-to-julia">Mapping C Types to Julia</a></li> <li class="toctree-l2"><a class="reference internal" href="calling-c-and-fortran-code.html#accessing-data-through-a-pointer">Accessing Data through a Pointer</a></li> <li class="toctree-l2"><a class="reference internal" href="calling-c-and-fortran-code.html#passing-pointers-for-modifying-inputs">Passing Pointers for Modifying Inputs</a></li> <li class="toctree-l2"><a class="reference internal" href="calling-c-and-fortran-code.html#garbage-collection-safety">Garbage Collection Safety</a></li> <li class="toctree-l2"><a class="reference internal" href="calling-c-and-fortran-code.html#non-constant-function-specifications">Non-constant Function Specifications</a></li> <li class="toctree-l2"><a class="reference internal" href="calling-c-and-fortran-code.html#indirect-calls">Indirect Calls</a></li> <li class="toctree-l2"><a class="reference internal" href="calling-c-and-fortran-code.html#calling-convention">Calling Convention</a></li> <li class="toctree-l2"><a class="reference internal" href="calling-c-and-fortran-code.html#accessing-global-variables">Accessing Global Variables</a></li> <li class="toctree-l2"><a class="reference internal" href="calling-c-and-fortran-code.html#passing-julia-callback-functions-to-c">Passing Julia Callback Functions to C</a></li> <li class="toctree-l2"><a class="reference internal" href="calling-c-and-fortran-code.html#c">C++</a></li> <li class="toctree-l2"><a class="reference internal" href="calling-c-and-fortran-code.html#handling-platform-variations">Handling Platform Variations</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="interacting-with-julia.html">Interacting With Julia</a><ul> <li class="toctree-l2"><a class="reference internal" href="interacting-with-julia.html#the-different-prompt-modes">The different prompt modes</a></li> <li class="toctree-l2"><a class="reference internal" href="interacting-with-julia.html#key-bindings">Key bindings</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="embedding.html">Embedding Julia</a><ul> <li class="toctree-l2"><a class="reference internal" href="embedding.html#high-level-embedding">High-Level Embedding</a></li> <li class="toctree-l2"><a class="reference internal" href="embedding.html#converting-types">Converting Types</a></li> <li class="toctree-l2"><a class="reference internal" href="embedding.html#calling-julia-functions">Calling Julia Functions</a></li> <li class="toctree-l2"><a class="reference internal" href="embedding.html#memory-management">Memory Management</a></li> <li class="toctree-l2"><a class="reference internal" href="embedding.html#working-with-arrays">Working with Arrays</a></li> <li class="toctree-l2"><a class="reference internal" href="embedding.html#exceptions">Exceptions</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="packages.html">Packages</a><ul> <li class="toctree-l2"><a class="reference internal" href="packages.html#package-status">Package Status</a></li> <li class="toctree-l2"><a class="reference internal" href="packages.html#adding-and-removing-packages">Adding and Removing Packages</a></li> <li class="toctree-l2"><a class="reference internal" href="packages.html#installing-unregistered-packages">Installing Unregistered Packages</a></li> <li class="toctree-l2"><a class="reference internal" href="packages.html#updating-packages">Updating Packages</a></li> <li class="toctree-l2"><a class="reference internal" href="packages.html#checkout-pin-and-free">Checkout, Pin and Free</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="packages.html#package-development">Package Development</a><ul> <li class="toctree-l2"><a class="reference internal" href="packages.html#initial-setup">Initial Setup</a></li> <li class="toctree-l2"><a class="reference internal" href="packages.html#generating-a-new-package">Generating a New Package</a></li> <li class="toctree-l2"><a class="reference internal" href="packages.html#making-your-package-available">Making Your Package Available</a></li> <li class="toctree-l2"><a class="reference internal" href="packages.html#publishing-your-package">Publishing Your Package</a></li> <li class="toctree-l2"><a class="reference internal" href="packages.html#tagging-package-versions">Tagging Package Versions</a></li> <li class="toctree-l2"><a class="reference internal" href="packages.html#fixing-package-requirements">Fixing Package Requirements</a></li> <li class="toctree-l2"><a class="reference internal" href="packages.html#man-package-requirements">Requirements Specification</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="performance-tips.html">Performance Tips</a><ul> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#avoid-global-variables">Avoid global variables</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#measure-performance-with-time-and-pay-attention-to-memory-allocation">Measure performance with <tt class="docutils literal"><span class="pre">@time</span></tt> and pay attention to memory allocation</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#tools">Tools</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#avoid-containers-with-abstract-type-parameters">Avoid containers with abstract type parameters</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#type-declarations">Type declarations</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#break-functions-into-multiple-definitions">Break functions into multiple definitions</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#write-type-stable-functions">Write “type-stable” functions</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#avoid-changing-the-type-of-a-variable">Avoid changing the type of a variable</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#separate-kernel-functions">Separate kernel functions</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#access-arrays-in-memory-order-along-columns">Access arrays in memory order, along columns</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#pre-allocating-outputs">Pre-allocating outputs</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#avoid-string-interpolation-for-i-o">Avoid string interpolation for I/O</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#fix-deprecation-warnings">Fix deprecation warnings</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#tweaks">Tweaks</a></li> <li class="toctree-l2"><a class="reference internal" href="performance-tips.html#performance-annotations">Performance Annotations</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="style-guide.html">Style Guide</a><ul> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#write-functions-not-just-scripts">Write functions, not just scripts</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#avoid-writing-overly-specific-types">Avoid writing overly-specific types</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#handle-excess-argument-diversity-in-the-caller">Handle excess argument diversity in the caller</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#append-to-names-of-functions-that-modify-their-arguments">Append <cite>!</cite> to names of functions that modify their arguments</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#avoid-strange-type-unions">Avoid strange type Unions</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#try-to-avoid-nullable-fields">Try to avoid nullable fields</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#avoid-elaborate-container-types">Avoid elaborate container types</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#avoid-underscores-in-names">Avoid underscores in names</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#don-t-overuse-try-catch">Don’t overuse try-catch</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#don-t-parenthesize-conditions">Don’t parenthesize conditions</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#don-t-overuse">Don’t overuse ...</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#don-t-use-unnecessary-static-parameters">Don’t use unnecessary static parameters</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#avoid-confusion-about-whether-something-is-an-instance-or-a-type">Avoid confusion about whether something is an instance or a type</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#don-t-overuse-macros">Don’t overuse macros</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#don-t-expose-unsafe-operations-at-the-interface-level">Don’t expose unsafe operations at the interface level</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#don-t-overload-methods-of-base-container-types">Don’t overload methods of base container types</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#be-careful-with-type-equality">Be careful with type equality</a></li> <li class="toctree-l2"><a class="reference internal" href="style-guide.html#do-not-write-x-f-x">Do not write <tt class="docutils literal"><span class="pre">x->f(x)</span></tt></a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="faq.html">Frequently Asked Questions</a><ul> <li class="toctree-l2"><a class="reference internal" href="faq.html#sessions-and-the-repl">Sessions and the REPL</a></li> <li class="toctree-l2"><a class="reference internal" href="faq.html#functions">Functions</a></li> <li class="toctree-l2"><a class="reference internal" href="faq.html#types-type-declarations-and-constructors">Types, type declarations, and constructors</a></li> <li class="toctree-l2"><a class="reference internal" href="faq.html#nothingness-and-missing-values">Nothingness and missing values</a></li> <li class="toctree-l2"><a class="reference internal" href="faq.html#julia-releases">Julia Releases</a></li> <li class="toctree-l2"><a class="reference internal" href="faq.html#developing-julia">Developing Julia</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="noteworthy-differences.html">Noteworthy Differences from other Languages</a><ul> <li class="toctree-l2"><a class="reference internal" href="noteworthy-differences.html#noteworthy-differences-from-matlab">Noteworthy differences from MATLAB</a></li> <li class="toctree-l2"><a class="reference internal" href="noteworthy-differences.html#noteworthy-differences-from-r">Noteworthy differences from R</a></li> <li class="toctree-l2"><a class="reference internal" href="noteworthy-differences.html#noteworthy-differences-from-python">Noteworthy differences from Python</a></li> </ul> </li> </ul> <ul> <li class="toctree-l1"><a class="reference internal" href="../stdlib/base.html">The Standard Library</a><ul> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#introduction">Introduction</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#getting-around">Getting Around</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#all-objects">All Objects</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#types">Types</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#generic-functions">Generic Functions</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#syntax">Syntax</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#iteration">Iteration</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#general-collections">General Collections</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#iterable-collections">Iterable Collections</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#indexable-collections">Indexable Collections</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#associative-collections">Associative Collections</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#set-like-collections">Set-Like Collections</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#dequeues">Dequeues</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#strings">Strings</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#i-o">I/O</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#network-i-o">Network I/O</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#text-i-o">Text I/O</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#multimedia-i-o">Multimedia I/O</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#memory-mapped-i-o">Memory-mapped I/O</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#standard-numeric-types">Standard Numeric Types</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#mathematical-operators">Mathematical Operators</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#mathematical-functions">Mathematical Functions</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#data-formats">Data Formats</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#numbers">Numbers</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#bigfloats">BigFloats</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#random-numbers">Random Numbers</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#arrays">Arrays</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#combinatorics">Combinatorics</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#statistics">Statistics</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#signal-processing">Signal Processing</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#numerical-integration">Numerical Integration</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#parallel-computing">Parallel Computing</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#distributed-arrays">Distributed Arrays</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#shared-arrays-experimental-unix-only-feature">Shared Arrays (Experimental, UNIX-only feature)</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#system">System</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#c-interface">C Interface</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#errors">Errors</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#tasks">Tasks</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#events">Events</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#reflection">Reflection</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/base.html#internals">Internals</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/sparse.html">Sparse Matrices</a></li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/linalg.html">Linear Algebra</a></li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/linalg.html#module-Base.LinAlg.BLAS">BLAS Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/constants.html">Constants</a></li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/file.html">Filesystem</a></li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/punctuation.html">Punctuation</a></li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/sort.html">Sorting and Related Functions</a><ul> <li class="toctree-l2"><a class="reference internal" href="../stdlib/sort.html#sorting-functions">Sorting Functions</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/sort.html#order-related-functions">Order-Related Functions</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/sort.html#sorting-algorithms">Sorting Algorithms</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/pkg.html">Package Manager Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/collections.html">Collections and Data Structures</a><ul> <li class="toctree-l2"><a class="reference internal" href="../stdlib/collections.html#priorityqueue">PriorityQueue</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/collections.html#heap-functions">Heap Functions</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/graphics.html">Graphics</a><ul> <li class="toctree-l2"><a class="reference internal" href="../stdlib/graphics.html#geometry">Geometry</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/test.html">Unit and Functional Testing</a><ul> <li class="toctree-l2"><a class="reference internal" href="../stdlib/test.html#overview">Overview</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/test.html#handlers">Handlers</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/test.html#macros">Macros</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/test.html#functions">Functions</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/test.html#testing-base-julia">Testing Base Julia</a></li> <li class="toctree-l1"><a class="reference internal" href="../stdlib/profile.html">Profiling</a><ul> <li class="toctree-l2"><a class="reference internal" href="../stdlib/profile.html#basic-usage">Basic usage</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/profile.html#accumulation-and-clearing">Accumulation and clearing</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/profile.html#options-for-controlling-the-display-of-profile-results">Options for controlling the display of profile results</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/profile.html#configuration">Configuration</a></li> <li class="toctree-l2"><a class="reference internal" href="../stdlib/profile.html#function-reference">Function reference</a></li> </ul> </li> </ul> <ul> <li class="toctree-l1"><a class="reference internal" href="../devdocs/julia.html">Documentation of Julia’s Internals</a><ul> <li class="toctree-l2"><a class="reference internal" href="../devdocs/cartesian.html">Base.Cartesian</a></li> <li class="toctree-l2"><a class="reference internal" href="../devdocs/sysimg.html">System Image Building</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../devdocs/C.html">Developing/debugging Julia’s C code</a><ul> <li class="toctree-l2"><a class="reference internal" href="../devdocs/backtraces.html">Reporting and analyzing crashes (segfaults)</a></li> <li class="toctree-l2"><a class="reference internal" href="../devdocs/debuggingtips.html">gdb debugging tips</a></li> </ul> </li> </ul> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" role="navigation" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="../index.html">Julia Language</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="../index.html">Docs</a> »</li> <li>Metaprogramming</li> <li class="wy-breadcrumbs-aside"> <a href="../_sources/manual/metaprogramming.txt" rel="nofollow"> View page source</a> </li> </ul> <hr/> </div> <div role="main" class="document"> <div class="section" id="metaprogramming"> <span id="man-metaprogramming"></span><h1>Metaprogramming<a class="headerlink" href="#metaprogramming" title="Permalink to this headline">¶</a></h1> <p>The strongest legacy of Lisp in the Julia language is its metaprogramming support. Like Lisp, Julia represents its own code as a data structure of the language itself. Since code is represented by objects that can be created and manipulated from within the language, it is possible for a program to transform and generate its own code. This allows sophisticated code generation without extra build steps, and also allows true Lisp-style macros, as compared to preprocessor “macro” systems, like that of C and C++, that perform superficial textual manipulation as a separate pass before any real parsing or interpretation occurs. Another aspect of metaprogramming is reflection: the ability of a running program to dynamically discover properties of itself. Reflection emerges naturally from the fact that all data types and code are represented by normal Julia data structures, so the structure of the program and its types can be explored programmatically just like any other data.</p> <div class="section" id="expressions-and-eval"> <h2>Expressions and Eval<a class="headerlink" href="#expressions-and-eval" title="Permalink to this headline">¶</a></h2> <p>Julia code is represented as a syntax tree built out of Julia data structures of type <tt class="docutils literal"><span class="pre">Expr</span></tt>. This makes it easy to construct and manipulate Julia code from within Julia, without generating or parsing source text. Here is the definition of the <tt class="docutils literal"><span class="pre">Expr</span></tt> type:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">type</span><span class="nc"> Expr</span> <span class="n">head</span><span class="p">::</span><span class="n">Symbol</span> <span class="n">args</span><span class="p">::</span><span class="n">Array</span><span class="p">{</span><span class="kt">Any</span><span class="p">,</span><span class="mi">1</span><span class="p">}</span> <span class="n">typ</span> <span class="k">end</span> </pre></div> </div> <p>The <tt class="docutils literal"><span class="pre">head</span></tt> is a symbol identifying the kind of expression, and <tt class="docutils literal"><span class="pre">args</span></tt> is an array of subexpressions, which may be symbols referencing the values of variables at evaluation time, may be nested <tt class="docutils literal"><span class="pre">Expr</span></tt> objects, or may be actual values of objects. The <tt class="docutils literal"><span class="pre">typ</span></tt> field is used by type inference to store type annotations, and can generally be ignored.</p> <p>There is special syntax for “quoting” code (analogous to quoting strings) that makes it easy to create expression objects without explicitly constructing <tt class="docutils literal"><span class="pre">Expr</span></tt> objects. There are two forms: a short form for inline expressions using <tt class="docutils literal"><span class="pre">:</span></tt> followed by a single expression, and a long form for blocks of code, enclosed in <tt class="docutils literal"><span class="pre">quote</span> <span class="pre">...</span> <span class="pre">end</span></tt>. Here is an example of the short form used to quote an arithmetic expression:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="n">ex</span> <span class="o">=</span> <span class="p">:(</span><span class="n">a</span><span class="o">+</span><span class="n">b</span><span class="o">*</span><span class="n">c</span><span class="o">+</span><span class="mi">1</span><span class="p">)</span> <span class="p">:(</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="o">*</span> <span class="n">c</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span> <span class="n">julia</span><span class="o">></span> <span class="nb">typeof</span><span class="p">(</span><span class="n">ex</span><span class="p">)</span> <span class="n">Expr</span> <span class="n">julia</span><span class="o">></span> <span class="n">ex</span><span class="o">.</span><span class="n">head</span> <span class="p">:</span><span class="n">call</span> <span class="n">julia</span><span class="o">></span> <span class="nb">typeof</span><span class="p">(</span><span class="n">ans</span><span class="p">)</span> <span class="n">Symbol</span> <span class="n">julia</span><span class="o">></span> <span class="n">ex</span><span class="o">.</span><span class="n">args</span> <span class="mi">4</span><span class="o">-</span><span class="n">element</span> <span class="n">Array</span><span class="p">{</span><span class="kt">Any</span><span class="p">,</span><span class="mi">1</span><span class="p">}:</span> <span class="p">:</span><span class="o">+</span> <span class="p">:</span><span class="n">a</span> <span class="p">:(</span><span class="n">b</span> <span class="o">*</span> <span class="n">c</span><span class="p">)</span> <span class="mi">1</span> <span class="n">julia</span><span class="o">></span> <span class="nb">typeof</span><span class="p">(</span><span class="n">ex</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span> <span class="n">Symbol</span> <span class="n">julia</span><span class="o">></span> <span class="nb">typeof</span><span class="p">(</span><span class="n">ex</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">2</span><span class="p">])</span> <span class="n">Symbol</span> <span class="n">julia</span><span class="o">></span> <span class="nb">typeof</span><span class="p">(</span><span class="n">ex</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">3</span><span class="p">])</span> <span class="n">Expr</span> <span class="n">julia</span><span class="o">></span> <span class="nb">typeof</span><span class="p">(</span><span class="n">ex</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">4</span><span class="p">])</span> <span class="kt">Int64</span> </pre></div> </div> <p>Expressions provided by the parser generally only have symbols, other expressions, and literal values as their args, whereas expressions constructed by Julia code can easily have arbitrary run-time values without literal forms as args. In this specific example, <tt class="docutils literal"><span class="pre">+</span></tt> and <tt class="docutils literal"><span class="pre">a</span></tt> are symbols, <tt class="docutils literal"><span class="pre">*(b,c)</span></tt> is a subexpression, and <tt class="docutils literal"><span class="pre">1</span></tt> is a literal 64-bit signed integer. Here’s an example of the longer expression quoting form:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="k">quote</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span> <span class="n">y</span> <span class="o">=</span> <span class="mi">2</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="k">end</span> <span class="k">quote</span> <span class="c"># none, line 2:</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span> <span class="c"># line 3:</span> <span class="n">y</span> <span class="o">=</span> <span class="mi">2</span> <span class="c"># line 4:</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="k">end</span> </pre></div> </div> <div class="section" id="symbols"> <h3>Symbols<a class="headerlink" href="#symbols" title="Permalink to this headline">¶</a></h3> <p>When the argument to <tt class="docutils literal"><span class="pre">:</span></tt> is just a symbol, a <tt class="docutils literal"><span class="pre">Symbol</span></tt> object results instead of an <tt class="docutils literal"><span class="pre">Expr</span></tt>:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="p">:</span><span class="n">foo</span> <span class="p">:</span><span class="n">foo</span> <span class="n">julia</span><span class="o">></span> <span class="nb">typeof</span><span class="p">(</span><span class="n">ans</span><span class="p">)</span> <span class="n">Symbol</span> </pre></div> </div> <p>In the context of an expression, symbols are used to indicate access to variables, and when an expression is evaluated, a symbol evaluates to the value bound to that symbol in the appropriate <a class="reference internal" href="variables-and-scoping.html#man-variables-and-scoping"><em>scope</em></a>.</p> <p>Sometimes extra parentheses around the argument to <tt class="docutils literal"><span class="pre">:</span></tt> are needed to avoid ambiguity in parsing.:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="p">:(:)</span> <span class="p">:(:)</span> <span class="n">julia</span><span class="o">></span> <span class="p">:(::)</span> <span class="p">:(::)</span> </pre></div> </div> <p><tt class="docutils literal"><span class="pre">Symbol</span></tt>s can also be created using the <tt class="docutils literal"><span class="pre">symbol</span></tt> function, which takes a character or string as its argument:</p> <div class="highlight-julia"><pre>julia> symbol('\'') :' julia> symbol("'") :'</pre> </div> </div> <div class="section" id="eval-and-interpolation"> <h3><tt class="docutils literal"><span class="pre">eval</span></tt> and Interpolation<a class="headerlink" href="#eval-and-interpolation" title="Permalink to this headline">¶</a></h3> <p>Given an expression object, one can cause Julia to evaluate (execute) it at global scope using the <tt class="docutils literal"><span class="pre">eval</span></tt> function:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="p">:(</span><span class="mi">1</span> <span class="o">+</span> <span class="mi">2</span><span class="p">)</span> <span class="p">:(</span><span class="mi">1</span> <span class="o">+</span> <span class="mi">2</span><span class="p">)</span> <span class="n">julia</span><span class="o">></span> <span class="n">eval</span><span class="p">(</span><span class="n">ans</span><span class="p">)</span> <span class="mi">3</span> <span class="n">julia</span><span class="o">></span> <span class="n">ex</span> <span class="o">=</span> <span class="p">:(</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="p">)</span> <span class="p">:(</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="p">)</span> <span class="n">julia</span><span class="o">></span> <span class="n">eval</span><span class="p">(</span><span class="n">ex</span><span class="p">)</span> <span class="n">ERROR</span><span class="p">:</span> <span class="n">a</span> <span class="n">not</span> <span class="n">defined</span> <span class="n">julia</span><span class="o">></span> <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span> <span class="n">julia</span><span class="o">></span> <span class="n">eval</span><span class="p">(</span><span class="n">ex</span><span class="p">)</span> <span class="mi">3</span> </pre></div> </div> <p>Every <a class="reference internal" href="modules.html#man-modules"><em>module</em></a> has its own <tt class="docutils literal"><span class="pre">eval</span></tt> function that evaluates expressions in its global scope. Expressions passed to <tt class="docutils literal"><span class="pre">eval</span></tt> are not limited to returning values — they can also have side-effects that alter the state of the enclosing module’s environment:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="n">ex</span> <span class="o">=</span> <span class="p">:(</span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span><span class="p">)</span> <span class="p">:(</span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span><span class="p">)</span> <span class="n">julia</span><span class="o">></span> <span class="n">x</span> <span class="n">ERROR</span><span class="p">:</span> <span class="n">x</span> <span class="n">not</span> <span class="n">defined</span> <span class="n">julia</span><span class="o">></span> <span class="n">eval</span><span class="p">(</span><span class="n">ex</span><span class="p">)</span> <span class="mi">1</span> <span class="n">julia</span><span class="o">></span> <span class="n">x</span> <span class="mi">1</span> </pre></div> </div> <p>Here, the evaluation of an expression object causes a value to be assigned to the global variable <tt class="docutils literal"><span class="pre">x</span></tt>.</p> <p>Since expressions are just <tt class="docutils literal"><span class="pre">Expr</span></tt> objects which can be constructed programmatically and then evaluated, one can, from within Julia code, dynamically generate arbitrary code which can then be run using <tt class="docutils literal"><span class="pre">eval</span></tt>. Here is a simple example:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="n">julia</span><span class="o">></span> <span class="n">ex</span> <span class="o">=</span> <span class="n">Expr</span><span class="p">(:</span><span class="n">call</span><span class="p">,</span> <span class="p">:</span><span class="o">+</span><span class="p">,</span><span class="n">a</span><span class="p">,:</span><span class="n">b</span><span class="p">)</span> <span class="p">:(</span><span class="mi">1</span> <span class="o">+</span> <span class="n">b</span><span class="p">)</span> <span class="n">julia</span><span class="o">></span> <span class="n">a</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span> <span class="n">julia</span><span class="o">></span> <span class="n">eval</span><span class="p">(</span><span class="n">ex</span><span class="p">)</span> <span class="mi">3</span> </pre></div> </div> <p>The value of <tt class="docutils literal"><span class="pre">a</span></tt> is used to construct the expression <tt class="docutils literal"><span class="pre">ex</span></tt> which applies the <tt class="docutils literal"><span class="pre">+</span></tt> function to the value 1 and the variable <tt class="docutils literal"><span class="pre">b</span></tt>. Note the important distinction between the way <tt class="docutils literal"><span class="pre">a</span></tt> and <tt class="docutils literal"><span class="pre">b</span></tt> are used:</p> <ul class="simple"> <li>The value of the <em>variable</em> <tt class="docutils literal"><span class="pre">a</span></tt> at expression construction time is used as an immediate value in the expression. Thus, the value of <tt class="docutils literal"><span class="pre">a</span></tt> when the expression is evaluated no longer matters: the value in the expression is already <tt class="docutils literal"><span class="pre">1</span></tt>, independent of whatever the value of <tt class="docutils literal"><span class="pre">a</span></tt> might be.</li> <li>On the other hand, the <em>symbol</em> <tt class="docutils literal"><span class="pre">:b</span></tt> is used in the expression construction, so the value of the variable <tt class="docutils literal"><span class="pre">b</span></tt> at that time is irrelevant — <tt class="docutils literal"><span class="pre">:b</span></tt> is just a symbol and the variable <tt class="docutils literal"><span class="pre">b</span></tt> need not even be defined. At expression evaluation time, however, the value of the symbol <tt class="docutils literal"><span class="pre">:b</span></tt> is resolved by looking up the value of the variable <tt class="docutils literal"><span class="pre">b</span></tt>.</li> </ul> <p>Constructing <tt class="docutils literal"><span class="pre">Expr</span></tt> objects like this is powerful, but somewhat tedious and ugly. Since the Julia parser is already excellent at producing expression objects, Julia allows “splicing” or interpolation of expression objects, prefixed with <tt class="docutils literal"><span class="pre">$</span></tt>, into quoted expressions, written using normal syntax. The above example can be written more clearly and concisely using interpolation:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="n">julia</span><span class="o">></span> <span class="n">ex</span> <span class="o">=</span> <span class="p">:(</span><span class="o">$</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="p">)</span> <span class="p">:(</span><span class="mi">1</span> <span class="o">+</span> <span class="n">b</span><span class="p">)</span> </pre></div> </div> <p>This syntax is automatically rewritten to the form above where we explicitly called <tt class="docutils literal"><span class="pre">Expr</span></tt>. The use of <tt class="docutils literal"><span class="pre">$</span></tt> for expression interpolation is intentionally reminiscent of <a class="reference internal" href="strings.html#man-string-interpolation"><em>string interpolation</em></a> and <a class="reference internal" href="running-external-programs.html#man-command-interpolation"><em>command interpolation</em></a>. Expression interpolation allows convenient, readable programmatic construction of complex Julia expressions.</p> </div> <div class="section" id="code-generation"> <h3>Code Generation<a class="headerlink" href="#code-generation" title="Permalink to this headline">¶</a></h3> <p>When a significant amount of repetitive boilerplate code is required, it is common to generate it programmatically to avoid redundancy. In most languages, this requires an extra build step, and a separate program to generate the repetitive code. In Julia, expression interpolation and eval allow such code generation to take place in the normal course of program execution. For example, the following code defines a series of operators on three arguments in terms of their 2-argument forms:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">for</span> <span class="n">op</span> <span class="o">=</span> <span class="p">(:</span><span class="o">+</span><span class="p">,</span> <span class="p">:</span><span class="o">*</span><span class="p">,</span> <span class="p">:</span><span class="o">&</span><span class="p">,</span> <span class="p">:</span><span class="o">|</span><span class="p">,</span> <span class="p">:</span><span class="o">$</span><span class="p">)</span> <span class="n">eval</span><span class="p">(</span><span class="k">quote</span> <span class="p">(</span><span class="o">$</span><span class="n">op</span><span class="p">)(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">)</span> <span class="o">=</span> <span class="p">(</span><span class="o">$</span><span class="n">op</span><span class="p">)((</span><span class="o">$</span><span class="n">op</span><span class="p">)(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">),</span><span class="n">c</span><span class="p">)</span> <span class="k">end</span><span class="p">)</span> <span class="k">end</span> </pre></div> </div> <p>In this manner, Julia acts as its own preprocessor, and allows code generation from inside the language. The above code could be written slightly more tersely using the <tt class="docutils literal"><span class="pre">:</span></tt> prefix quoting form:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">for</span> <span class="n">op</span> <span class="o">=</span> <span class="p">(:</span><span class="o">+</span><span class="p">,</span> <span class="p">:</span><span class="o">*</span><span class="p">,</span> <span class="p">:</span><span class="o">&</span><span class="p">,</span> <span class="p">:</span><span class="o">|</span><span class="p">,</span> <span class="p">:</span><span class="o">$</span><span class="p">)</span> <span class="n">eval</span><span class="p">(:((</span><span class="o">$</span><span class="n">op</span><span class="p">)(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">)</span> <span class="o">=</span> <span class="p">(</span><span class="o">$</span><span class="n">op</span><span class="p">)((</span><span class="o">$</span><span class="n">op</span><span class="p">)(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">),</span><span class="n">c</span><span class="p">)))</span> <span class="k">end</span> </pre></div> </div> <p>This sort of in-language code generation, however, using the <tt class="docutils literal"><span class="pre">eval(quote(...))</span></tt> pattern, is common enough that Julia comes with a macro to abbreviate this pattern:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">for</span> <span class="n">op</span> <span class="o">=</span> <span class="p">(:</span><span class="o">+</span><span class="p">,</span> <span class="p">:</span><span class="o">*</span><span class="p">,</span> <span class="p">:</span><span class="o">&</span><span class="p">,</span> <span class="p">:</span><span class="o">|</span><span class="p">,</span> <span class="p">:</span><span class="o">$</span><span class="p">)</span> <span class="p">@</span><span class="n">eval</span> <span class="p">(</span><span class="o">$</span><span class="n">op</span><span class="p">)(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">)</span> <span class="o">=</span> <span class="p">(</span><span class="o">$</span><span class="n">op</span><span class="p">)((</span><span class="o">$</span><span class="n">op</span><span class="p">)(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">),</span><span class="n">c</span><span class="p">)</span> <span class="k">end</span> </pre></div> </div> <p>The <tt class="docutils literal"><span class="pre">@eval</span></tt> macro rewrites this call to be precisely equivalent to the above longer versions. For longer blocks of generated code, the expression argument given to <tt class="docutils literal"><span class="pre">@eval</span></tt> can be a block:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="p">@</span><span class="n">eval</span> <span class="k">begin</span> <span class="c"># multiple lines</span> <span class="k">end</span> </pre></div> </div> <p>Interpolating into an unquoted expression is not supported and will cause a compile-time error:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="o">$</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="n">ERROR</span><span class="p">:</span> <span class="n">unsupported</span> <span class="n">or</span> <span class="n">misplaced</span> <span class="n">expression</span> <span class="o">$</span> </pre></div> </div> </div> </div> <div class="section" id="macros"> <span id="man-macros"></span><h2>Macros<a class="headerlink" href="#macros" title="Permalink to this headline">¶</a></h2> <p>Macros are the analogue of functions for expression generation at compile time. Just as functions map a tuple of argument values to a return value, macros map a tuple of argument <em>expressions</em> to a returned <em>expression</em>. They allow the programmer to arbitrarily transform the written code to a resulting expression, which then takes the place of the macro call in the final syntax tree. Macros are invoked with the following general syntax:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="p">@</span><span class="n">name</span> <span class="n">expr1</span> <span class="n">expr2</span> <span class="o">...</span> <span class="p">@</span><span class="n">name</span><span class="p">(</span><span class="n">expr1</span><span class="p">,</span> <span class="n">expr2</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span> </pre></div> </div> <p>Note the distinguishing <tt class="docutils literal"><span class="pre">@</span></tt> before the macro name and the lack of commas between the argument expressions in the first form, and the lack of whitespace after <tt class="docutils literal"><span class="pre">@name</span></tt> in the second form. The two styles should not be mixed. For example, the following syntax is different from the examples above; it passes the tuple <tt class="docutils literal"><span class="pre">(expr1,</span> <span class="pre">expr2,</span> <span class="pre">...)</span></tt> as one argument to the macro:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="p">@</span><span class="n">name</span> <span class="p">(</span><span class="n">expr1</span><span class="p">,</span> <span class="n">expr2</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span> </pre></div> </div> <p>Before the program runs, this statement will be replaced with the returned result of calling an expander function for <tt class="docutils literal"><span class="pre">@name</span></tt> on the expression arguments. Expanders are defined with the <tt class="docutils literal"><span class="pre">macro</span></tt> keyword:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">macro</span> <span class="n">name</span><span class="p">(</span><span class="n">expr1</span><span class="p">,</span> <span class="n">expr2</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span> <span class="o">...</span> <span class="k">return</span> <span class="n">resulting_expr</span> <span class="k">end</span> </pre></div> </div> <p>Here, for example, is a simplified definition of Julia’s <tt class="docutils literal"><span class="pre">@assert</span></tt> macro:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">macro</span> <span class="nb">assert</span><span class="p">(</span><span class="n">ex</span><span class="p">)</span> <span class="k">return</span> <span class="p">:(</span><span class="o">$</span><span class="n">ex</span> <span class="o">?</span> <span class="n">nothing</span> <span class="p">:</span> <span class="nb">error</span><span class="p">(</span><span class="s">"Assertion failed: "</span><span class="p">,</span> <span class="o">$</span><span class="p">(</span><span class="n">string</span><span class="p">(</span><span class="n">ex</span><span class="p">))))</span> <span class="k">end</span> </pre></div> </div> <p>This macro can be used like this:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="p">@</span><span class="nb">assert</span> <span class="mi">1</span><span class="o">==</span><span class="mf">1.0</span> <span class="n">julia</span><span class="o">></span> <span class="p">@</span><span class="nb">assert</span> <span class="mi">1</span><span class="o">==</span><span class="mi">0</span> <span class="n">ERROR</span><span class="p">:</span> <span class="n">assertion</span> <span class="n">failed</span><span class="p">:</span> <span class="mi">1</span> <span class="o">==</span> <span class="mi">0</span> <span class="k">in</span> <span class="nb">error</span> <span class="n">at</span> <span class="nb">error</span><span class="o">.</span><span class="n">jl</span><span class="p">:</span><span class="mi">21</span> </pre></div> </div> <p>In place of the written syntax, the macro call is expanded at parse time to its returned result. This is equivalent to writing:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="mi">1</span><span class="o">==</span><span class="mf">1.0</span> <span class="o">?</span> <span class="n">nothing</span> <span class="p">:</span> <span class="nb">error</span><span class="p">(</span><span class="s">"Assertion failed: "</span><span class="p">,</span> <span class="s">"1==1.0"</span><span class="p">)</span> <span class="mi">1</span><span class="o">==</span><span class="mi">0</span> <span class="o">?</span> <span class="n">nothing</span> <span class="p">:</span> <span class="nb">error</span><span class="p">(</span><span class="s">"Assertion failed: "</span><span class="p">,</span> <span class="s">"1==0"</span><span class="p">)</span> </pre></div> </div> <p>That is, in the first call, the expression <tt class="docutils literal"><span class="pre">:(1==1.0)</span></tt> is spliced into the test condition slot, while the value of <tt class="docutils literal"><span class="pre">string(:(1==1.0))</span></tt> is spliced into the assertion message slot. The entire expression, thus constructed, is placed into the syntax tree where the <tt class="docutils literal"><span class="pre">@assert</span></tt> macro call occurs. Then at execution time, if the test expression evaluates to true, then <tt class="docutils literal"><span class="pre">nothing</span></tt> is returned, whereas if the test is false, an error is raised indicating the asserted expression that was false. Notice that it would not be possible to write this as a function, since only the <em>value</em> of the condition is available and it would be impossible to display the expression that computed it in the error message.</p> <p>The actual definition of <tt class="docutils literal"><span class="pre">@assert</span></tt> in the standard library is more complicated. It allows the user to optionally specify their own error message, instead of just printing the failed expression. Just like in functions with a variable number of arguments, this is specified with an ellipses following the last argument:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">macro</span> <span class="nb">assert</span><span class="p">(</span><span class="n">ex</span><span class="p">,</span> <span class="n">msgs</span><span class="o">...</span><span class="p">)</span> <span class="n">msg_body</span> <span class="o">=</span> <span class="n">isempty</span><span class="p">(</span><span class="n">msgs</span><span class="p">)</span> <span class="o">?</span> <span class="n">ex</span> <span class="p">:</span> <span class="n">msgs</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="n">msg</span> <span class="o">=</span> <span class="n">string</span><span class="p">(</span><span class="s">"assertion failed: "</span><span class="p">,</span> <span class="n">msg_body</span><span class="p">)</span> <span class="k">return</span> <span class="p">:(</span><span class="o">$</span><span class="n">ex</span> <span class="o">?</span> <span class="n">nothing</span> <span class="p">:</span> <span class="nb">error</span><span class="p">(</span><span class="o">$</span><span class="n">msg</span><span class="p">))</span> <span class="k">end</span> </pre></div> </div> <p>Now <tt class="docutils literal"><span class="pre">@assert</span></tt> has two modes of operation, depending upon the number of arguments it receives! If there’s only one argument, the tuple of expressions captured by <tt class="docutils literal"><span class="pre">msgs</span></tt> will be empty and it will behave the same as the simpler definition above. But now if the user specifies a second argument, it is printed in the message body instead of the failing expression. You can inspect the result of a macro expansion with the aptly named <tt class="xref jl jl-func docutils literal"><span class="pre">macroexpand()</span></tt> function:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="n">macroexpand</span><span class="p">(:(@</span><span class="nb">assert</span> <span class="n">a</span><span class="o">==</span><span class="n">b</span><span class="p">))</span> <span class="p">:(</span><span class="k">if</span> <span class="n">a</span> <span class="o">==</span> <span class="n">b</span> <span class="n">nothing</span> <span class="k">else</span> <span class="n">Base</span><span class="o">.</span><span class="nb">error</span><span class="p">(</span><span class="s">"assertion failed: a == b"</span><span class="p">)</span> <span class="k">end</span><span class="p">)</span> <span class="n">julia</span><span class="o">></span> <span class="n">macroexpand</span><span class="p">(:(@</span><span class="nb">assert</span> <span class="n">a</span><span class="o">==</span><span class="n">b</span> <span class="s">"a should equal b!"</span><span class="p">))</span> <span class="p">:(</span><span class="k">if</span> <span class="n">a</span> <span class="o">==</span> <span class="n">b</span> <span class="n">nothing</span> <span class="k">else</span> <span class="n">Base</span><span class="o">.</span><span class="nb">error</span><span class="p">(</span><span class="s">"assertion failed: a should equal b!"</span><span class="p">)</span> <span class="k">end</span><span class="p">)</span> </pre></div> </div> <p>There is yet another case that the actual <tt class="docutils literal"><span class="pre">@assert</span></tt> macro handles: what if, in addition to printing “a should equal b,” we wanted to print their values? One might naively try to use string interpolation in the custom message, e.g., <tt class="docutils literal"><span class="pre">@assert</span> <span class="pre">a==b</span> <span class="pre">"a</span> <span class="pre">($a)</span> <span class="pre">should</span> <span class="pre">equal</span> <span class="pre">b</span> <span class="pre">($b)!"</span></tt>, but this won’t work as expected with the above macro. Can you see why? Recall from <a class="reference internal" href="strings.html#man-string-interpolation"><em>string interpolation</em></a> that an interpolated string is rewritten to a call to the <tt class="docutils literal"><span class="pre">string</span></tt> function. Compare:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="nb">typeof</span><span class="p">(:(</span><span class="s">"a should equal b"</span><span class="p">))</span> <span class="n">ASCIIString</span> <span class="p">(</span><span class="n">constructor</span> <span class="n">with</span> <span class="mi">2</span> <span class="n">methods</span><span class="p">)</span> <span class="n">julia</span><span class="o">></span> <span class="nb">typeof</span><span class="p">(:(</span><span class="s">"a (</span><span class="si">$</span><span class="s">a) should equal b (</span><span class="si">$</span><span class="s">b)!"</span><span class="p">))</span> <span class="n">Expr</span> <span class="n">julia</span><span class="o">></span> <span class="n">dump</span><span class="p">(:(</span><span class="s">"a (</span><span class="si">$</span><span class="s">a) should equal b (</span><span class="si">$</span><span class="s">b)!"</span><span class="p">))</span> <span class="n">Expr</span> <span class="n">head</span><span class="p">:</span> <span class="n">Symbol</span> <span class="n">string</span> <span class="n">args</span><span class="p">:</span> <span class="n">Array</span><span class="p">(</span><span class="kt">Any</span><span class="p">,(</span><span class="mi">5</span><span class="p">,))</span> <span class="mi">1</span><span class="p">:</span> <span class="n">ASCIIString</span> <span class="s">"a ("</span> <span class="mi">2</span><span class="p">:</span> <span class="n">Symbol</span> <span class="n">a</span> <span class="mi">3</span><span class="p">:</span> <span class="n">ASCIIString</span> <span class="s">") should equal b ("</span> <span class="mi">4</span><span class="p">:</span> <span class="n">Symbol</span> <span class="n">b</span> <span class="mi">5</span><span class="p">:</span> <span class="n">ASCIIString</span> <span class="s">")!"</span> <span class="n">typ</span><span class="p">:</span> <span class="kt">Any</span> </pre></div> </div> <p>So now instead of getting a plain string in <tt class="docutils literal"><span class="pre">msg_body</span></tt>, the macro is receiving a full expression that will need to be evaluated in order to display as expected. This can be spliced directly into the returned expression as an argument to the <tt class="docutils literal"><span class="pre">string</span></tt> call; see <a class="reference external" href="https://github.com/JuliaLang/julia/blob/master/base/error.jl">error.jl</a> for the complete implementation.</p> <p>The <tt class="docutils literal"><span class="pre">@assert</span></tt> macro makes great use of splicing into quoted expressions to simplify the manipulation of expressions inside the macro body.</p> <div class="section" id="hygiene"> <h3>Hygiene<a class="headerlink" href="#hygiene" title="Permalink to this headline">¶</a></h3> <p>An issue that arises in more complex macros is that of <a class="reference external" href="http://en.wikipedia.org/wiki/Hygienic_macro">hygiene</a>. In short, macros must ensure that the variables they introduce in their returned expressions do not accidentally clash with existing variables in the surrounding code they expand into. Conversely, the expressions that are passed into a macro as arguments are often <em>expected</em> to evaluate in the context of the surrounding code, interacting with and modifying the existing variables. Another concern arises from the fact that a macro may be called in a different module from where it was defined. In this case we need to ensure that all global variables are resolved to the correct module. Julia already has a major advantage over languages with textual macro expansion (like C) in that it only needs to consider the returned expression. All the other variables (such as <tt class="docutils literal"><span class="pre">msg</span></tt> in <tt class="docutils literal"><span class="pre">@assert</span></tt> above) follow the <a class="reference internal" href="variables-and-scoping.html#man-variables-and-scoping"><em>normal scoping block behavior</em></a>.</p> <p>To demonstrate these issues, let us consider writing a <tt class="docutils literal"><span class="pre">@time</span></tt> macro that takes an expression as its argument, records the time, evaluates the expression, records the time again, prints the difference between the before and after times, and then has the value of the expression as its final value. The macro might look like this:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">macro</span> <span class="n">time</span><span class="p">(</span><span class="n">ex</span><span class="p">)</span> <span class="k">return</span> <span class="k">quote</span> <span class="kd">local</span> <span class="n">t0</span> <span class="o">=</span> <span class="n">time</span><span class="p">()</span> <span class="kd">local</span> <span class="n">val</span> <span class="o">=</span> <span class="o">$</span><span class="n">ex</span> <span class="kd">local</span> <span class="n">t1</span> <span class="o">=</span> <span class="n">time</span><span class="p">()</span> <span class="n">println</span><span class="p">(</span><span class="s">"elapsed time: "</span><span class="p">,</span> <span class="n">t1</span><span class="o">-</span><span class="n">t0</span><span class="p">,</span> <span class="s">" seconds"</span><span class="p">)</span> <span class="n">val</span> <span class="k">end</span> <span class="k">end</span> </pre></div> </div> <p>Here, we want <tt class="docutils literal"><span class="pre">t0</span></tt>, <tt class="docutils literal"><span class="pre">t1</span></tt>, and <tt class="docutils literal"><span class="pre">val</span></tt> to be private temporary variables, and we want <tt class="docutils literal"><span class="pre">time</span></tt> to refer to the <tt class="docutils literal"><span class="pre">time</span></tt> function in the standard library, not to any <tt class="docutils literal"><span class="pre">time</span></tt> variable the user might have (the same applies to <tt class="docutils literal"><span class="pre">println</span></tt>). Imagine the problems that could occur if the user expression <tt class="docutils literal"><span class="pre">ex</span></tt> also contained assignments to a variable called <tt class="docutils literal"><span class="pre">t0</span></tt>, or defined its own <tt class="docutils literal"><span class="pre">time</span></tt> variable. We might get errors, or mysteriously incorrect behavior.</p> <p>Julia’s macro expander solves these problems in the following way. First, variables within a macro result are classified as either local or global. A variable is considered local if it is assigned to (and not declared global), declared local, or used as a function argument name. Otherwise, it is considered global. Local variables are then renamed to be unique (using the <tt class="docutils literal"><span class="pre">gensym</span></tt> function, which generates new symbols), and global variables are resolved within the macro definition environment. Therefore both of the above concerns are handled; the macro’s locals will not conflict with any user variables, and <tt class="docutils literal"><span class="pre">time</span></tt> and <tt class="docutils literal"><span class="pre">println</span></tt> will refer to the standard library definitions.</p> <p>One problem remains however. Consider the following use of this macro:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">module</span> <span class="n">MyModule</span> <span class="k">import</span> <span class="n">Base</span><span class="o">.</span><span class="p">@</span><span class="n">time</span> <span class="n">time</span><span class="p">()</span> <span class="o">=</span> <span class="o">...</span> <span class="c"># compute something</span> <span class="p">@</span><span class="n">time</span> <span class="n">time</span><span class="p">()</span> <span class="k">end</span> </pre></div> </div> <p>Here the user expression <tt class="docutils literal"><span class="pre">ex</span></tt> is a call to <tt class="docutils literal"><span class="pre">time</span></tt>, but not the same <tt class="docutils literal"><span class="pre">time</span></tt> function that the macro uses. It clearly refers to <tt class="docutils literal"><span class="pre">MyModule.time</span></tt>. Therefore we must arrange for the code in <tt class="docutils literal"><span class="pre">ex</span></tt> to be resolved in the macro call environment. This is done by “escaping” the expression with the <tt class="docutils literal"><span class="pre">esc</span></tt> function:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">macro</span> <span class="n">time</span><span class="p">(</span><span class="n">ex</span><span class="p">)</span> <span class="o">...</span> <span class="kd">local</span> <span class="n">val</span> <span class="o">=</span> <span class="o">$</span><span class="p">(</span><span class="n">esc</span><span class="p">(</span><span class="n">ex</span><span class="p">))</span> <span class="o">...</span> <span class="k">end</span> </pre></div> </div> <p>An expression wrapped in this manner is left alone by the macro expander and simply pasted into the output verbatim. Therefore it will be resolved in the macro call environment.</p> <p>This escaping mechanism can be used to “violate” hygiene when necessary, in order to introduce or manipulate user variables. For example, the following macro sets <tt class="docutils literal"><span class="pre">x</span></tt> to zero in the call environment:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">macro</span> <span class="n">zerox</span><span class="p">()</span> <span class="k">return</span> <span class="n">esc</span><span class="p">(:(</span><span class="n">x</span> <span class="o">=</span> <span class="mi">0</span><span class="p">))</span> <span class="k">end</span> <span class="k">function</span><span class="nf"> foo</span><span class="p">()</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span> <span class="p">@</span><span class="n">zerox</span> <span class="n">x</span> <span class="c"># is zero</span> <span class="k">end</span> </pre></div> </div> <p>This kind of manipulation of variables should be used judiciously, but is occasionally quite handy.</p> </div> <div class="section" id="non-standard-string-literals"> <span id="man-non-standard-string-literals2"></span><h3>Non-Standard String Literals<a class="headerlink" href="#non-standard-string-literals" title="Permalink to this headline">¶</a></h3> <p>Recall from <a class="reference internal" href="strings.html#man-non-standard-string-literals"><em>Strings</em></a> that string literals prefixed by an identifier are called non-standard string literals, and can have different semantics than un-prefixed string literals. For example:</p> <ul class="simple"> <li><tt class="docutils literal"><span class="pre">r"^\s*(?:#|$)"</span></tt> produces a regular expression object rather than a string</li> <li><tt class="docutils literal"><span class="pre">b"DATA\xff\u2200"</span></tt> is a byte array literal for <tt class="docutils literal"><span class="pre">[68,65,84,65,255,226,136,128]</span></tt>.</li> </ul> <p>Perhaps surprisingly, these behaviors are not hard-coded into the Julia parser or compiler. Instead, they are custom behaviors provided by a general mechanism that anyone can use: prefixed string literals are parsed as calls to specially-named macros. For example, the regular expression macro is just the following:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">macro</span> <span class="n">r_str</span><span class="p">(</span><span class="n">p</span><span class="p">)</span> <span class="n">Regex</span><span class="p">(</span><span class="n">p</span><span class="p">)</span> <span class="k">end</span> </pre></div> </div> <p>That’s all. This macro says that the literal contents of the string literal <tt class="docutils literal"><span class="pre">r"^\s*(?:#|$)"</span></tt> should be passed to the <tt class="docutils literal"><span class="pre">@r_str</span></tt> macro and the result of that expansion should be placed in the syntax tree where the string literal occurs. In other words, the expression <tt class="docutils literal"><span class="pre">r"^\s*(?:#|$)"</span></tt> is equivalent to placing the following object directly into the syntax tree:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">Regex</span><span class="p">(</span><span class="s">"^</span><span class="se">\\</span><span class="s">s*(?:#|\</span><span class="si">$</span><span class="s">)"</span><span class="p">)</span> </pre></div> </div> <p>Not only is the string literal form shorter and far more convenient, but it is also more efficient: since the regular expression is compiled and the <tt class="docutils literal"><span class="pre">Regex</span></tt> object is actually created <em>when the code is compiled</em>, the compilation occurs only once, rather than every time the code is executed. Consider if the regular expression occurs in a loop:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">for</span> <span class="n">line</span> <span class="o">=</span> <span class="n">lines</span> <span class="n">m</span> <span class="o">=</span> <span class="n">match</span><span class="p">(</span><span class="n">r</span><span class="s">"^\s*(?:#|</span><span class="si">$</span><span class="s">)"</span><span class="p">,</span> <span class="n">line</span><span class="p">)</span> <span class="k">if</span> <span class="n">m</span> <span class="o">==</span> <span class="n">nothing</span> <span class="c"># non-comment</span> <span class="k">else</span> <span class="c"># comment</span> <span class="k">end</span> <span class="k">end</span> </pre></div> </div> <p>Since the regular expression <tt class="docutils literal"><span class="pre">r"^\s*(?:#|$)"</span></tt> is compiled and inserted into the syntax tree when this code is parsed, the expression is only compiled once instead of each time the loop is executed. In order to accomplish this without macros, one would have to write this loop like this:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">re</span> <span class="o">=</span> <span class="n">Regex</span><span class="p">(</span><span class="s">"^</span><span class="se">\\</span><span class="s">s*(?:#|\</span><span class="si">$</span><span class="s">)"</span><span class="p">)</span> <span class="k">for</span> <span class="n">line</span> <span class="o">=</span> <span class="n">lines</span> <span class="n">m</span> <span class="o">=</span> <span class="n">match</span><span class="p">(</span><span class="n">re</span><span class="p">,</span> <span class="n">line</span><span class="p">)</span> <span class="k">if</span> <span class="n">m</span> <span class="o">==</span> <span class="n">nothing</span> <span class="c"># non-comment</span> <span class="k">else</span> <span class="c"># comment</span> <span class="k">end</span> <span class="k">end</span> </pre></div> </div> <p>Moreover, if the compiler could not determine that the regex object was constant over all loops, certain optimizations might not be possible, making this version still less efficient than the more convenient literal form above. Of course, there are still situations where the non-literal form is more convenient: if one needs to interpolate a variable into the regular expression, one must take this more verbose approach; in cases where the regular expression pattern itself is dynamic, potentially changing upon each loop iteration, a new regular expression object must be constructed on each iteration. In the vast majority of use cases, however, regular expressions are not constructed based on run-time data. In this majority of cases, the ability to write regular expressions as compile-time values is invaluable.</p> <p>The mechanism for user-defined string literals is deeply, profoundly powerful. Not only are Julia’s non-standard literals implemented using it, but also the command literal syntax (<tt class="docutils literal"><span class="pre">`echo</span> <span class="pre">"Hello,</span> <span class="pre">$person"`</span></tt>) is implemented with the following innocuous-looking macro:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">macro</span> <span class="n">cmd</span><span class="p">(</span><span class="n">str</span><span class="p">)</span> <span class="p">:(</span><span class="n">cmd_gen</span><span class="p">(</span><span class="o">$</span><span class="n">shell_parse</span><span class="p">(</span><span class="n">str</span><span class="p">)))</span> <span class="k">end</span> </pre></div> </div> <p>Of course, a large amount of complexity is hidden in the functions used in this macro definition, but they are just functions, written entirely in Julia. You can read their source and see precisely what they do — and all they do is construct expression objects to be inserted into your program’s syntax tree.</p> </div> </div> <div class="section" id="reflection"> <h2>Reflection<a class="headerlink" href="#reflection" title="Permalink to this headline">¶</a></h2> <p>In addition to the syntax-level introspection utilized in metaprogramming, Julia provides several other runtime reflection capabilities.</p> <p><strong>Type fields</strong> The names of data type fields (or module members) may be interrogated using the <tt class="docutils literal"><span class="pre">names</span></tt> function. For example, given the following type:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="k">type</span><span class="nc"> Point</span> <span class="n">x</span><span class="p">::</span><span class="n">FloatingPoint</span> <span class="n">y</span> <span class="k">end</span> </pre></div> </div> <p><tt class="docutils literal"><span class="pre">names(Point)</span></tt> will return the array <tt class="docutils literal"><span class="pre">Any[:x,</span> <span class="pre">:y]</span></tt>. The type of each field in a <tt class="docutils literal"><span class="pre">Point</span></tt> is stored in the <tt class="docutils literal"><span class="pre">types</span></tt> field of the Point object:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="nb">typeof</span><span class="p">(</span><span class="n">Point</span><span class="p">)</span> <span class="n">DataType</span> <span class="n">julia</span><span class="o">></span> <span class="n">Point</span><span class="o">.</span><span class="n">types</span> <span class="p">(</span><span class="n">FloatingPoint</span><span class="p">,</span><span class="kt">Any</span><span class="p">)</span> </pre></div> </div> <p><strong>Subtypes</strong> The <em>direct</em> subtypes of any DataType may be listed using <tt class="docutils literal"><span class="pre">subtypes(t::DataType)</span></tt>. For example, the abstract DataType <tt class="docutils literal"><span class="pre">FloatingPoint</span></tt> has four (concrete) subtypes:</p> <div class="highlight-julia"><div class="highlight"><pre><span class="n">julia</span><span class="o">></span> <span class="n">subtypes</span><span class="p">(</span><span class="n">FloatingPoint</span><span class="p">)</span> <span class="mi">4</span><span class="o">-</span><span class="n">element</span> <span class="n">Array</span><span class="p">{</span><span class="kt">Any</span><span class="p">,</span><span class="mi">1</span><span class="p">}:</span> <span class="n">BigFloat</span> <span class="n">Float16</span> <span class="kt">Float32</span> <span class="kt">Float64</span> </pre></div> </div> <p>Any abstract subtype will also be included in this list, but further subtypes thereof will not; recursive applications of <tt class="docutils literal"><span class="pre">subtypes</span></tt> allow to build the full type tree.</p> <p><strong>Type internals</strong> The internal representation of types is critically important when interfacing with C code. <tt class="docutils literal"><span class="pre">isbits(T::DataType)</span></tt> returns true if <cite>T</cite> is stored with C-compatible aligment. The offsets of each field may be listed using <tt class="docutils literal"><span class="pre">fieldoffsets(T::DataType)</span></tt>.</p> <p><strong>Function methods</strong> The methods of any function may be listed using <tt class="docutils literal"><span class="pre">methods(f::Function)</span></tt>.</p> <p><strong>Function representations</strong> Functions may be introspected at several levels of representation. The lowered form of a function is available using <tt class="docutils literal"><span class="pre">code_lowered(f::Function,</span> <span class="pre">(Args...))</span></tt>, and the type-inferred lowered form is available using <tt class="docutils literal"><span class="pre">code_typed(f::Function,</span> <span class="pre">(Args...))</span></tt>.</p> <p>Closer to the machine, the LLVM Intermediate Representation of a function is printed by <tt class="docutils literal"><span class="pre">code_llvm(f::Function,</span> <span class="pre">(Args...))</span></tt>, and finally the resulting assembly instructions (after JIT’ing step) are available using <tt class="docutils literal"><span class="pre">code_native(f::Function,</span> <span class="pre">(Args...)</span></tt>.</p> </div> </div> </div> <footer> <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation"> <a href="arrays.html" class="btn btn-neutral float-right" title="Multi-dimensional Arrays"/>Next <span class="fa fa-arrow-circle-right"></span></a> <a href="modules.html" class="btn btn-neutral" title="Modules"><span class="fa fa-arrow-circle-left"></span> Previous</a> </div> <hr/> <div role="contentinfo"> <p> </p> </div> <a href="https://github.com/snide/sphinx_rtd_theme">Sphinx theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a> </footer> </div> </div> </section> </div> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT:'../', VERSION:'0.3.4', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="../_static/js/theme.js"></script> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.StickyNav.enable(); }); </script> </body> </html>