Chapter 9. Metaprogramming


This chapter covers

  • Understanding metaprogramming and its uses
  • Using generics to remove code duplication
  • Constructing a Nim abstract syntax tree
  • Executing code at compile time
  • Using templates and macros

This chapter describes one of the most advanced and most powerful features in the Nim programming language: metaprogramming, composed of a number of components including generics, templates, and macros.

Metaprogramming is a feature of Nim that gives you the ability to treat your application’s source code as data. This means you can write code that reads, generates, analyses, and modifies other code. Being able to perform such activities brings many advantages, including allowing you to minimize the number of lines of code needed to express a solution. In turn, this means that metaprogramming reduces development time.

Generating code is usually easy enough in most languages, but reading, analyzing, and modifying it isn’t. Consider the following simple type definition:

  Person = object
    name: string
    age: int

Analyzing this code to retrieve information about the Person type isn’t easy in a language without metaprogramming. For instance, in Java, you could do it via reflection at runtime. In other languages, you could attempt to treat the type definition as a string and parse it, but doing so would be very error prone. In Nim, there are facilities that allow you to analyze type definitions at compile time.

9.1. Generics

9.2. Templates

9.3. Macros

9.4. Creating a configuration DSL

9.5. Summary