Meta Programming
   HOME

TheInfoList



OR:

Metaprogramming is a programming technique in which computer programs have the ability to treat other programs as their data. It means that a program can be designed to read, generate, analyze or transform other programs, and even modify itself while running. In some cases, this allows programmers to minimize the number of lines of code to express a solution, in turn reducing development time. It also allows programs a greater flexibility to efficiently handle new situations without recompilation. Metaprogramming can be used to move computations from run-time to compile-time, to generate code using compile time computations, and to enable self-modifying code. The ability of a programming language to be its own metalanguage is called reflection. Reflection is a valuable language feature to facilitate metaprogramming. Metaprogramming was popular in the 1970s and 1980s using list processing languages such as
LISP A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
. LISP hardware machines were popular in the 1980s and enabled applications that could process code. They were frequently used for artificial intelligence applications.


Approaches

Metaprogramming enables developers to write programs and develop code that falls under the generic programming paradigm. Having the programming language itself as a first-class data type (as in
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
, Prolog, SNOBOL, or Rebol) is also very useful; this is known as '' homoiconicity''. Generic programming invokes a metaprogramming facility within a language by allowing one to write code without the concern of specifying data types since they can be supplied as parameters when used. Metaprogramming usually works in one of three ways. # The first approach is to expose the internals of the run-time engine to the programming code through
application programming interface An application programming interface (API) is a way for two or more computer programs to communicate with each other. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how t ...
s (APIs) like that for the .NET IL emitter. # The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments or context, like JavaScript. Thus, "programs can write programs." Although both approaches can be used in the same language, most languages tend to lean toward one or the other. # The third approach is to step outside the language entirely. General purpose program transformation systems such as compilers, which accept language descriptions and carry out arbitrary transformations on those languages, are direct implementations of general metaprogramming. This allows metaprogramming to be applied to virtually any target language without regard to whether that target language has any metaprogramming abilities of its own. One can see this at work with
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
and how it allows tackling some limitations faced in C by using constructs that were part of the Scheme language itself to extend C.
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
is probably the quintessential language with metaprogramming facilities, both because of its historical precedence and because of the simplicity and power of its metaprogramming. In Lisp metaprogramming, the unquote operator (typically a comma) introduces code that is evaluated at program definition time rather than at run time; see Self-evaluating forms and quoting in Lisp. The metaprogramming language is thus identical to the host programming language, and existing Lisp routines can be directly reused for metaprogramming, if desired. This approach has been implemented in other languages by incorporating an interpreter in the program, which works directly with the program's data. There are implementations of this kind for some common high-level languages, such as
RemObjects RemObjects Software is an American software company founded in 2002 by Alessandro Federici and Marc Hoffman. It develops and offers tools and libraries for software developers on a variety of development platforms, including Embarcadero Delphi, Mi ...
Pascal Script Pascal Script is a scripting language based on the programming language Pascal that facilitates automated runtime control over scriptable applications and server software. It is implemented by a free scripting engine that includes a compiler and a ...
for Object Pascal.


Usages


Code generation

