Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Metaprogramming

From Wikipedia, the free encyclopedia
Programming paradigm
This article is about the computer programming technique. For the management technique, seeCharles Simonyi.
This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages)
icon
This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Metaprogramming" – news ·newspapers ·books ·scholar ·JSTOR
(August 2011) (Learn how and when to remove this message)
This article'stone or style may not reflect theencyclopedic tone used on Wikipedia. See Wikipedia'sguide to writing better articles for suggestions.(February 2017) (Learn how and when to remove this message)
(Learn how and when to remove this message)

Metaprogramming is acomputer programming technique in whichcomputer programs have the ability to treat other programs as theirdata. It means that a program can be designed to read, generate, analyse, or transform other programs, and even modify itself, while running.[1][2] In some cases, this allows programmers to minimize the number of lines of code to express a solution, in turn reducing development time.[3] It also allows programs more flexibility to efficiently handle new situations with no recompiling.

Metaprogramming can be used to move computations fromruntime tocompile time, to generate code usingcompile time computations, and to enableself-modifying code. The ability of aprogramming language to be its ownmetalanguage allowsreflective programming, and is termedreflection.[4] Reflection is a valuable language feature to facilitate metaprogramming.

Metaprogramming was popular in the 1970s and 1980s using list processing languages such asLisp.Lisp machine hardware gained some notice in the 1980s, and enabled applications that could process code. They were often used forartificial intelligence applications.

Approaches

[edit]

Metaprogramming enables developers to write programs and develop code that falls under thegeneric programmingparadigm. Having the programming language itself as afirst-class data type (as inLisp,Prolog,SNOBOL, orRebol) is also very useful; this is known ashomoiconicity.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 asparameters when used.

Metaprogramming usually works in one of three ways.[5]

  1. The first approach is to expose the internals of theruntime system (engine) to the programming code throughapplication programming interfaces (APIs) like that for the.NETCommon Intermediate Language (CIL) emitter.
  2. The second approach isdynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments or context, likeJavaScript.[6] 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.
  3. The third approach is to step outside the language entirely. General purposeprogram transformation systems such ascompilers, 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 withScheme and how it allows tackling some limits faced inC by using constructs that are part of the Scheme language to extend C.[7]

Lisp 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 isevaluated at program definition time rather than at run time. 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 asRemObjectsPascal Script forObject Pascal.

Usages

[edit]

Code generation

[edit]

A simple example of a metaprogram is thisPOSIX Shellscript, which is an example ofgenerative programming:

#!/bin/sh# metaprogramecho'#!/bin/sh'>programforiin$(seq992)doecho"echo$i">>programdonechmod+xprogram

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.

Aquine 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 compiling is available (such as inC#,Forth,Frink,Groovy,JavaScript,Lisp,Elixir,Lua,Nim,Perl,PHP,Python,Rebol,Ruby,Rust,R,SAS,Smalltalk, andTcl), then techniques can be used to perform metaprogramming without generating source code.

One style of generative approach is to employdomain-specific languages (DSLs). A fairly common example of using DSLs involves generative metaprogramming:lex andyacc, two tools used to generatelexical analysers andparsers, let the user describe the language usingregular expressions andcontext-free grammars, and embed the complex algorithms required to efficiently parse the language.

Code instrumentation

[edit]

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

Challenges

[edit]

Some argue that there is a sharp learning curve to make complete use of metaprogramming features.[8] Since metaprogramming gives more flexibility and configurability at runtime, misuse or incorrect use of 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.[9] Due to this, some believe[8] 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

[edit]

Macro systems

[edit]
Main article:Macro (computer science)

Macro assemblers

[edit]
Main article:Macro assembler

TheIBM/360 and derivatives had powerfulmacro assembler facilities that were often used to generate completeassembly language programs[citation needed] or sections of programs (for different operating systems for instance). Macros provided withCICStransaction processing system had assembler macros that generatedCOBOL statements as a pre-processing step.

Other assemblers, such asMASM, also support macros.

Metaclasses

[edit]
Main article:Metaclass

Metaclasses are provided by the following programming languages:

Template metaprogramming

[edit]
Main article:Template metaprogramming

Staged metaprogramming

[edit]
Main article:Multi-stage programming

Dependent types

[edit]
Main article:Dependent type

Use ofdependent types allows proving that generated code is never invalid.[15] However, this approach is leading-edge and rarely found outside of research programming languages.

Implementations

[edit]

The list of notable metaprogramming systems is maintained atList of program transformation systems.

See also

[edit]

References

[edit]
  1. ^Sondergaard, Harald (2013)."Course on Program Analysis and Transformation". Retrieved18 September 2014.
  2. ^Czarnecki, Krzysztof; Eisenecker, Ulrich W. (2000).Generative Programming. Addison Wesley.ISBN 0-201-30977-7.
  3. ^Walker, Max."The Art of Metaprogrmming in Java".New Circle. Retrieved28 January 2014.
  4. ^Krauss, Aaron."Programming Concepts: Type Introspection and Reflection". Archived fromthe original on 10 March 2016. Retrieved10 March 2016.
  5. ^Joshi, Prateek (5 April 2014)."What Is Metaprogramming? – Part 2/2".Perpetual Enigma. Retrieved14 August 2014.
  6. ^for example, instance_eval inRuby takes a string or an anonymous function."Class BasicObject Ruby 3.5".
  7. ^"Art of Metaprogramming".IBM.
  8. ^abBicking, Ian."The challenge of metaprogramming".IanBicking.org. Retrieved21 September 2016.
  9. ^Terry, Matt (21 August 2013)."Beware of Metaprogramming".Medium.com. Medium Corporation. Retrieved21 August 2014.
  10. ^ThroughCommon Lisp Object System's "Meta Object Protocol"
  11. ^"C++ Template Metaprogramming".aszt.inf.elte.hu. Retrieved2022-07-23.
  12. ^Lisp (programming language) "Self-evaluating forms and quoting", quasi-quote operator.
  13. ^"LMS: Program Generation and Embedded Compilers in Scala".scala-lms.github.io. Retrieved2017-12-06.
  14. ^Rompf, Tiark; Odersky, Martin (June 2012)."Lightweight Modular Staging: A Pragmatic Approach to Runtime Code Generation and Compiled DSLs".Communications of the ACM.55 (6):121–130.doi:10.1145/2184319.2184345.ISSN 0001-0782.S2CID 52898203.
  15. ^Chlipala, Adam (June 2010)."Ur: statically-typed metaprogramming with type-level record computation"(PDF).ACM SIGPLAN Notices. PLDI '10.45 (6):122–133.doi:10.1145/1809028.1806612. Retrieved29 August 2012.

External links

[edit]
Imperative
Structured
Object-oriented
Declarative
Functional
Dataflow
Logic
Domain-
specific
language

(DSL)
Concurrent,
parallel
Metaprogramming
Separation
of concerns
Comparisons/Lists
Level
Generation
Retrieved from "https://en.wikipedia.org/w/index.php?title=Metaprogramming&oldid=1335302027"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp