HOME

TheInfoList




A macro (short for "macro instruction", from
Greek#REDIRECT Greek Greek may refer to: Greece Anything of, from, or related to Greece Greece ( el, Ελλάδα, , ), officially the Hellenic Republic, is a country located in Southeast Europe. Its population is approximately 10.7 million as of ...
combining form "long, large") in
computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of computation, automation, a ...
is a rule or
pattern A pattern is a regularity in the world, in human-made design, or in abstract ideas. As such, the elements of a pattern repeat in a predictable manner. A geometric pattern is a kind of pattern formed of geometric Geometry (from the grc, ...

pattern
that specifies how a certain input should be mapped to a replacement output. Applying a macro to an input is ''macro expansion''. The input and output may be a sequence of
lexical token In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algor ...
s or
characters Character(s) may refer to: Arts, entertainment, and media Literature * Character (novel), ''Character'' (novel), a 1936 Dutch novel by Ferdinand Bordewijk * Characters (Theophrastus), ''Characters'' (Theophrastus), a classical Greek set of char ...
, or a
syntax treeSyntax tree may refer to: * Abstract syntax tree, used in computer science * Concrete syntax tree, used in linguistics {{dabconcept ...
. Character macros are supported in
software application Application software (app for short) is computing software designed to carry out a specific task other than one relating to the operation of the computer itself, typically to be used by end-users. Examples of an application Application may refer ...
s to make it easy to invoke common command sequences. Token and tree macros are supported in some
programming language A programming language is a formal language In logic, mathematics, computer science, and linguistics, a formal language consists of string (computer science), words whose symbol (formal), letters are taken from an alphabet (computer science) ...

programming language
s to enable
code reuse Code reuse, also called software reuse, is the use of existing software Software is a collection of instructions that tell a computer A computer is a machine that can be programmed to carry out sequences of arithmetic or logical operati ...
or to extend the language, sometimes for
domain-specific languagesA domain-specific language (DSL) is a computer languageA computer language is a method of communication with a computer A computer is a machine that can be programmed to carry out sequences of arithmetic or logical operations automatically. M ...
. Macros are used to make a sequence of computing instructions available to the
programmer A computer programmer, sometimes called a software developer, a programmer or more recently a coder (especially in more informal contexts), is a person who creates computer software Software is a collection of Instruction (computer science) ...
as a single program statement, making the programming task less tedious and less error-prone. (Thus, they are called "macros" because a "big" block of code can be expanded from a "small" sequence of characters.) Macros often allow positional or keyword parameters that dictate what the conditional assembler program generates and have been used to create entire programs or program suites according to such variables as
operating system An operating system (OS) is system software System software is software designed to provide a platform for other software. Examples of system software include operating systems (OS) like macOS, Linux, Android (operating system), Android and Mi ...

operating system
,
platform Platform may refer to: Technology * Computing platform, a framework on which applications may be run * Platform game, a genre of video games * Car platform, a set of components shared by several vehicle models * Weapons platform, a system or s ...
or other factors. The term derives from "macro instruction", and such expansions were originally used in generating
assembly language In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task. Programming involves tasks such as analysis, gene ...
code.


Keyboard and mouse macros

Keyboard macros and mouse macros allow short sequences of keystrokes and mouse actions to transform into other, usually more time-consuming, sequences of keystrokes and mouse actions. In this way, frequently used or repetitive sequences of keystrokes and mouse movements can be
automate Automation describes a wide range of technologies that reduce human intervention in processes. Human intervention is reduced by predetermining decision criteria, subprocess relationships, and related actions — and embodying those predetermi ...

automate
d. Separate programs for creating these macros are called
macro recorder A macro recorder is software Software is a collection of instructions that tell a computer A computer is a machine that can be programmed to carry out sequences of arithmetic or logical operations automatically. Modern computers can pe ...
s. During the 1980s, macro programs – originally
SmartKey SmartKey was the first macro processing program of its type, and the first TSR or ''terminate and stay resident'' program for PCs and CP/M microcomputer A microcomputer is a small, relatively inexpensive computer A computer is a machin ...
, then SuperKey, KeyWorks, Prokey – were very popular, first as a means to automatically format
screenplay A screenplay, or script, is a written work by screenwriter A screenplay writer (also called screenwriter for short), scriptwriter or scenarist, is a writer A writer is a person who uses written words in different styles and technique ...
s, then for a variety of user input tasks. These programs were based on the TSR (
terminate and stay resident A terminate-and-stay-resident program (commonly TSR) is a computer program A computer program is a collection of instructions that can be executed by a computer to perform a specific task. A computer program is usually written by a computer ...
) mode of operation and applied to all keyboard input, no matter in which context it occurred. They have to some extent fallen into obsolescence following the advent of mouse-driven user interfaces and the availability of keyboard and mouse macros in applications such as
word processor A word processor (WP) is a device or computer program that provides for input, editing, formatting, and output of text, often with some additional features. Early word processors were stand-alone devices dedicated to the function, but current ...
s and
spreadsheet A spreadsheet is a computer application for organization, analysis, and storage of data in table (information), tabular form. Spreadsheets were developed as computerized analogs of paper accounting Worksheet#Accounting, worksheets. The program op ...

spreadsheet
s, making it possible to create application-sensitive keyboard macros. Keyboard macros can be used in
massively multiplayer online role-playing game A massively multiplayer online role-playing game (MMORPG) is a video game#REDIRECT Video game A video game is an electronic game that involves interaction with a user interface or input device such as a joystick, game controller, controller, ...
s (MMORPGs) to perform repetitive, but lucrative tasks, thus accumulating resources. As this is done without human effort, it can skew the economy of the game. For this reason, use of macros is a violation of the TOS or
EULA An end-user license agreement (EULA, ) is a legal contract entered into between a software developer A computer programmer, sometimes called a software developer, a programmer or more recently a coder (especially in more informal contexts), is ...
of most MMORPGs, and their administrators spend considerable effort to suppress them.


Application macros and scripting

Keyboard and mouse macros that are created using an application's built-in macro features are sometimes called application macros. They are created by carrying out the sequence once and letting the application record the actions. An underlying macro programming language, most commonly a
scripting language A scripting language or script language is a programming language A programming language is a formal language In mathematics Mathematics (from Ancient Greek, Greek: ) includes the study of such topics as quantity (number theory), mathe ...
, with direct access to the features of the application may also exist. The programmers' text editor,
Emacs Emacs or EMACS (Editor MACroS) is a family of text editor A text editor is a type of computer program that edits plain text. Such programs are sometimes known as "notepad" software, following the naming of Microsoft Notepad. Text editors a ...

Emacs
, (short for "editing macros") follows this idea to a conclusion. In effect, most of the editor is made of macros. Emacs was originally devised as a set of macros in the editing language TECO; it was later ported to dialects of
Lisp Lisp (historically LISP) is a family of programming language A programming language is a formal language In logic, mathematics, computer science, and linguistics, a formal language consists of string (computer science), words whose symbo ...
. Another programmers' text editor,
Vim Vim means enthusiasm and vigor. It may also refer to: * Vim (cleaning product) * Vim Comedy Company, a movie studio * Vim Records * Vimentin, a protein * "Vim", a song by Machine Head on the album ''Through the Ashes of Empires'' * Vim (text editor ...
(a descendant of
vi
vi
), also has an implementation of keyboard macros. It can record into a register (macro) what a person types on the keyboard and it can be replayed or edited just like VBA macros for Microsoft Office. Vim also has a scripting language called Vimscript to create macros.
Visual Basic for Applications Visual Basic for Applications (VBA) is an implementation of Microsoft Microsoft Corporation is an American multinational corporation, multinational technology company with headquarters in Redmond, Washington. It develops, manufactures, licens ...
(VBA) is a programming language included in
Microsoft Office Microsoft Office, or simply Office, is a family of client software In computing, a client is a piece of computer hardware or software that accesses a service made available by a Server (computing), server as part of the client–server mo ...
from Office 97 through Office 2019 (although it was available in some components of Office prior to Office 97). However, its function has evolved from and replaced the macro languages that were originally included in some of these applications.
XEDIT XEDIT is a visual editor A visual editor, or full-screen editor is computer software Software is a collection of Instruction (computer science), instructions that tell a computer how to work. This is in contrast to Computer hardware, hardw ...
, running on the
Conversational Monitor System The Conversational Monitor System (CMS – originally: "Cambridge Monitor System") is a simple interactiveAcross the many fields concerned with interactivity, including information science, computer science, human-computer interaction, communic ...
(CMS) component of VM, supports macros written in EXEC, EXEC2 and
REXX Rexx (Restructured Extended Executor) is a programming language that can be interpreted or compiled In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (t ...
, and some CMS commands were actually wrappers around XEDIT macros.
The Hessling Editor XEDIT is a visual editor for VM (operating system), VM/CMS using block-oriented terminal, block mode IBM 3270 Computer terminal, terminals. (Line-mode terminals are also supported.) XEDIT is much more line-oriented than modern Personal computer, ...

The Hessling Editor
(THE), a partial clone of XEDIT, supports Rexx macros using Regina and Open
Object REXX The Object REXX programming language is an object-oriented programming language, object-oriented scripting programming language, scripting language initially produced by IBM for the operating system OS/2 and later for Microsoft Windows. It is a fol ...
(oorexx). Many common applications, and some on PCs, use Rexx as a scripting language.


Macro virus

VBA has access to most Microsoft Windows system calls and executes when documents are opened. This makes it relatively easy to write
computer virus A computer virus is a type of computer program that, when executed, replicates itself by modifying other computer programs and Code injection, inserting its own Computer language, code. If this replication succeeds, the affected areas are then ...

computer virus
es in VBA, commonly known as
macro virus In computing terminology, a macro virus is a computer virus, virus that is written in a Macro (computer science), macro programming language, language: a programming language which is embedded inside a software application (e.g., word processors a ...
es. In the mid-to-late 1990s, this became one of the most common types of computer virus. However, during the late 1990s and to date,
Microsoft Microsoft Corporation is an American multinational corporation, multinational technology company, technology corporation which produces Software, computer software, consumer electronics, personal computers, and related services. Its best-know ...

Microsoft
has been patching and updating their programs. In addition, current anti-virus programs immediately counteract such attacks.


Parameterized macro

A parameterized macro is a macro that is able to insert given objects into its expansion. This gives the macro some of the power of a
function Function or functionality may refer to: Computing * Function key A function key is a key on a computer A computer is a machine that can be programmed to carry out sequences of arithmetic or logical operations automatically. Modern comp ...
. As a simple example, in the
C programming language C (, as in the letter ''c'') is a general-purpose, procedural computer programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce various kinds of Input/outp ...
, this is a typical macro that is ''not'' a parameterized macro: #define PI 3.14159 This causes PI to always be replaced with 3.14159 wherever it occurs. An example of a parameterized macro, on the other hand, is this: #define pred(x) ((x)-1) What this macro expands to depends on what
argument In logic Logic is an interdisciplinary field which studies truth and reasoning Reason is the capacity of consciously making sense of things, applying logic Logic (from Ancient Greek, Greek: grc, wikt:λογική, λογική, lab ...
''x'' is passed to it. Here are some possible expansions: pred(2) → ((2) -1) pred(y+2) → ((y+2) -1) pred(f(5)) → ((f(5))-1) Parameterized macros are a useful source-level mechanism for performing in-line expansion, but in languages such as C where they use simple textual substitution, they have a number of severe disadvantages over other mechanisms for performing in-line expansion, such as
inline function In the C and C++ C++ () is a general-purpose programming language In computer software, a general-purpose programming language is a programming language dedicated to a general-purpose, designed to be used for writing software in a wide ...
s. The parameterized macros used in languages such as
Lisp Lisp (historically LISP) is a family of programming language A programming language is a formal language In logic, mathematics, computer science, and linguistics, a formal language consists of string (computer science), words whose symbo ...
,
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a Procedural programming, procedural, imperative programming, imperative computer programming language developed and published by IBM. It is designed for scientific, engi ...
and Scheme, on the other hand, are much more powerful, able to make decisions about what code to produce based on their arguments; thus, they can effectively be used to perform run-time code generation.


Text-substitution macros

Languages such as C and some
assembly language In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task. Programming involves tasks such as analysis, gene ...
s have rudimentary macro systems, implemented as
preprocessor In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algori ...

preprocessor
s to the compiler or assembler.
C preprocessor The C preprocessor is the macro preprocessor for the C, Objective-C Objective-C is a general-purpose, object-oriented Object-oriented programming (OOP) is a programming paradigm Program, programme, programmer, or programming may re ...
macros work by simple textual substitution at the
token Token may refer to: Arts, entertainment, and media * Token, a game piece or counter, used in some games * The Tokens The Tokens were an American male doo-wop-style vocal group and record production company group from Brooklyn, New York B ...
, rather than the character level. However, the macro facilities of more sophisticated assemblers, e.g., IBM High Level Assembler (HLASM) can't be implemented with a preprocessor; the code for assembling instructions and data is interspersed with the code for assembling macro invocations. A classic use of macros is in the computer typesetting system
TeX TeX (, see below), stylized within the system as TeX, is a typesetting system which was designed and mostly written by Donald Knuth and released in 1978. TeX is a popular means of typesetting complex mathematical formulae; it has been noted ...
and its derivatives, where most of the functionality is based on macros. MacroML is an experimental system that seeks to reconcile
static typing In programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce various kinds of Input/output, output. Programming languages are used in computer programming to ...
and macro systems.
Nemerle Nemerle is a general-purpose, high-level, statically typed In programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce various kinds of Input/output, outpu ...
has typed syntax macros, and one productive way to think of these syntax macros is as a multi-stage computation. Other examples: * m4 is a sophisticated stand-alone macro processor. *
TRAC Trac is an open-source, web-based project management Project management is the process of leading the work of a team to achieve goals and meet success criteria at a specified time. The primary challenge of project management is to achieve al ...
*
Macro Extension TAL
Macro Extension TAL
, accompanying
Template Attribute Language The Template Attribute Language (TAL) is a templating language used to generate dynamic HTML and XML pages. Its main goal is to simplify the collaboration between programmers and designers. This is achieved by embedding TAL statements inside valid ...
* SMX: for web pages * ML/1 (Macro Language One) * The General Purpose Macroprocessor is a contextual pattern matching macro processor, which could be described as a combination of
regular expression A regular expression (shortened as regex or regexp; also referred to as rational expression) is a sequence of Character (computing), characters that specifies a ''search pattern matching, pattern''. Usually such patterns are used by string-se ...
s, EBNF and
AWK AWK (''awk'') is a domain-specific language A domain-specific language (DSL) is a computer languageComputer language is a formal language In logic, mathematics, computer science, and linguistics, a formal language consists of string (compute ...
* SAM76 *
troff troff (), short for "typesetter roff", is the major component of a document processing system developed by AT&T Corporation for the Unix operating system. troff and the related nroff were both developed from the original roff (computer program) ...
and
nroff nroff (short for "new roff") is a text-formatting on a composing stick on a type case. , letter founder, from the 1728 edition of ''Cyclopaedia, or an Universal Dictionary of Arts and Sciences, Cyclopaedia''. . Typesetting is the composition o ...
: for typesetting and formatting Unix manpages. *
CMS EXEC CMS EXEC, or EXEC, is an interpreted, command procedure control, computer scripting language used by the CMS EXEC Processor supplied with the IBM International Business Machines Corporation (IBM) is an American multinational technology com ...
: for command-line macros and application macros *
EXEC 2 EXEC 2 is an interpreted, command procedure control, computer scripting language A scripting language or script language is a programming language A programming language is a formal language comprising a Instruction set architecture, set of in ...
in
Conversational Monitor System The Conversational Monitor System (CMS – originally: "Cambridge Monitor System") is a simple interactiveAcross the many fields concerned with interactivity, including information science, computer science, human-computer interaction, communic ...
(CMS): for command-line macros and application macros *
CLIST #redirect CLISTCLIST (Command List) (pronounced "C-List") is a Procedural programming, procedural programming language for Time Sharing Option, TSO in MVS systems. It originated in OS/360 Release 20 and has assumed a secondary role since the availab ...
in IBM's
Time Sharing Option Time Sharing Option (TSO) is an interactive time-sharing In computing, time-sharing is the sharing of a computing resource among many users at the same time by means of multiprogramming and computer multitasking, multi-tasking.DEC Timesharing (1 ...
(TSO): for command-line macros and application macros *
REXX Rexx (Restructured Extended Executor) is a programming language that can be interpreted or compiled In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (t ...
: for command-line macros and application macros in, e.g.,
AmigaOS AmigaOS is a family of proprietary native operating system An operating system (OS) is system software System software is software designed to provide a platform for other software. Examples of system software include operating systems like ...

AmigaOS
, CMS,
OS/2 OS/2 (Operating System/2) is a series of computer operating systems, initially created by Microsoft and IBM under the leadership of IBM software designer Ed Iacobucci. As a result of a feud between the two companies over how to position OS/2 re ...
, TSO *
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 (Unicode), historical and modern scripts as organise ...
: for formatting documents * Various
shells Shell may refer to: Architecture and design * Shell (structure), a thin structure **Concrete shell, a thin shell of concrete, usually with no interior columns or exterior buttresses **Thin-shell structure, **Oil company Science Biology * Seashell ...
for, e.g.,
Linux Linux ( or ) is a family of open-source Open source is source code that is made freely available for possible modification and redistribution. Products include permission to use the source code, design documents, or content of the product ...

Linux
Some major applications have been written as text macro invoked by other applications, e.g., by
XEDIT XEDIT is a visual editor A visual editor, or full-screen editor is computer software Software is a collection of Instruction (computer science), instructions that tell a computer how to work. This is in contrast to Computer hardware, hardw ...
in CMS.


Embeddable languages

Some languages, such as
PHP PHP is a general-purpose scripting language A scripting language or script language is a programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce various k ...

PHP
, can be embedded in free-format text, or the source code of other languages. The mechanism by which the code fragments are recognised (for instance, being bracketed by and ?>) is similar to a textual macro language, but they are much more powerful, fully featured languages.


Procedural macros

Macros in the
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a Procedural programming, procedural, imperative programming, imperative computer programming language developed and published by IBM. It is designed for scientific, engi ...
language are written in a subset of PL/I itself: the compiler executes "
preprocessor In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algori ...

preprocessor
statements" at compilation time, and the output of this execution forms part of the code that is compiled. The ability to use a familiar
procedural language Procedural programming is a programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mainly with i ...
as the macro language gives power much greater than that of text substitution macros, at the expense of a larger and slower compiler. Frame technology's frame macros have their own command syntax but can also contain text in any language. Each frame is both a generic component in a hierarchy of nested subassemblies, and a procedure for integrating itself with its subassembly frames (a recursive process that resolves integration conflicts in favor of higher level subassemblies). The outputs are custom documents, typically compilable source modules. Frame technology can avoid the proliferation of similar but subtly different components, an issue that has plagued software development since the invention of macros and
subroutine In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task. Programming involves tasks such as analysis, gener ...
s. Most assembly languages have less powerful procedural macro facilities, for example allowing a block of code to be repeated N times for
loop unrolling Loop unrolling, also known as loop unwinding, is a loop transformation technique that attempts to optimize a program's execution speed at the expense of its binary Binary may refer to: Science and technology Mathematics * Binary number ...
; but these have a completely different syntax from the actual assembly language.


Syntactic macros

Macro systems—such as the C preprocessor described earlier—that work at the level of lexical tokens cannot preserve the lexical structure reliably. Syntactic macro systems work instead at the level of
abstract syntax tree In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algor ...
s, and preserve the lexical structure of the original program. The most widely used implementations of syntactic macro systems are found in
Lisp Lisp (historically LISP) is a family of programming language A programming language is a formal language In logic, mathematics, computer science, and linguistics, a formal language consists of string (computer science), words whose symbo ...
-like languages. These languages are especially suited for this style of macro due to their uniform, parenthesized syntax (known as
S-expression In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task. Programming involves tasks such as analysis, gener ...
s). In particular, uniform syntax makes it easier to determine the invocations of macros. Lisp macros transform the program structure itself, with the full language available to express such transformations. While syntactic macros are often found in Lisp-like languages, they are also available in other languages such as
Prolog Prolog is a logic programming Logic programming is a programming paradigm which is largely based on formal logic. Any program written in a logic programming language is a set of sentences in logical form, expressing facts and rules about some ...

Prolog
, Erlang, Dylan, Scala,
Nemerle Nemerle is a general-purpose, high-level, statically typed In programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce various kinds of Input/output, outpu ...
,
Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous ferric oxides, hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxi ...
,
Elixir An elixir is a sweet liquid used for medical purposes, to be taken orally and intended to cure one's illness. When used as a pharmaceutical preparation, an elixir contains at least one active ingredient An active ingredient is the ingredient ...
,
Nim Nim is a mathematical game, mathematical game of strategy in which two players take turns removing (or "nimming") objects from distinct heaps or piles. On each turn, a player must remove at least one object, and may remove any number of objects ...
,
Haxe Haxe is an open source high-level cross-platform programming language and compiler that can produce applications and source code, for many different computing platforms from one code-base. It is free and open-source software, released under the M ...
, and
Julia Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio (given name), Julio and Julius. (For further details on etymology, see wikt:Iulius#Latin, Wiktionary entry “Julius”.) The given name ''Julia'' had been ...
. They are also available as third-party extensions to
JavaScript JavaScript (), often abbreviated JS, is a programming language A programming language is a formal language In mathematics Mathematics (from Ancient Greek, Greek: ) includes the study of such topics as quantity (number theory), ma ...

JavaScript
, C# and
Python Python may refer to: * Pythonidae The Pythonidae, commonly known as pythons, are a family of nonvenomous snakes found in Africa, Asia, and Australia. Among its members are some of the largest snakes in the world. Ten genera and 42 species ...
.


Early Lisp macros

Before Lisp had macros, it had so-called FEXPRs, function-like operators whose inputs were not the values computed by the arguments but rather the syntactic forms of the arguments, and whose output were values to be used in the computation. In other words, FEXPRs were implemented at the same level as EVAL, and provided a window into the meta-evaluation layer. This was generally found to be a difficult model to reason about effectively. In 1963, Timothy Hart proposed adding macros to Lisp 1.5 in
AI Memo The AI Memos are a series of influential memorandum A memorandum (abbrev.: memo; from the Latin Latin (, or , ) is a classical language belonging to the Italic languages, Italic branch of the Indo-European languages. Latin was originally s ...
57: MACRO Definitions for LISP.


Anaphoric macros

An anaphoric macro is a type of programming macro that deliberately captures some form supplied to the macro which may be referred to by an anaphor (an expression referring to another). Anaphoric macros first appeared in Paul Graham's On Lisp and their name is a reference to linguistic anaphora—the use of words as a substitute for preceding words.


Hygienic macros

In the mid-eighties, a number of papers introduced the notion of
hygienic macro Hygienic macros are Macro (computer science), macros whose expansion is guaranteed not to cause the accidental #The_hygiene_problem, capture of identifiers. They are a feature of programming languages such as Scheme (programming language), Scheme, D ...
expansion (syntax-rules), a pattern-based system where the syntactic environments of the macro definition and the macro use are distinct, allowing macro definers and users not to worry about inadvertent variable capture (cf.
referential transparency Referential transparency and referential opacity are properties of parts of computer program A computer program is a collection of instructions that can be executed by a computer to perform a specific task. A computer program is usually wri ...
). Hygienic macros have been standardized for Scheme in the R5RS,
R6RS Scheme is a minimalist In visual arts The visual arts are art forms such as painting, drawing, printmaking, sculpture Sculpture is the branch of the visual arts that operates in three dimensions. It is one of the plastic arts. D ...
, and R7RS standards. A number of competing implementations of hygienic macros exist such as syntax-rules, syntax-case, explicit renaming, and syntactic closures. Both syntax-rules and syntax-case have been standardized in the Scheme standards. Recently, Racket (programming language), Racket has combined the notions of hygienic macros with a "tower of evaluators", so that the syntactic expansion time of one macro system is the ordinary runtime of another block of code, and showed how to apply interleaved expansion and parsing in a non-parenthesized language. A number of languages other than Scheme either implement hygienic macros or implement partially hygienic systems. Examples include Scala,
Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous ferric oxides, hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxi ...
,
Elixir An elixir is a sweet liquid used for medical purposes, to be taken orally and intended to cure one's illness. When used as a pharmaceutical preparation, an elixir contains at least one active ingredient An active ingredient is the ingredient ...
,
Julia Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio (given name), Julio and Julius. (For further details on etymology, see wikt:Iulius#Latin, Wiktionary entry “Julius”.) The given name ''Julia'' had been ...
, Dylan,
Nim Nim is a mathematical game, mathematical game of strategy in which two players take turns removing (or "nimming") objects from distinct heaps or piles. On each turn, a player must remove at least one object, and may remove any number of objects ...
, and
Nemerle Nemerle is a general-purpose, high-level, statically typed In programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce various kinds of Input/output, outpu ...
.


Applications

; Evaluation order :Macro systems have a range of uses. Being able to choose the order of evaluation (see lazy evaluation and Strict function, non-strict functions) enables the creation of new syntactic constructs (e.g. control structures) indistinguishable from those built into the language. For instance, in a Lisp dialect that has cond but lacks if, it is possible to define the latter in terms of the former using macros. For example, Scheme has both continuations and hygienic macros, which enables a programmer to design their own control abstractions, such as looping and early exit constructs, without the need to build them into the language. ; Data sub-languages and domain-specific languages : Next, macros make it possible to define data languages that are immediately compiled into code, which means that constructs such as state machines can be implemented in a way that is both natural and efficient. ; Binding constructs :Macros can also be used to introduce new binding constructs. The most well-known example is the transformation of let into the application of a function to a set of arguments. Matthias Felleisen, Felleisen conjectures
Matthias Felleisen, LL1 mailing list posting
that these three categories make up the primary legitimate uses of macros in such a system. Others have proposed alternative uses of macros, such as anaphoric macros in macro systems that are unhygienic or allow selective unhygienic transformation. The interaction of macros and other language features has been a productive area of research. For example, Software component, components and Modular programming, modules are useful for large-scale programming, but the interaction of macros and these other constructs must be defined for their use together. Module and component-systems that can interact with macros have been proposed for Scheme and other languages with macros. For example, the Racket (programming language), Racket language extends the notion of a macro system to a syntactic tower, where macros can be written in languages including macros, using hygiene to ensure that syntactic layers are distinct and allowing modules to export macros to other modules.


Macros for machine-independent software

Macros are normally used to map a short string (macro invocation) to a longer sequence of instructions. Another, less common, use of macros is to do the reverse: to map a sequence of instructions to a macro string. This was the approach taken by the STAGE2 Mobile Programming System, which used a rudimentary macro compiler (called SIMCMP) to map the specific instruction set of a given computer into ''machine-independent'' macros. Applications (notably compilers) written in these machine-independent macros can then be run without change on any computer equipped with the rudimentary macro compiler. The first application run in such a context is a more sophisticated and powerful macro compiler, written in the machine-independent macro language. This macro compiler is applied to itself, in a Bootstrapping (computing), bootstrap fashion, to produce a compiled and much more efficient version of itself. The advantage of this approach is that complex applications can be ported from one computer to a very different computer with very little effort (for each target machine architecture, just the writing of the rudimentary macro compiler). The advent of modern programming languages, notably C, for which compilers are available on virtually all computers, has rendered such an approach superfluous. This was, however, one of the first instances (if not the first) of Bootstrapping (compilers), compiler bootstrapping.


Assembly language

While ''macro instructions'' can be defined by a programmer for any set of native assembler program instructions, typically macros are associated with macro libraries delivered with the operating system allowing access to operating system functions such as * peripheral access by access methods (including macros such as OPEN, CLOSE, READ and WRITE) * operating system functions such as ATTACH, WAIT and POST for subtask creation and synchronization. Typically such macros expand into executable code, e.g., for the EXIT macroinstruction, * a list of ''define constant'' instructions, e.g., for the Data Control Block, DCB macro—DTF (Define The File) for DOS/360 and successors, DOS—or a combination of code and constants, with the details of the expansion depending on the parameters of the macro instruction (such as a reference to a file and a data area for a READ instruction); * the executable code often terminated in either a ''branch and link register'' instruction to call a routine, or a supervisor call instruction to call an operating system function directly. * Generating a ''Stage 2'' job stream for System Generation (OS), system generation in, e.g., OS/360. Unlike typical macros, sysgen stage 1 macros do not generate data or code to be loaded into storage, but rather use the PUNCH statement to output JCL and associated data. In older operating systems such as those used on IBM mainframes, full operating system functionality was only available to assembler language programs, not to high level language programs (unless assembly language subroutines were used, of course), as the standard macro instructions did not always have counterparts in routines available to high-level languages.


History

In the mid-1950s, when
assembly language In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task. Programming involves tasks such as analysis, gene ...
programming was commonly used to write programs for digital computers, the use of macro instructions was initiated for two main purposes: to reduce the amount of program coding that had to be written by generating several assembly language statements from one macro instruction and to enforce program writing standards, e.g. specifying input/output commands in standard ways. Macro instructions were effectively a middle step between assembly language programming and the high-level programming languages that followed, such as FORTRAN and COBOL. Two of the earliest programming installations to develop "macro languages" for the IBM 705 computer were at Dow Chemical Corp. in Delaware and the Air Material Command, Ballistics Missile Logistics Office in California. A macro instruction written in the format of the target assembly language would be processed by a macro compiler, which was a pre-processor to the assembler, to generate one or more assembly language instructions to be processed next by the assembler program that would translate the assembly language instructions into machine language instructions. By the late 1950s the macro language was followed by the Macro Assemblers. This was a combination of both where one program served both functions, that of a macro pre-processor and an assembler in the same package. In 1959, Douglas E. Eastwood and Douglas McIlroy of Bell Labs introduced conditional and recursive macros into the popular Symbolic Assembly Program, SAP assembler, creating what is known as Macro SAP. McIlroy's 1960 paper was seminal in the area of extending any (including high-level programming language, high-level) programming languages through general-purpose macro processor, macro processors. Macro Assemblers allowed assembly language programmers to implement their own macro-language and allowed limited portability of code between two machines running the same CPU but different operating systems, for example, early versions of MSDOS and CPM-86. The macro library would need to be written for each target machine but not the overall assembly language program. Note that more powerful macro assemblers allowed use of conditional assembly constructs in macro instructions that could generate different code on different machines or different operating systems, reducing the need for multiple libraries. In the 1980s and early 1990s, desktop PCs were only running at a few MHz and assembly language routines were commonly used to speed up programs written in C, Fortran, Pascal and others. These languages, at the time, used different calling conventions. Macros could be used to interface routines written in assembly language to the front end of applications written in almost any language. Again, the basic assembly language code remained the same, only the macro libraries needed to be written for each target language. In modern operating systems such as Unix and its derivatives, operating system access is provided through subroutines, usually provided by dynamic libraries. High-level languages such as C offer comprehensive access to operating system functions, obviating the need for assembler language programs for such functionality.


See also

* s * (the origin of the concept of macros) * * s * * * Computer science and engineering * Computer science


References


External links


How to write Macro Instructions Rochester Institute of Technology, Professors Powerpoint
{{Authority control Programming constructs Source code Automation software Computer science