A simple example of a metaprogram is this
POSIX Shell A Unix shell is a command-line interpreter or shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command language and a scripting language, and is used by the operating system to ...
script Script may refer to: Writing systems * Script, a distinctive writing system, based on a repertoire of specific elements or symbols, or that repertoire * Script (styles of handwriting) ** Script typeface, a typeface with characteristics of handw ...
, which is an example of generative programming: #!/bin/sh # metaprogram echo '#!/bin/sh' > program for i in $(seq 992) do echo "echo $i" >> program done chmod +x program This script (or program) generates a new 993-line program that prints out the numbers 1–992. This is only an illustration of how to use code to write more code; it is not the most efficient way to print out a list of numbers. Nonetheless, a programmer can write and execute this metaprogram in less than a minute, and will have generated over 1000 lines of code in that amount of time. A quine is a special kind of metaprogram that produces its own source code as its output. Quines are generally of recreational or theoretical interest only. Not all metaprogramming involves generative programming. If programs are modifiable at runtime or if incremental compilation is available (such as in C#,
Forth Forth or FORTH may refer to: Arts and entertainment * ''forth'' magazine, an Internet magazine * ''Forth'' (album), by The Verve, 2008 * ''Forth'', a 2011 album by Proto-Kaw * Radio Forth, a group of independent local radio stations in Scotla ...
, Frink, Groovy, JavaScript,
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
, Elixir,
Lua Lua or LUA may refer to: Science and technology * Lua (programming language) * Latvia University of Agriculture * Last universal ancestor, in evolution Ethnicity and language * Lua people, of Laos * Lawa people, of Thailand sometimes referred t ...
,
Nim Nim is a mathematical two player game. Nim or NIM may also refer to: * Nim (programming language) * Nim Chimpsky, a signing chimpanzee Acronyms * Network Installation Manager, an IBM framework * Nuclear Instrumentation Module * Negative index met ...
, Perl, PHP, Python, REBOL, Ruby, Rust,
SAS SAS or Sas may refer to: Arts, entertainment, and media * ''SAS'' (novel series), a French book series by Gérard de Villiers * ''Shimmer and Shine'', an American animated children's television series * Southern All Stars, a Japanese rock ba ...
,
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
, and
Tcl TCL or Tcl or TCLs may refer to: Business * TCL Technology, a Chinese consumer electronics and appliance company **TCL Electronics, a subsidiary of TCL Technology * Texas Collegiate League, a collegiate baseball league * Trade Centre Limited, a ...
), then techniques can be used to perform metaprogramming without actually generating source code. One style of generative approach is to employ
domain-specific language A domain-specific language (DSL) is a computer language specialized to a particular application domain. This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains. There are a wide variety of DSLs, ranging f ...
s (DSLs). A fairly common example of using DSLs involves generative metaprogramming: lex and yacc, two tools used to generate
lexical analyzer In computer science, lexical analysis, lexing or tokenization is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of ''lexical tokens'' ( strings with an assigned and thus identified ...
s and parsers, let the user describe the language using regular expressions and
context-free grammar In formal language theory, a context-free grammar (CFG) is a formal grammar whose production rules are of the form :A\ \to\ \alpha with A a ''single'' nonterminal symbol, and \alpha a string of terminals and/or nonterminals (\alpha can be empt ...
s, and embed the complex algorithms required to efficiently parse the language.


Code instrumentation

One usage of metaprogramming is to instrument programs in order to do dynamic program analysis.


Behavioral changes

Metaprogramming can be used to weave behavioral changes in a program, as done in aspect-oriented programming. For instance, metaprogramming can be used to inject
feature flag A feature toggle in software development provides an alternative to maintaining multiple feature branches in source code. A condition within the code enables or disables a feature during runtime. In agile settings the toggle is used in product ...
s or to explore possible patches for fixing bugs.


Challenges

Some argue that there is a sharp learning curve to make complete use of metaprogramming features. Since metaprogramming gives more flexibility and configurability at runtime, misuse or incorrect use of the metaprogramming can result in unwarranted and unexpected errors that can be extremely difficult to debug to an average developer. It can introduce risks in the system and make it more vulnerable if not used with care. Some of the common problems which can occur due to wrong use of metaprogramming are inability of the compiler to identify missing configuration parameters, invalid or incorrect data can result in unknown exception or different results. Due to this, some believe that only high-skilled developers should work on developing features which exercise metaprogramming in a language or platform and average developers must learn how to use these features as part of convention.


Uses in programming languages


Macro systems

*
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
and most
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
dialects. * Scheme hygienic macros *
MacroML MacroML is an experimental programming language based on the ML family, seeking to reconcile ML's static typing and the types of macro systems commonly found in dynamically typed languages like Scheme; this reconciliation is difficult since Turi ...
* Racket (programming language) *
Template Haskell Template Haskell is an experimental language extension to the Haskell programming language implemented in the Glasgow Haskell Compiler (version 6 and later). In early incarnations it was also known as Template Meta-Haskell. It allows compile-tim ...
* Scala macros * Clojure macros *
Nim Nim is a mathematical two player game. Nim or NIM may also refer to: * Nim (programming language) * Nim Chimpsky, a signing chimpanzee Acronyms * Network Installation Manager, an IBM framework * Nuclear Instrumentation Module * Negative index met ...
* Rust * Haxe * Julia * Elixir


Macro assemblers

The
IBM/360 The IBM System/360 (S/360) is a family of mainframe computer systems that was announced by IBM on April 7, 1964, and delivered between 1965 and 1978. It was the first family of computers designed to cover both commercial and scientific applica ...
and derivatives had powerful
macro assembler Macro (or MACRO) may refer to: Science and technology * Macroscopic, subjects visible to the eye * Macro photography, a type of close-up photography * Image macro, a picture with text superimposed * Monopole, Astrophysics and Cosmic Ray Observato ...
facilities that were often used to generate complete
assembly language In computer programming, assembly language (or assembler language, or symbolic machine code), often referred to simply as Assembly and commonly abbreviated as ASM or asm, is any low-level programming language with a very strong correspondence be ...
programs or sections of programs (for different operating systems for instance). Macros provided with CICS transaction processing system had assembler macros that generated
COBOL COBOL (; an acronym for "common business-oriented language") is a compiled English-like computer programming language designed for business use. It is an imperative, procedural and, since 2002, object-oriented language. COBOL is primarily us ...
statements as a pre-processing step. Other assemblers, such as
MASM The Microsoft Macro Assembler (MASM) is an x86 assembler that uses the Intel syntax for MS-DOS and Microsoft Windows. Beginning with MASM 8.0, there are two versions of the assembler: One for 16-bit & 32-bit assembly sources, and another (ML64) ...
, also support macros.


Metaclasses

Metaclasses are provided by the following programming languages: *
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
* Python * Nil * Groovy * Ruby *
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
*
Lua Lua or LUA may refer to: Science and technology * Lua (programming language) * Latvia University of Agriculture * Last universal ancestor, in evolution Ethnicity and language * Lua people, of Laos * Lawa people, of Thailand sometimes referred t ...


Template metaprogramming

* C "X Macros" * C++ Templates * D *
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
,
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
and most Lisp dialects by using the quasiquote ("backquote") operator. *
Nim Nim is a mathematical two player game. Nim or NIM may also refer to: * Nim (programming language) * Nim Chimpsky, a signing chimpanzee Acronyms * Network Installation Manager, an IBM framework * Nuclear Instrumentation Module * Negative index met ...


Staged metaprogramming

* MetaML * MetaOCaml * Scalabr>natively
or using the Lightweight Modular Staging Framework
Terra


Dependent types

Usage of dependent types allows proving that generated code is never invalid. However, this approach is bleeding-edge and is rarely found outside of research programming languages.


Implementations

The list of notable metaprogramming systems is maintained at List of Program Transformation Systems.


See also

* Aspect weaver *
Comparison of code generation tools List of tools Technical features References {{DEFAULTSORT:Code Generation Tools, Comparison Of Programming tools Code generation tools Source code generation ...
*
Compile-time function execution In computing, compile-time function execution (or compile time function evaluation, or general constant expressions) is the ability of a compiler, that would normally compile a function to machine code and execute it at run time, to execute the fu ...
*
Compile-time reflection In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior. Historical background The earliest computers were programmed in their native assembly lan ...
* Genetic programming * Homoiconicity *
Inferential programming In ordinary computer programming, the programmer keeps the program's intended results in mind and painstakingly constructs a computer program to achieve those results. Inferential programming refers to (still mostly hypothetical) techniques and tec ...
* Instruction set simulator * Intentional Programming * Interpreted language * Machine learning *
Metacompiler In computer science, a compiler-compiler or compiler generator is a programming tool that creates a parser, interpreter, or compiler from some form of formal description of a programming language and machine. The most common type of compiler- ...
* Metaobject *
Partial evaluation In computing, partial evaluation is a technique for several different types of program optimization by specialization. The most straightforward application is to produce new programs that run faster than the originals while being guaranteed to ...
* Reflection (computer programming) * Self-interpreter * Self-modifying code *
Source code generation In computer science, the term automatic programming identifies a type of computer programming in which some mechanism generates a computer program to allow human programmers to write the code at a higher abstraction level. There has been little ...
*
Transcompiler A source-to-source translator, source-to-source compiler (S2S compiler), transcompiler, or transpiler is a type of translator that takes the source code of a program written in a programming language as its input and produces an equivalent so ...
(also known as transpilation) * Very Large Scale Integration


References


External links


c2.com Wiki: Metaprogramming articleMeta Programming
on the Program Transformation Wiki
Code generation Vs Metaprogramming"Solenoid"
The first metaprogramming framework fo
eXist-db
{{Types of programming languages Programming paradigms